text
stringlengths 28
935k
| meta
stringlengths 137
139
| red_pajama_subset
stringclasses 1
value |
---|---|---|
\section{Introduction}
\label{sec1}
A common experimental design in clinical studies, especially longitudinal ones, is the matched pairs design where observations are made from the same subjects under two different conditions, often at two points in time, before and after treatment, or after a fixed period of time from the baseline. Revealing the possible dependence structure of the observations is a major goal. However, a typical issue when dealing with paired data is the occurrence of missing data. The challenge is to exploit the available data to perform valid inference.
The literature on matched pairs with missing data has primarily focused on one-dimensional, continuous, discrete or ordinal variables, aimed at detecting changes in location/mean \cite{ekbohm1976comparing,guo2017comparative,martinez2013hypothesis,xu2012accurate}, scale/variance \cite{derrick2018tests}, and distribution \cite{gaigall2020testing}. Some of the proposals apply multiple imputation techniques \cite{akritas2002nonparametric,akritas2006nonparametric,verbeke2009}, but they often require large sample sizes for being correct. Other proposals rely on specific model assumptions such as symmetry or bivariate normality \cite{ekbohm1976comparing,samawi2011,xu2012accurate}, but they exhibit a non-robust behavior against deviations. The common approach recently adopted in literature results from combining in a non parametric approach separate test statistics for the paired and unpaired observations, by using either weighted test statistics \cite{amro2017permuting,fong2018rank,gaigall2020testing,konietschke2012ranking,martinez2013hypothesis,samawi2014notes}, a multiplication combination test \cite{amro2019}, or combined p-values \cite{amro2021asymptotic,kuan2013,yu2012permutation,qi2019}
The recent scientific and technological progress in measuring biological processes has enabled monitoring of patient's condition with a growing level of detail and complexity. Thus, beyond the ongoing identification of univariate biomarkers, new complex data structures are being incorporated into the analysis, as is the case of population ages and mortality distributions \cite{bigot2017}, distributions of functional connectivity patterns in the brain \cite{dubey2020functional,petersen2016functional}, post-intracerebral hemorrhage hematoma densities \cite{petersen2021}, graph-based representations of connectivity and functional brain activity \cite{takerkart2014}, and glucose distributions from continuous monitoring \cite{matabuena2021glucodensities}.
The aim of the present paper is to provide a statistical test for matched pairs with missing data which does not require any parametric assumptions and uses all observations available. We propose new maximum mean discrepancy (MMD) estimators to achieve this aim \cite{gretton2012kernel}. The energy distance and the MMD are two equivalent statistical metrics with the ability to detect distributional differences between random samples \cite{szekely2013energy,shen2021exact}. Moreover, MMD-based statistics can also be seen as a natural generalization of the ANOVA test to cases where the distributions are not necessary Gaussian \cite{rizzo2010disco}. MMD overcomes Gaussian assumptions by representing distances between distributions as distances between mean embeddings in a reproducing kernel Hilbert space (RKHS). MMD has been successfully applied to independence testing \cite{szekely2007measuring}, two-sample testing \cite{gretton2012kernel}, survival analysis \cite{fernandez2019maximum}, or clustering analysis \cite{francca2021kernel}.
Besides conducting an extensive simulation study, the new testing procedures are applied to the AEGIS diabetes dataset, resulting from a longitudinal population-based study \cite{gude2017}. This dataset includes data from continuous glucose monitoring (CGM), performed at the beginning of the study and five years later. Importantly, there is a substantial loss to follow up. A distributional representation of glucose concentration summarizes several days of monitoring, providing a personal signature of glucose homeostasis \cite{matabuena2021glucodensities}. The present approach allows us to address some interesting questions related to the possible changes in CGM profile with ageing, or the relation between obesity and diabetes. Furthermore, an adaption of a previous clustering method to matched pairs with missing data allows us to find out specific patient phenotypes, with potential applications in patient stratification \cite{francca2021kernel}.
The rest of this paper is outlined as follows. In Section \ref{sec:glucodensities} we provide a motivation for the new methods from the distributional representation of CGM data. In Section \ref{sec:methods} we define the problem in general terms and introduce the statistical model based on the MMD metric, providing weighted test statistics for dealing with missing data under MCAR mechanism (Section \ref{sec:mcar}) and under MAR mechanism (Section \ref{sec:mar}). A proof presenting theoretical guarantees of the proposed methods is delivered in the appendix. In Section \ref{sec:kernel_choice} the choice of kernel functions and corresponding hyperparameters is discussed. Then we present the results of an extensive simulation study in Section \ref{sec:simulation_study}. In Section \ref{sec:cluster} a previous clustering method is adapted to missing data under the MAR mechanism. We present in Section \ref{sec:aegis} some applications of both hypothesis testing and clustering analysis to the AEGIS study, by exploiting the distributional representation of CGM data. We close with a discussion in Section \ref{sec:discussion}.
\section{Motivation: a distributional representation of continuous glucose monitoring data}
\label{sec:glucodensities}
Distributional data analysis is a novel methodology that has proved successful to manage biosensor data in different settings such as the connectivity analysis of the brain network \cite{petersen2016functional}, the diabetes management \cite{matabuena2021glucodensities}, and the physical activity analysis \cite{ghosal2021distributional,matabuena2021distributional}.
In a previous paper \cite{matabuena2021glucodensities}, we introduce a novel distributional representation for CGM data, termed glucodensity, which allows us to obtain a functional profile of patient glucose homeostasis. Glucodensity is a natural extension of Time in Range (TIR) metrics, that measures the proportion of time a person spends with their blood glucose levels within the target range of $70-180$ mg/dL \cite{battelino2019clinical,beck2019validation}. Although very intuitive, TIR metrics have two main disadvantages: first, the range fits poorly depending on the characteristics of the population examined; second, there is a loss of information caused by the discretization of the recorded data into intervals. Instead, glucodensity effectively measures the proportion of time each individual spends at a specific glucose concentration. Previous results for glucodensities show a better predictive performance as compared to common diabetes biomarkers.
Given a series of CGM data $\{Y_j\}_{j=1}^m$, the glucodensity can be modeled as a probability density function $f(\cdot)$ that can be approached by kernel density estimation:
\begin{equation}
\hat f(y)=\frac{1}{m}\sum _{j=1}^{m} \frac{1}{h} K\left(\frac{Y_j-y}{h}\right),
\end{equation}
where $h>0$ is the smoothing parameter and $k(\cdot)$ denotes a non-negative real-valued integrable function (Figure \ref{fig:gluco_overview}).
\begin{figure}[h]
\centering
\includegraphics[width=0.8\linewidth]{figures/glucodensity.pdf}
\caption{Left: The CGM recording from a normoglycemic patient. Right: The corresponding glucodensity.
}
\label{fig:gluco_overview}
\end{figure}
Let $\mathcal{D}$ be the space of probability density functions $f$ such that $\int _{\mathbb{R}}u^2f(u)du <\infty$. In order to measure the difference between two glucodensities, $f$ and $g$, a metric on $\mathcal{D}$ is required. We use the $2-$Wasserstein distance:
\begin{equation}
d^2_{\mathcal{W}_2}(f,g)= \int_{0}^{1} \left|Q_{f}\left(t\right)-Q_{g}\left(t\right)\right|^{2}dt, \quad f, g\in \mathcal{D},
\label{eq:wasserstein}
\end{equation}
where $Q_{f}$ and $Q_{g}$ denote the corresponding quantile functions. The $2$-Wasserstein distance in (\ref{eq:wasserstein}) depends only on quantile functions, so we can approximate it by computing empirical quantile functions $\hat{Q}_f=\hat{F}^{-1}$ and $\hat{Q}_g=\hat{G}^{-1}$, from the corresponding empirical cumulative distribution functions $\hat{F}$ and $\hat{G}$.
Figure \ref{fig:glucodensity_changes} contains an example of the glucodensity representation for the continuous glucose monitoring performed on three different individuals, both in a prediabetes and later diabetes status. This figure immediately poses the challenge of defining new statistical methods to compare two sets of glucodensity measurements to assess whether some population statistics differ. This can be useful to compare the glucose homeostasis before and after a treatment, or after a certain period of time.
\begin{figure}[ht!]
\centering
\includegraphics[width=0.6\linewidth]{figures/glucodensity_changes_prediabetic.pdf}
\caption{Glucodensity changes in prediabetic patients (blue) who develope diabetes after $5$ years (red).}
\label{fig:glucodensity_changes}
\end{figure}
\section{Hypotheses and statistics}
\label{sec:methods}
Let $\mathcal{D}$ be a separable Hilbert space and $\left(X_{1},X_{2}\right)^\top \in \mathcal{D}^2$ a random pair representing two different measurements on a subject at two different time points. Let us consider a general matched pairs design given by i.i.d. random variables
\begin{equation}
\mathbf{X}_j=\begin{pmatrix} X_{1j} \\ X_{2j} \end{pmatrix}, ~ j=1,...,n.
\end{equation}
To continue the example of our motivation, $X_{1j}$ can represent the glucodensity at the beginning of a certain study for the j-th patient, and $X_{2j}$ the glucodensity at the end of the study for the same patient. Let assume that both $\{X_{1j}\}_{j=1}^n$ and $\{X_{2j}\}_{j=1}^n$ are drawn from probability measures $P_1$ and $P_2$, respectively. We are interested in testing the equality of distributions as null hypothesis $H_{0}:\{P_{1} = P_{2}\}$ against the alternative $H_{1}:\{ P_{1} \neq P_{2}\}$, i.e., to check whether there are systematical differences between the outcomes at different time points.
\subsection{Missing Completely at Random (MCAR) mechanism}
\label{sec:mcar}
When some of the elements of the matched pairs are missing completely at random the available data can be sorted as:
\begin{equation}
\mathbf{X}=\underbrace{\begin{pmatrix} X_{11} \\ X_{21} \end{pmatrix} \cdots \begin{pmatrix} X_{1n_1} \\ X_{2n_1} \end{pmatrix}}_{
\substack{\text{Complete data $\mathbf{X}^{\text{com}}$} \\ \text{$n_1$ observations}}}
\hspace{0.2cm} \underbrace{\begin{pmatrix} X_{1n_{1+1}} \\ - \end{pmatrix} \cdots \begin{pmatrix} X_{1n_1+n_2} \\ - \end{pmatrix}}_{
\substack{\text{Incomplete data $\mathbf{X}^{\text{inc}}_1$} \\ \text{$n_2$ observations}}} \hspace{0.2cm} \underbrace{\begin{pmatrix} - \\ X_{2 n_1+n_2+1} \end{pmatrix} \cdots \begin{pmatrix} - \\ X_{2 n_1+n_2+n_3} \end{pmatrix}}_{
\substack{\text{Incomplete data $\mathbf{X}^{\text{inc}}_2$} \\ \text{$n_3$ observations}}}, \\
\end{equation}
where $n=n_1+n_2+n_3$. For ease of notation, we denote $\mathbf{X}^{\text{com}}_1=\{X_{1j}\}_{j=1}^{n_1}$, $\mathbf{X}^{\text{com}}_2=\{X_{2j}\}_{j=1}^{n_1}$, $\mathbf{X}^{\text{inc}}_1=\{X_{1j}\}_{j=n_1+1}^{n_1+n_2}$ and $\mathbf{X}^{\text{inc}}_2=\{X_{2j}\}_{j=n_1+n_2+1}^{n}$. Additionally, a missingness status variable can be defined
$\delta_{ij}\in \{0,1\}$, $i=1,2$, $j=1,\dots, n$, so $\delta_{ij}=1$ if the element is missing and $\delta_{ij}=0$ otherwise.
A natural way of testing the equality of distributions is measuring the distance between them. We propose two test statistics: $\mathcal{T}_1$ for the complete data sets $\mathbf{X}^{\text{com}}_1$ and $\mathbf{X}^{\text{com}}_2$, and $\mathcal{T}_2$ for the incomplete data sets $\mathbf{X}^{\text{inc}}_1$ and $\mathbf{X}^{\text{inc}}_2$, which are then combined in one weighted test statistic:
\begin{equation}
\mathcal{T}(\mathbf{X})= \alpha \mathcal{T}_1(\mathbf{X}^{\text{com}}_1,\mathbf{X}^{\text{com}}_2)+(1-\alpha) \mathcal{T}_2(\mathbf{X}^{\text{inc}}_1,\mathbf{X}^{\text{inc}}_2),
\label{eq:test_statistic}
\end{equation}
for some weighting parameter $\alpha \in \left[0,1\right]$. Both $\mathcal{T}_1$ and $\mathcal{T}_2$ are based on the maximum mean discrepancy (MMD) to measure the empirical distance between the marginal distributions \cite{gretton2012kernel}. Let $k: \mathcal{D}\times \mathcal{D} \to \mathbb{R}^{+}$ be a symmetric definite positive kernel. The existence of a dot product space $\mathcal{H}$ and feature mapping $\phi: \mathcal{D} \to \mathcal{H}$ is guaranteed, such that $k(X,X')=\langle \phi(X),\phi(X')\rangle_{\mathcal{H}}$. A reproducing kernel of $\mathcal{H}$ is a kernel function that satisfies (1) $\forall X\in \mathcal{D}$, $k(\cdot,X)\in \mathcal{H}$, and (2) $\forall X\in \mathcal{D}$, $\forall g\in \mathcal{H}$, $\langle g,k(\cdot,X) \rangle_{\mathcal{H}}=g(X)$. $\mathcal{H}$ is then said to be a reproducing kernel Hilbert space (RKHS). Kernel mean embedding results from extending the mapping $\phi$ to the space of probability distributions by representing each distribution as a mean function $\phi(F) = \mathbf{E}[k(\cdot,X)] = \int_{\mathcal{D}} k(\cdot,X)dP$. The kernel mean embedding can be empirically estimated by $\widetilde{\phi}= \frac{1}{n}\sum_{i=1}^{n}k\left(\cdot, X\right)$. Then, we can measure the distance between random samples as follows:
\begin{align*}
\mathcal{T}_1\left(\mathbf{X}^{\text{com}}_1,\mathbf{X}^{\text{com}}_2\right)&= \norm{\widetilde{\phi}^{\text{com}}_{1}-\widetilde{\phi}^{\text{com}}_{2}}_{\mathcal{H}}^{2}\\
&= \langle \frac{1}{n_1}\sum_{i=1}^{n_1}k\left(\cdot, X_{1i}\right)-\frac{1}{n_1}\sum_{i=1}^{n_1}k\left(\cdot, X_{2i}\right), \frac{1}{n_1}\sum_{i=1}^{n_1}k\left(\cdot, X_{1i}\right)-\frac{1}{n_1}\sum_{i=1}^{n_1}k\left(\cdot, X_{2i}\right) \rangle \\
&=\frac{1}{n_1^{2}} \sum_{i=1}^{n_1}\sum_{j=1}^{n_1} k\left(X_{1i},X_{1j}\right)+\frac{1}{n_1^{2}} \sum_{i=1}^{n_1}\sum_{j=1}^{n_1} k\left(X_{2i},X_{2j}\right)-\frac{2}{n_1^{2}} \sum_{i=1}^{n_1}\sum_{j=1}^{n_1}k\left(X_{1i},X_{2j}\right).
\end{align*}
Analogously,
\begin{align*}
\mathcal{T}_2\left(\mathbf{X}^{\text{inc}}_1,\mathbf{X}^{\text{inc}}_2\right) &= \norm{\widetilde{\phi}^{\text{inc}}_{1}-\widetilde{\phi}^{\text{inc}}_{2}}_{\mathcal{H}}^{2} \\
&=\frac{1}{n_2^{2}} \sum_{i=n_1+1}^{n_1+n_2} \sum_{j=n_1+1}^{n_1+n_2} k\left(X_{1i}, X_{1j}\right)+\frac{1}{n_3^{2}} \sum_{i=n_1+n_2+1}^{n_1+n_2+n_3} \sum_{j=n_1+n_2+1}^{n_1+n_2+n_3} k\left(X_{2i}, X_{2j}\right)\\
&\phantom{=}\,\,-\frac{2}{n_2n_3} \sum_{i=n_1+1}^{n_1+n_2} \sum_{j=n_1+n_2+1}^{n_1+n_2+n_3} k\left(X_{1i},X_{2j}\right).
\end{align*}
Importantly, for the class of {\em characteristic} kernels, the embeddings are injective, and hence $\norm{P_{1}-P_{2}}_{\mathcal{H}}^{2} = 0$, if and only if $P_1 = P_2$ \cite{sriperumbudur2011universality}.
In order to calibrate the tests under the null hypothesis it should be pointed out that both $\mathcal{T}_1$ and $\mathcal{T}_2$ do not follow a free asymptotic distribution. The empirical estimate of MMD is a one-sample V-statistics and hence asymptotic distribution is difficult to obtain due to the degeneracy of V-statistics, which incorporates a correlation structure for the complete paired observations $\mathbf{X}^{\text{com}}$ \cite{gretton2012kernel}. To address this issue we propose a wild bootstrap procedure for the first $n_1$ observations, while the remaining $n_2+n_3$ observations can be properly handled by permutations methods, that can achieve an exact type I error control. For each $b=1,\dots,B$, it proceeds as follows:
\begin{enumerate}
\item For the first $n_1$ complete paired observations, take random weights $w^b_{i}$, $i=1,\dots, n_1$, with
\begin{align*}
w^b_{i}= e^{-1/l_{n_1}}w^{b}_{i-1}+\sqrt{1-e^{-2/l_{n_1}}}\epsilon_i,
\end{align*}
where $w^b_0,\epsilon_1,\cdots, \epsilon_{n_1}$ are independent standard normal variables, and $l_{n_1}$ is a bootstrap parameter used to mimic the dependence structure, such that $l_{n_1}= o\left(n_1\right)$ but $ \lim_{n_1\to \infty} l_{n_1}=\infty$. Then,
\begin{align*}
\mathcal{T}^{b}_1\left(\mathbf{X}^{\text{com}}_1,\mathbf{X}^{\text{com}}_2\right)= \frac{1}{n_1^{2}} \sum_{i=1}^{n_1}\sum_{j=1}^{n_1} w^b_{i} w^b_{j} \left[ k\left(X_{1i},X_{1j}\right)+ k\left(X_{2i},X_{2j}\right)-2k\left(X_{1i},X_{2j}\right) \right].
\end{align*}
\item The remaining $n_2+n_3$ observations belonging to $\mathbf{X}^{\text{inc}}_1$ and $\mathbf{X}^{\text{inc}}_2$ are randomly permuted, i.e. each observation is randomly assigned to new $\mathbf{X}^{\text{inc},\pi}_1$ or $\mathbf{X}^{\text{inc},\pi}_2$ sets, resulting in new $\mathcal{T}_2^b(\mathbf{X}^{\text{inc},\pi}_1,\mathbf{X}^{\text{inc},\pi}_2)$.
\item Then, calculate
\begin{align*}
\mathcal{T}^{b}= \alpha \mathcal{T}^{b}_1 \left(\mathbf{X}^{\text{com}}_1,\mathbf{X}^{\text{com}}_2 \right)+(1-\alpha)\mathcal{T}_2^b\left(\mathbf{X}^{\text{inc},\pi}_1,\mathbf{X}^{\text{inc},\pi}_2\right)
\end{align*}
\end{enumerate}
Finally, return $p$-value$= \frac{1}{B} \sum_{b=1}^{B} 1\{ \mathcal{T}^{b} \geq \mathcal{T}(\mathbf{X})\}$.
\begin{theorem}
\label{pre:1}
Let $\mathbf{X}^{\text{com}}=\{\left(X_{1i}, X_{2i}\right)^{\top}\}^{n_1}_{i=1}$ be a set of i.i.d. complete paired samples, and $\mathbf{X}^{\text{inc}}_1=\{X_{1i}\}^{n_1+n_2}_{i=n_1+1}$, and $\mathbf{X}^{\text{inc}}_2=\{X_{2i}\}^{n_1+n_2+n_3}_{i=n_1+n_2+1}$ two sets of i.i.d. incomplete paired samples. Let suppose that $n_1/\left(n_1+n_2+n_3\right)\to\kappa_1\in \left(0,1\right)$ and $n_2/(n_2+n_3)\to \kappa_2 \in \left(0,1\right)$ as $n_1,n_2,n_3\to \infty$; then, the test statistic given by (\ref{eq:test_statistic}) is consistent against the alternative $H_{1}: \{P_{1} \neq P_{2}\}$; we can detect a difference in distribution with the sample size growing to infinity. Furthermore, the calibration strategy described above is also consistent in the same sense.
\end{theorem}
\subsection{Missing at Random (MAR) mechanism}
\label{sec:mar}
We assume a MAR mechanism where the probability of being missing on the second time point is based on the corresponding
value on the first time point, which can be described as follows
\begin{equation}
\mathbf{X}=\underbrace{\begin{pmatrix} X_{11} \\ X_{21} \end{pmatrix} \cdots \begin{pmatrix} X_{1n_1} \\ X_{2n_1} \end{pmatrix}}_{
\substack{\text{Complete data $\mathbf{X}^{\text{com}}$} \\ \text{$n_1$ observations}}}
\hspace{0.2cm} \underbrace{\begin{pmatrix} X_{1n_1+1} \\ - \end{pmatrix} \cdots \begin{pmatrix} X_{1n_1+n_2} \\ - \end{pmatrix}}_{
\substack{\text{Incomplete data $\mathbf{X}^{\text{inc}}_1$} \\ \text{$n_2$ observations}}}, \\
\end{equation}
where $n=n_1 + n_2$. We denote by $\pi\left(\cdot\right)= P\left(\delta_{2j}=1 |X_{1j}=\cdot\right)$, the conditional probability that the observation $X_{2j}$ will be missing given $X_{1j}$. A natural way to incorporate the missing data mechanism in the test statistic is to associate weight $\omega_j$ with the $j$-th observation via an inverse probability weighting (IPW) estimator \cite{tsiatis2007semiparametric}, given by
\begin{equation}
\omega_j= \frac{\delta_{2j}}{n\pi\left(X_{1j}\right)},~ j = 1,\dots, n.
\label{eq:weights}
\end{equation}
In practice, we estimate the probability $\pi(\cdot)$ by means of a binary classification algorithm. We denote by $\tilde{\omega}_j$ the estimated weight. We propose the following test statistic
\begin{align*}
\mathcal{T}\left(\mathbf{X}\right) &= \mathcal{T}\left(\mathbf{X}^{\text{com}}_1,\mathbf{X}^{\text{com}}_2\right) =\norm{\widetilde{\phi}^{\text{com}}_{1}-\widetilde{\phi}^{\text{com}}_{2}}_{\mathcal{H}}^{2}\\
&= \langle \sum_{j=1}^{n_1} \tilde{\omega}_j k\left(\cdot, X_{1j}\right)-\sum_{j=1}^{n_1} \tilde{\omega}_j k\left(\cdot, X_{2j}\right), \sum_{j=1}^{n_1} \tilde{\omega}_j k\left(\cdot, X_{1j}\right)-\sum_{j=1}^{n_1} \tilde{\omega}_j k\left(\cdot, X_{2j}\right) \rangle \\
&= \sum_{i=1}^{n_1}\sum_{j=1}^{n_1} \tilde{\omega}_i \tilde{\omega}_j k\left(X_{1i},X_{2j}\right) + \sum_{i=1}^{n_1}\sum_{j=1}^{n_1} \tilde{\omega}_i \tilde{\omega}_j k\left(X_{1i},X_{2j}\right)- 2 \sum_{i=1}^{n_1}\sum_{j=1}^{n_1} \tilde{\omega}_i \tilde{\omega}_j k\left(X_{1i},X_{2j}\right).
\end{align*}
In this scenario, we propose to calibrate the test under the null hypothesis in an analogous manner to the MCAR mechanism. Specifically, for each bootstrap iteration we propose to use the following estimator
\begin{align*}
\mathcal{T}^{b}\left(\mathbf{X}\right) = \frac{1}{n_1^{2}} \sum_{i=1}^{n_1}\sum_{j=1}^{n_1} w^{b}_{i} w^{b}_{j} \tilde{\omega}_i \tilde{\omega}_j \left[ k\left(X_{1i},X_{1j}\right)+ k\left(X_{2i},X_{2j}\right)-2k\left(X_{1i},X_{2j}\right) \right].
\end{align*}
\subsection{Kernel choice and kernel hyperparameters}
\label{sec:kernel_choice}
We propose using the Gaussian kernel $k\left(X,Y\right)= e^{-\norm{X-Y}^{2}/\sigma^2}$ for $X,Y \in \mathbb{R}$, and $k\left(X,Y\right)= e^{-d^{2}_{\mathcal{W}_{2}}\left(X,Y\right)/ \sigma^2}$ for $X,Y \in \mathcal{D}$, where $\sigma>0$. Importantly, the Gaussian kernel is a characteristic kernel, and thus we can detect asymptotically any difference in distribution. The kernel bandwidth $\sigma$ was estimated through the median heuristic $\sigma ^2= median \{||X_i-X_j||^{2}:1\leq i< j\leq n \}$.
\subsection{Simulation study}
\label{sec:simulation_study}
We investigate the finite sample behavior of the above methods in extensive simulations. A total of $2,000$ simulations were performed for both MCAR and MAR scenarios. Methods were examined with respect to their Type-I error rate control at level 5\%. A total of $2,000$ bootstrap runs and permutation replicas were held. The wild bootstrap parameter $l_{n_1}$ was selected according to $l_{n_1}= \sqrt{n_1}$.
The observations were generated by mimicking the sort of distributional representations commonly obtained from CGM data. Since the 2-Wasserstein distance depends only on quantile functions, observations were sampled from the following location-scale model on quantile functions \cite{petersen2021}: let $Z\in \mathbb{R}^{p}$ be a random vector of predictor variables and let $Q_0$ be a fixed quantile function; here we considered the age as the only predictor variable and fixed $Q_0\left(t\right)= 70+240t$ in the range of glucose values expected from type-2 diabetes; let $\eta\left(z\right)= a_0+a_1z_1$ and $\tau\left(z\right)= b_0+b_1z_1$ be the location and scale components of the model, respectively, where $a= \left(a_0,a_{1}\right)$ and $b= \left(b_0, b_{1} \right)$ are the corresponding coefficients and we assume that $\tau\left(Z\right)>0$ almost surely; let $V_1$ and $V_2$ two random variables that satisfy $E\left(V_1|Z\right)=0, E\left(V_2|Z\right)=1$, and $V_2>0$ almost surely; the model is given by
\begin{equation}
Q\left(t\right)= V_1+V_2\eta\left(Z\right)+V_2\tau\left(Z\right)Q_0\left(t\right),
\end{equation}
\subsubsection{MCAR scenario.}
\label{sec:sim_mcar}
We fixed $n_1=n_2=n_3=150$. In order to introduce correlation structure into the quantile functions for $\mathbf{X}^{\text{com}}_1$ and $\mathbf{X}^{\text{com}}_2$, we sampled variables $V_1^*$ and $V_2^*$ from bivariate uniform distributions with correlation given by $\rho\in \{0.00,0.20,0.40,0.60,0.80\}$. The location-scale model is given by $V_1=-20+40V_1^*$ and $V_2= 0.8+0.4V_2^*$, and fixed parameters $a_0=b_0=0$, $a_1=0.3$ and $b_1=0.005$. The observations for $\mathbf{X}^{\text{inc}}_1$ and $\mathbf{X}^{\text{inc}}_2$ were i.i.d. generated and then we applied the same location-scale model than before. A total of $2,000$ simulations were performed assuming that the age was distributed as $Z_1,Z_2\sim \mathcal{U}_{[30,50]}$ both at the beginning and at the end of the study, that is, for all the variables in $\mathbf{X}$. Another $2,000$ simulations were performed assuming that the age was distributed as $Z_1\sim \mathcal{U}_{[30,50]}$ at the beginning of the study, that is, for all the variables in $\mathbf{X}^{\text{com}}_1$ and $\mathbf{X}^{\text{inc}}_1$, and was distributed as $Z_2\sim \mathcal{U}_{[50,70]}$ at the end of the study, that is, for all the variables in $\mathbf{X}^{\text{com}}_2$ and $\mathbf{X}^{\text{inc}}_2$.
\subsubsection{MAR scenario.}
\label{sec:sim_mar}
We fixed $n=300$. The missing mechanism is given by $P\left(\delta_{2j}=1|Y_1,Y_2\right)= (1+e^{-1+ Y_1+ Y_2})^{-1}$, $j=1,\dots, n$, where $Y_1,Y_2\sim \mathcal{N}\left(0,1\right)$ are two independent random variables. We introduced correlation structure into the quantile functions for $\mathbf{X}^{\text{com}}_1$ and $\mathbf{X}^{\text{com}}_2$ as we did in the MCAR scenario. We used the same location-scale model. The same methodology as in the MCAR scenario was applied for sampling the age.
\subsubsection{Results.}
Table \ref{table:tabla1} shows the results of the simulation study. We can see the test calibration under the null hypothesis is acceptable. However, there are some biases in the two situations due to missing data mechanisms. As the discrepancy of the null hypothesis increases, the test rejects the more null hypothesis, and in some cases, it is clear the consistency of the new methods with $100$ percent of reject cases.
\begin{table}[ht]
\centering
\begin{tabular}{ccccc}
\hline
$\rho$ & $Z_1$ & $Z_2$ & MCAR & MAR \\
\hline
$0.00$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[30,50]}$ & $0.03$ & $0.03$ \\
$0.20$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[30,50]}$ & $0.04$ & $0.03$ \\
$0.40$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[30,50]}$ & $0.05$ & $0.03$ \\
$0.60$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[30,50]}$ & $0.03$ & $0.04$ \\
$0.80$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[30,50]}$ & $0.04$ & $0.04$ \\
\hline
$0.00$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[50,70]}$ & $0.98$ & $0.88$ \\
$0.20$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[50,70]}$ & $0.99$ & $0.90$ \\
$0.40$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[50,70]}$ & $0.99$ & $0.91$ \\
$0.60$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[50,70]}$ & $0.99$ & $0.93$ \\
$0.80$ & $\mathcal{U}_{[30,50]}$ & $\mathcal{U}_{[50,70]}$ & $0.99$ & $0.96$ \\
\hline
\end{tabular}
\caption{The proportion of simulations rejecting the null hypothesis is shown under MCAR and MAR mechanisms.}
\label{table:tabla1}
\end{table}
\subsection{Paired missing data clustering}
\label{sec:cluster}
Let $\mathbf{X}=\left\{\left(X_{1j}, X_{2j}, \delta_{2j}\right)\right\}^{n}_{j=1}$, be a dataset of i.i.d. random variables obtained under a MAR mechanism, where we denote again by $\pi\left(\cdot\right)= P\left(\delta_{2j}=1 |X_{1j}=\cdot\right)$, the probability that the observation $X_{2j}$ will be missing. We associate a weight $\tilde{\omega}_j$ with the $j$-th observation via an IPW estimator, by applying equation (\ref{eq:weights}). Let $\mathbf{X}_j=(X_{1j},X_{2j})^{\top}$, $\mathbf{X}_h=(X_{1h},X_{2h})^{\top} \in \mathbf{X}^{\text{com}}$ be two different complete paired samples. We define the following bivariate kernel
$k\left(\mathbf{X}_j,\mathbf{X}_h\right)= e^{-\left(d^{2}_{\mathcal{W}_2}(X_{1j},X_{1h})+d^{2}_{\mathcal{W}_2}(X_{2j},X_{2h})\right)/\sigma^2}$, where $\sigma^2= median\{d^{2}_{\mathcal{W}_2}\left(X_{1j},X_{1h}\right)+d^{2}_{\mathcal{W}_2}\left(X_{2j},X_{2h} \right): 1\leq j<h\leq n \}$.
Consider a disjoint partition $\mathbf{X}^{\text{com}}=\bigcup _{i=1}^k C_i$, with $C_i\cap C_l=\emptyset$, for all $i\neq l$. Following \cite{francca2021kernel}, we aim to build a new partition $\tilde{C}_1,\dots, \tilde{C}_k$ by maximizing an objective function given by
\begin{equation}
\left(\tilde{C}_1,\dots, \tilde{C}_k\right)= \arg \max_{\left(C_1,\dots,C_{k}\right)} \sum_{i=1}^{k} \frac{1}{v_i} \sum_{\mathbf{X}_{j},\mathbf{X}_{h} \in C_i} \tilde{\omega}_j \tilde{\omega}_h k\left(\mathbf{X}_{j},\mathbf{X}_{h}\right),
\end{equation}
where $v_i= \sum_{\mathbf{X}_{j}\in \mathcal{C}_i} \tilde{\omega}_j$. We can iteratively solve this optimization problem by measuring the impact of moving each observation to another cluster. Let denote by $S_i= \sum_{\mathbf{X}_{j},\mathbf{X}_{h}\in C_i} \tilde{\omega}_j \tilde{\omega}_h k(\mathbf{X}_{j},\mathbf{X}_{h})$ the internal similarity of cluster $C_i$, and $S_i\left(\mathbf{X}_{j}\right)= \sum_{\mathbf{X}_{h} \in C_i} \tilde{\omega}_j \tilde{\omega}_h k(\mathbf{X}_{j},\mathbf{X}_{h})$ the internal similarity with respect to the observation $\mathbf{X}_{j}$. By moving the observation $\mathbf{X}_{j}$ from cluster $C_i$ to $C_l$ we change the result of the objective function by
\begin{equation}
\Delta S^{i\to l} \left(X_{2j}\right)= \frac{S^{+}_{l} }{v_l+ \tilde{\omega}_j} + \frac{S^{-}_{i}}{v_i- \tilde{\omega}_j}-\frac{S_{l}}{v_l}-\frac{S_{i}}{v_i},
\end{equation}
where $S_l^{+}= S_l+2S_l\left(\mathbf{X}_{j}\right)+\tilde{\omega}_j \tilde{\omega}_j k\left(\mathbf{X}_{j},\mathbf{X}_{j}\right)$ is the internal similarity of the new cluster $C_l$ after the addition of the observation $\mathbf{X}_{j}$, and $S_i^{-}= S_i-2S_i\left(\mathbf{X}_{j}\right)+\tilde{\omega}_j \tilde{\omega}_j k\left(\mathbf{X}_{j},\mathbf{X}_{j}\right)$ is the internal similarity of the new cluster $C_i$ after removing the observation $\mathbf{X}_{j}$. Ultimately, we compute $i^{*}= \arg \max_{l=1\dots,k|l\neq i} \Delta Q^{i\to l} \left(\mathbf{X}_{j}\right)$, and if $\Delta S^{i\to i^{*}}(\mathbf{X}_{j})>0$ we move $\mathbf{X}_{j}$ to cluster $C_{i^*}$, otherwise we keep it in $C_i$.
\section{Illustrative data analysis}
\label{sec:aegis}
As a practical application, we consider an ongoing longitudinal, population-based study by \cite{gude2017}, aimed at analyzing the evolution of different clinical biomarkers related to circulating glucose in a initial random sample of $1516$ patients over $10$ years. In addition, a CGM are performed every five years on a randomized subset of patients. Specifically, at the beginning of the study, $581$ participants were randomly selected for wearing a CGM device for $3$-$7$ days. Out of the total of $581$ participants, $68$ were diagnosed with diabetes before the study and $22$ during the first five years. Table \ref{tab:aegis_table} shows the baseline characteristics of these $581$ patients grouped by sex. After a five-year follow-up, only 161 participants agreed to perform a second glucose monitoring.
\begin{table}[ht!]
\centering
\begin{tabular}{lll}
\hline
& Men $(n=220)$ & Women $(n=361)$ \\
\hline
Age, years & $47.8\pm 14.8$ & $48.2\pm14.5$ \\
A1c, \% & $5.6\pm0.9$ & $5.5\pm0.7$ \\
FPG, mg/dl & $97\pm23$ & $91\pm21$ \\
HOMA-IR, mg/dl.$\mu$ IU/ml & $3.97\pm5.56$ & $2.74\pm2.47$ \\
BMI, kg/m$^2$ & $28.9\pm4.7$ & $27.7\pm5.3$ \\
CONGA, mg/dl & $0.88\pm0.40$ & $0.86\pm0.36$ \\
MAGE, mg/dl & $33.6\pm22.3$ & $31.2 \pm14.6$ \\
MODD & $0.84\pm0.58$ & $0.77\pm0.33$ \\
\hline
\end{tabular}
\caption{Baseline characteristics of AEGIS study participants with CGM monitoring by sex. Mean and standard deviation are shown. A1c: glycated hemoglobin; FPG: fasting plasma glucose; HOMA-IR: homeostasis model assessment-insulin resistance; BMI: body mass index; CONGA: glycemic variability in terms of continuous overall net glycemic action; MAGE: mean amplitude of glycemic excursions; MODD: mean of daily differences.}
\label{tab:aegis_table}
\end{table}
The AEGIS study raises some interesting questions that can be addressed with the present approach.
{\bf Changes in CGM profile with ageing}. Some recent works explore the important role of ageing in glucose dysregulation, and the difficulties inherent in maintaining glucose homeostasis as close to normal as possible \cite{chia2017}. The proposed $\mathcal{T}$-test gives us the opportunity to examine if there exist statistical differences after five years at a distributional level. We estimate the missing data mechanism by means of logistic regression, using as predictors the age and glycaemic status (normoglycemic, prediabetes or type-2 diabetes) at the beginning of the study and sex of each participant. We applied the $\mathcal{T}$-test considering glucodensities at both time points to check the null hypothesis of equality of distributions. We obtained a p-value = $0.048$, identifying significant differences at both time points.
{\bf Obesity in diabetes}. Obesity is a critical risk factor for the development of type-2 diabetes \cite{leong1999obesity}. In order to further characterize this risk subpopulation, we analyzed those normoglycemic subjects with overweight in the AEGIS dataset, by examining again if there exist statistical differences after five years at a distributional level. We applied the $\mathcal{T}$-test to check the null hypothesis in the following two subgroups of the normoglycemic population: i) individuals with a body mass index less than $22 Kg/m^{2}$ (low body mass index); ii) individuals with a body mass index higher than $22 Kg/m^{2}$ (overweight and obesity). In the first case we obtained a $p$-value = $0.36$, providing no evidence against the null hypothesis, while in the second case we obtained a $p$-value = $0.056$, which can be interpreted as borderline. Figure \ref{fig:obesity} shows the difference between the quantile curves in these two subgroups.
\begin{figure}[ht!]
\centering
\includegraphics[width=0.7\linewidth]{figures/obesidad.pdf}
\caption{Difference between the quantile curves (before and after) in normoglycemic individuals according to body mass status. The dispersion is more significant for the overweight and obesity subgroup, consistent with an increasing glycemic risk.}
\label{fig:obesity}
\end{figure}
{\bf Patient stratification}. Clustering analysis can be a useful tool for providing distinctive and meaningful patient phenotypes and, consequently, in guiding patient stratification for delivering more personalized care \cite{kosorok2019precision}. We applied a clustering analysis to those individuals for whom CGM has been performed at both time points. Figure \ref{fig:clustering} shows the resulting two clusters. The individuals in cluster $1$ do not present significant changes between both time points, while some significant differences are noted in cluster $2$. Table \ref{table:groups} shows the baseline clinical characteristics of each cluster. Both groups of individuals have important differences in insulin resistance and glycaemic variability metrics. Importantly, in cluster 2 the average glycaemic characteristics in terms of glycated hemoglobin and fasting plasma glucose are consistent with prediabetes (5.7\% $\leq$ A1c $\leq$ 6.4\% or 100 mg/dl $\leq$ FPG $\leq$ 125 mg/dl according to American Diabetes Association guidelines). In contrast, cluster 1 is composed of normoglycemic individuals. Ultimately, clustering results effectively correlates with a significant change in the glycaemic status.
Finally, we performed stepwise logistic regression with forward selection to identify which baseline characteristics independently predicted the corresponding group, resulting age, FPG and CONGA. We checked the null hypothesis that each coefficient is equal to zero. Table \ref{table:stepwise} shows the results of this analysis, identifying FPG and CONGA as the subset of characteristics that best predicted the outcome.
\begin{figure}[ht!]
\centering
\includegraphics[width=0.7\linewidth]{figures/graficoclustering.pdf}
\caption{Resulting clusters are shown. Both quantile curves at the beginning of the study (blue) and five years later (orange) are shown for each cluster.}
\label{fig:clustering}
\end{figure}
\begin{table}[ht!]
\centering
\begin{tabular}{lll}
\hline
& cluster 1 & cluster 2 \\
\hline
Age (years decimal) & $43.66\pm 12.80$ & $53.11\pm 12.34$ \\
A1c, \% & $5.27\pm 0.25$ & $6.20 \pm 1.07$ \\
FPG, mg/dl & $84.83 \pm 9.93$ & $108.39 \pm 32.61$ \\
HOMA-IR, mg/dl.$\mu$ IU/ml& $2.28 \pm 1.16$ & $4.97 \pm 8.50$ \\
BMI, kg/m$^2$ & $27.09 \pm 4.87$ & $29.29\pm 4.83$ \\
Waist, cm & $87.29 \pm 13.60$ & $95.18 \pm 14.43$ \\
CONGA, mg/dl & $0.75 \pm 0.20$ & $1.21 \pm 0.52$ \\
MAGE, mg/dl & $26.16 \pm 7.16$ & $45.80\pm 24.58$ \\
MODD & $0.66 \pm 0.18$ & $1.05 \pm 0.48$ \\
\hline
\end{tabular}
\caption{Clinical baseline characteristics for the individuals belonging to each cluster. Mean and standard deviation are shown.}
\label{table:groups}
\end{table}
\begin{table}[ht!]
\begin{center}
\begin{tabular}{l c}
\hline
& Coefficients \\
\hline
(Intercept) & $-10.01$ $(1.82)^{***}$ \\
age & $0.04$ $(0.02)$ \\
FPG & $0.05$ $(0.02)^{**}$ \\
CONGA & $3.60$ $(0.91)^{***}$ \\
\hline
& Quality measures \\
\hline
AIC & $140.37$ \\
BIC & $152.69$ \\
Log Likelihood & $-66.18$ \\
Deviance & $132.37$ \\
\hline
\multicolumn{2}{l}{ $^{***}p<0.001$; $^{**}p<0.01$}
\end{tabular}
\caption{Coefficients obtained from logistic regression. Results from some different model selection criteria for the fitted model are shown.}
\label{table:stepwise}
\end{center}
\end{table}
\section{Discussion}
\label{sec:discussion}
The analysis of paired data with missing values is becoming critical in longitudinal studies, particularly when comparing the participants' condition across different time points. The available methods in the literature are not applicable when data adopt non-vectorial representations, better suited to capture functional, structural or other complex forms of information increasingly common in current medicine. To overcome this limitation we have provided novel methods for hypothesis testing in the presence of complex paired missing data under both MCAR and MAR mechanisms. They are not based on any parametric assumption and use all observations within the matched pairs design. The methods are based on the notion of maximum mean discrepancy, a metric between mean embeddings in a RKHS that can be applied to both Euclidean and non-Euclidean data, with different structured, functional and distributional representations, by an appropriate design of the reproducing kernel. Specifically, the space of probability density functions has been used throughout the text to test the feasibility of this approach.
The asymptotic validity of the methods was proven and can be found in the appendix. In an extensive simulation study, the type-I error rate control of the tests has been examined under both MCAR and MAR mechanisms, performing well with different correlation coefficients. The sample size affects the behavior of the tests, since inference in a functional space customarily demands more data than in a vectorial space. Hence a worsening of performance is expected for very small sample sizes.
The application of these methods to a real longitudinal, population-based, diabetes study has highlighted some of their capabilities and advantages to explore new clinical findings, by exploiting monitoring information along the continuous range of glucose values. It should be emphasized the robustness of the results, even in an scenario with an important proportion of missing data. Furthermore, a complementary clustering analysis has revealed the effectiveness of this approach to provide an early risk identification with the potential to enable a personalized strategy.
In order to simplify the application of these methods, they are freely available on GitHub
(https://github.com/).
\section*{Acknowledgments}
Funding for the project was provided by the .
| {'timestamp': '2022-06-06T02:15:00', 'yymm': '2206', 'arxiv_id': '2206.01590', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01590'} | arxiv |
\subsubsection{Decision guide S2}
\label{ssec:dg2}
\hfill\\\noindent\textbf{D2.1: \ac{MCC} versus \ac{BA}} \\
We follow the recommendations of Chicco et al. \cite{chicco2021matthews}, who suggest \ac{MCC} as the default metric to assess classification performance with a single score. In binary classification problems, a high \ac{MCC} value implies good results for all four basic rates of the confusion matrix (\ac{TPR}, \ac{TNR}, \ac{PPV}, \ac{NPV}) as well as a high F$_1$ Score, Accuracy and \ac{BA} \citep{chicco2021matthews}. Furthermore, \ac{MCC} is insensitive to which class is defined as the positive class, and its values are relatively well-interpretable with 0 indicating the performance of a random classifier and 1 reflecting perfect performance. On the other hand, the achievable \ac{MCC} values depend crucially on the prevalence~\citep{chicco2021matthews}. Furthermore, \ac{MCC} is generally not suitable if an unequal treatment of classes is requested (see F2.5.1). The weighted versions of \ac{BA} or the (mathematically almost identical) Youden's Index can be used to address these issues. An open research question, however, is how to best assess the accuracy of multi-class algorithms in the presence of ordinal data (i.e. when an unequal handling of class confusions is requested; F2.5.2). Note that weighted Cohen's Kappa has been proposed to address this issue. However, Kappa statistics in general have originally been proposed for assessing inter-rater reliability and come with various problems in the context of performance assessment \citep{chicco2021matthews}. Despite their popularity as chance-corrected alternatives to accuracy we thus do not recommend them in our framework. Furthermore, the properties of all of the multi-class metrics have not been studies well for non-binary classification problems.
\subsubsection{Decision guide S3}
\label{ssec:dg3}
\hfill\\\noindent\textbf{D3.1: \ac{TN}-based metrics versus non-\ac{TN}-based metrics} \\
The following aspects should be taken into account when deciding between \ac{AUROC} (operating on the full confusion matrix) and \ac{AP} (disregarding TN):
\begin{itemize}
\item \textbf{Problem statement:} Whether or not to validate classification tasks with \ac{TN}-based metrics is among the most controversial issues in metric selection, currently resulting in heterogeneous practices across the biomedical image analysis community. This is because typical validation combines the aspect of Sensitivity with the aspect of either Specificity (\ac{TN}-based), or \ac{PPV} (non-\ac{TN}-based). Often, the two aspects are not reported individually, but combined into a single score. Thus, the choice between Specificity and \ac{PPV} (or \ac{TN}-based versus non-\ac{TN}-based) represents the basis for further choices, e.g. between common per-class counting metrics such as F$_\beta$ Score (\ac{PPV}-based / non-\ac{TN}-based) and \ac{LR+} (Specificity-based / \ac{TN}-based) or common multi-threshold metrics such as \ac{AUROC} (Specificity-based / \ac{TN}-based) and \ac{AP} (\ac{PPV}-based / non-\ac{TN}-based) \footnote{Other relevant \ac{TN}-based metrics include Accuracy, \ac{BA} and \ac{MCC} while other non-\ac{TN}-based metrics include \ac{FROC} score and \ac{PQ}}. The crucial differences between these pairs are often reported to be in regard to tangible pitfalls such as dealing with class imbalance (e.g. \ac{AP} responding better to class imbalance than \ac{AUROC}). However, it is necessary to keep in mind that all these differences can in fact be traced back to whether a metric is based on \ac{TN}.
\item \textbf{How to decide whether to validate with \ac{TN} or not?} As this discussion is limited to per-class validation (either binary classification, or “One versus Rest” / “One versus One” schemes for multi-class classification \cite{hand2001simple}), associated metrics define a positive (P) and a negative class (N) and a subsequent two-class confusion matrix (\ac{TP}, \ac{FP}, \ac{TN}, \ac{FN}). The fundamental difference between \ac{TN}-based and non-\ac{TN}-based metrics boils down to the question: Is there a focus on the positive class or are the two classes of equal interest (F2.5.2)? \ac{TN}-based metrics (Sensitivity + Specificity, \ac{LR+}, \ac{AUROC}) consider the entire confusion matrix and thus reflect a symmetric interest in both classes. Non-\ac{TN}-based metrics (Sensitivity + \ac{PPV}, F$_\beta$ Score, \ac{AP}) only consider three quarters of the confusion matrix and thus reflect an asymmetric interest shifted towards the positive class. In practice, information retrieval tasks (special interest in the queried class) are often distinguished from classification tasks (interest in both classes). A retrieval task could be to query images featuring a certain phenomenon from a large database. In this case, the focus is on low \ac{FP} in the queried images, i.e. on \ac{PPV}, which is a non-\ac{TN}-based metric. As an example that can be interpreted both ways, consider the task of cancer detection on image level (“cancer or no cancer?”). While the interest in the two errors \ac{FP} (false alarm) and \ac{FN} (missed cancer) is obvious, the question is: Should the metric score of the classifier increase when an image without cancer is added to the data set and the classifier predicts that correctly (\ac{TN})? In favour of \ac{TN}-based metrics one could argue that any correct decision should increase the validation score, while in favour of non-\ac{TN}-based metrics (information retrieval perspective) one could argue that the task is to detect cancer and not to detect non-cancer. The second argument becomes stronger in the case of highly imbalanced data sets, where the aspect of cancer detection performance shrinks in comparison to the aspect of correctly identifying non-cancer. For "One versus Rest" settings in multi-class scenarios, one could argue to employ non-\ac{TN}-based metrics, since there is an inherent focus on the class defined as positive, and the “rest” often outweighs the single positive class in number of data cases (class imbalance, F4.1 \citep{mahani2019classification}).
\item \textbf{Dependencies on prevalence:} Prevalence is the ratio of the positive class $P / (P+N)$ occurring in the data set. \ac{PPV}-based metrics such as F$_\beta$ Score and \ac{AP} depend on prevalence, whereas \textit{Specificity}-based metrics such as \ac{AUROC} and \ac{LR+} do not depend on prevalence. Thus, the former might be closer to quantities of interest for practitioners in the context of specific applications, while the latter exclusively represents the inherent properties of the classifier \textit{irrespective of prevalence in the data set} and might thus be more interesting to developers. Note that the independence of prevalence is often portrayed as a pitfall of \textit{Specificity}-based metrics because, counter-intuitively, they may yield high scores in scenarios with low prevalence and thus low \ac{PPV}. However, in certain cases independence of prevalence can be desired, e.g. when high variations in prevalence are expected in future applications of the model (e.g. due to varying data cohorts).
\end{itemize}
\noindent\textbf{D3.2: \ac{AP} versus \ac{FROC} Score} \\
The following aspects should be taken into account when deciding between \ac{AP} and \ac{FROC} Score:
\begin{itemize}
\item \textbf{Community preferences:} While \ac{AP} constitutes the undisputed standard metric for object detection and instance segmentation in the computer vision community, the \ac{FROC} Score is often favoured in the clinical context due to its easier interpretability despite its lack of standardization (employed \ac{FPPI} Scores vary across studies \cite{jin2020deep,bejnordi2017diagnostic,setio2017validation}). Thus, the decision between the two metrics often boils down to a decision between a standardized and technical validation versus an interpretable and application-focused validation.
\item \textbf{Data set size awareness:} In contrast to \ac{AP}, the \ac{FROC} Score takes into account the total number of images in the data set (see also Fig.~\ref{fig:ap-froc}). This property does not affect relative method comparison and can be related to the underlying question "at which scale are matched objects (cardinalities) aggregated / counted?". We discuss this question and implication for associated metrics in Sec. \ref{sec:pitf:fundamentals_od} (see also Fig.~\ref{fig:perimage-perdataset}). While \ac{AP} originally (i.e. in the computer vision community) counts matched objects over the entire data set (as opposed to per image), Sec.~\ref{sec:pitf:fundamentals_od} demonstrates how to apply \ac{AP} and other object detection metrics to (e.g. clinical) scenarios requiring per image aggregation. \ac{FROC} score is a hybrid metric in this context, where \textit{Sensitivity} is computed per data set while FP are averaged over single images (\ac{FPPI}).
\item \textbf{Dealing with low-confidence predictions:} It is often desired to filter low confidence predictions (e.g. objects with high confidence of being background) prior to metric computation. For \ac{AP} computation this requires a cutoff on the confidence score or upper limits of considered predictions per image or per data set. For \ac{FROC}, however, with typical values of \ac{FPPI}, such low-confidence predictions naturally go unconsidered, thus allowing to avoid additional filtering measures.
\item \textbf{\ac{FPPI}:} Different \ac{FPPI} values are used in the field for computing the FROC Score. A potential default are the values 1/8, 1/4, 1/2, 1, 2, 4, 8, as used for multiple popular benchmarks \cite{van2010comparing,setio2017validation}. Here, lower \ac{FPPI} values (smaller than one) are weighted equally to higher \ac{FPPI} values (greater than 1; four values each). Deviation from this weighting might be appropriate depending on the application, but should be explained. In the biostatistics community, areas under the curve are sometimes computed constraining the \ac{FPPI} range to [0,1] \cite{samuelson2006comparing}.
\end{itemize}
\noindent\textbf{D3.3: Predicted confidence scores and calibration} \\
A \textit{calibrated model} outputs predicted class scores (in this context interpreted as "confidence scores") that match the empirical success rate (e.g. outputs with score 0.8 for a specific class empirically belong to this class in $80\%$ of the cases). Since this requirement is defined over the entire data set, calibration represents a weaker requirement compared to requiring correct confidence outputs at the individual level. The latter corresponds to estimating the true posterior probability of the output label given the input data. The following aspects should be taken into account when deciding whether control on confidence values is required and at which level:
\begin{itemize}
\item \textbf{When to validate predicted confidence scores?} In the given context, we distinguish two primary use cases:
\begin{itemize}
\item Classification tasks where a cutoff on the predicted class scores is optimized on a validation set according to a predefined target value (or a predefined trade-off between \ac{FP} and \ac{FN}) to induce a concrete decision rule (see Fingerprint F2.6 in Fig.~\ref{fig:fingerprint-ilc}). Associated model validation will be based on the confusion matrix resulting from the decision rule while raw values of predicted class scores are not considered. Thus, \textbf{validation of predicted confidence scores is no hard requirement for these scenarios}.
\item Tasks where no specific decision rule is set (F2.6: "no interest in cutoff at all") and classification is instead validated through general class discrimination (as measured by multi-threshold metrics). In these cases, the final decision is left to an interpretable rule based on predicted class scores, e.g. "risk < 0.05". In order to ensure meaningful decision rules, it is typically of \textbf{importance that predicted confidence scores are validated}. There are, however, exceptions for this requirement, e.g., when a cutoff is not set at the time of validation (implying general interest in algorithm performance across many tasks), but will instead be optimized later upon potential applications.
\end{itemize}
\item \textbf{Data set-wise versus individual validation of confidence scores:} Whether a risk as described in the example above must be controlled across all predictions of a given confidence score (calibration) or at the individual level (true posterior probabilities) depends on whether the cost-benefit trade-off is fixed across the data set or varies at the individual level.
\item \textbf{How to validate predicted confidence scores?} We refer the reader to two common metric families: 1) calibration errors \citep{guoCalibrationModernNeural2017}, where deviations from the described matching are computed for multiple bins of the continuous confidence scale [0,1] (computed per data set), and 2) proper scoring rules \citep{gneitingStrictlyProperScoring2007}, e.g. the Brier Score, which assess whether the classifier outputs are close to the true probability per class given the reference. In contrast to combining calibration errors with a classification metric, proper scoring rules validate confidence scores in a single score. Further, proper scoring rules operate on an individual level, while calibration errors are determined in relation to the entire data set.
\item \textbf{Calibration plots:} So-called calibration plots \cite{guoCalibrationModernNeural2017} allow for quick and interpretable examination of how well predicted confidence scores are classified. They allow for controlling calibration -- but not individual-level probabilities -- and should be reported in addition to curve plots on which the discrimination metrics are based \cite{moons2015transparent}.
\end{itemize}
\subsubsection{Decision guide S4}
\label{ssec:dg4}
\hfill\\\noindent\textbf{D4.1: \ac{TN}-based metrics versus non-\ac{TN}-based metrics} \\
The following aspects should be taken into account when deciding between \ac{LR+} (operating on the full confusion matrix) and F$_\beta$ Score (disregarding TN):
\begin{itemize}
\item \textbf{Problem statement:} Whether or not to validate classification tasks with \ac{TN}-based metrics is among the most controversial issues in metric selection, currently resulting in heterogeneous practices across the biomedical image analysis community. This is because typical validation combines the aspect of Sensitivity with the aspect of either Specificity (\ac{TN}-based), or \ac{PPV} (non-\ac{TN}-based). Often, the two aspects are not reported individually, but combined into a single score. Thus, the choice between Specificity and \ac{PPV} (or \ac{TN}-based versus non-\ac{TN}-based) represents the basis for further choices, e.g. between common per-class counting metrics such as F$_\beta$ Score (\ac{PPV}-based / non-\ac{TN}-based) and \ac{LR+} (Specificity-based / \ac{TN}-based) or common multi-threshold metrics such as \ac{AUROC} (Specificity-based / \ac{TN}-based) and \ac{AP} (\ac{PPV}-based / non-\ac{TN}-based) \footnote{Other relevant \ac{TN}-based) metrics include Accuracy, \ac{BA} and \ac{MCC} while other non-\ac{TN}-based metrics include \ac{FROC} score and \ac{PQ}}. The crucial differences between these pairs are often reported to be in regard to dealing with class imbalance (e.g. \ac{AP} responding better to class imbalance than \ac{AUROC}). However, it is necessary to keep in mind that all these differences can in fact be traced back to whether a metric is based on \ac{TN}.
\item \textbf{How to decide whether to validate with \ac{TN} or not?} As this discussion is limited to per-class validation (either binary classification, or “One versus Rest” / “One versus One” schemes for multi-class classification \cite{hand2001simple}), associated metrics define a positive (P) and a negative class (N) and a subsequent two-class confusion matrix (\ac{TP}, \ac{FP}, \ac{TN}, \ac{FN}). The fundamental difference between \ac{TN}-based and non-\ac{TN}-based metrics boils down to the question: Is there a focus on the positive class or are the two classes of equal interest (F2.5.2)? \ac{TN}-based metrics (Sensitivity + Specificity, \ac{LR+}, \ac{AUROC}) consider the entire confusion matrix and thus reflect a symmetric interest in both classes. Non-\ac{TN}-based metrics (Sensitivity + \ac{PPV}, F$_\beta$ Score, \ac{AP}) only consider three quarters of the confusion matrix and thus reflect an asymmetric interest shifted towards the positive class. In practice, information retrieval tasks (special interest in the queried class) are often distinguished from classification tasks (equal interest in both classes). As an example, consider the task of cancer detection on image level (“cancer or no cancer?”). While the interest in the two errors \ac{FP} (false alarm) and \ac{FN} (missed cancer) is obvious, the question is: Should the metric score of the classifier increase when an image without cancer is added to the data set and the classifier predicts that correctly (\ac{TN})? In favour of \ac{TN}-based metrics one could argue that any correct decision should increase the validation score, while in favour of non-\ac{TN}-based metrics (information retrieval perspective) one could argue that the task is to detect cancer and not to detect non-cancer. The second argument becomes stronger in the case of highly imbalanced data sets, where the aspect of cancer detection performance shrinks in comparison to the aspect of correctly identifying non-cancer. For "One versus Rest" settings in multi-class scenarios, one could argue to employ non-\ac{TN}-based metrics, since there is an inherent focus on the class defined as positive, and the “rest” often outweighs the single positive class in number of data cases (class imbalance, F4.1 \citep{mahani2019classification}).
\item \textbf{Interpretability as an additional aspect for selection:} While the conceptual pros and cons of \ac{TN}-based metrics have been described above, in practice, the medical community has a strong preference towards \ac{TN}-based metrics. One reason might be the notion of superior interpretability enabled by the symmetric focus on the positive and negative classes. For instance, in keeping with the above example, \ac{LR+} can be interpreted as "the likelihood of cancer being predicted as positive divided by the likelihood of a non-cancer case being predicted as positive" \cite{wales2003moving}.
\end{itemize}
\noindent\textbf{D4.2: \ac{PPV}@Sensitivity versus \ac{FPPI}@Sensitivity} \\
The decision between \ac{PPV}@Sensitivity and \ac{FPPI}@Sensitivity relates to most aspects described in D3.2 (\ac{AP} versus \ac{FROC} Score): While \ac{PPV} is a generic metric applied in various communities, \ac{FPPI} originated in the medical community and features improved interpretability. One important difference is that \ac{PPV} is typically computed once over the entire data set, while \ac{FPPI} counts FP per image and subsequently averages over the data set. In Sec. \ref{sec:pitf:fundamentals_od} we discuss the implications of these two aggregation strategies and further present an approach on how to apply various object detection metrics (including \ac{PPV}) in the context of per-image aggregation.
\noindent\textbf{D4.3: F$_\beta$ Score versus \ac{PQ}} \\
The F$_\beta$ Score is a pure detection metric counting \ac{TP}, \ac{FP}, and \ac{FN} detections on instance level (specifically, it represents the harmonic mean of \ac{PPV} and Sensitivity, see also Sec.~\ref{sec:pitf:fundamentals}). The “segmentation aspect” of IS is here only incorporated via a prior cutoff on the localization criterion operating on pixel level (e.g. “\ac{IoU} > 0.5”). In case shifting the focus of validation more towards the segmentation quality of successfully matched (\ac{TP}) instances is desired, there are two options:
\begin{enumerate}
\item \textbf{Complementary segmentation metric:} One option is to select separate segmentation metrics (in addition to object detection metrics such as F$_\beta$ Score) on a per-instance basis (e.g. “\ac{DSC} per \ac{TP}-instance”). This selection is enabled by following the IS path in Fig.~\ref{fig:meta-mapping} traversing the SS subroutines S7 (Fig.~\ref{fig:metric-selection:s7-overlap}) and S8 (Fig.~\ref{fig:metric-selection:s8-boundary}).
\item \textbf{Hybrid metric:} An alternative is to select \ac{PQ} instead of F$_\beta$ Score, which allows expressing both interests (detection performance and segmentation quality) in a single score. Essentially, \ac{PQ} is a modified F$_1$ Score, where \ac{TP} instances do not count as “1” in the calculation, but the “1” is replaced with the associated \ac{DSC} score (range [0,1]) of the instance. While combining the two aspects in a single score might be desirable, e.g. for method benchmarking or ranking, on the downside, such combined metrics make it harder to trace back performance to individual aspects (in this case: object detection versus segmentation).
\end{enumerate}
\noindent\textbf{D4.4: How to determine $\beta$ in F$_\beta$ Score} \\
The F$_\beta$ Score is defined as:
\begin{equation}
F_\beta = (1 + \beta^2) \cdot \frac{\ac{PPV} \cdot \text{Sensitivity}}{(\beta^2 \cdot \ac{PPV}) + \text{Sensitivity}} = \frac{(1 + \beta^2) \cdot \ac{TP}}{(1 + \beta^2) \cdot \ac{TP} + \beta^2 \cdot \ac{FN} + \ac{FP}}
\end{equation}
The most common choice is to set $\beta$ to $1$ resulting in equal weighting of \ac{FP} and \ac{FN} penalties. Higher values of $\beta$ result in higher weights on \ac{FN} penalties compared to \ac{FP} penalties and thus imply a focus on Sensitivity compared to \ac{PPV}.
\subsubsection{Decision guide S5}
\label{ssec:dg5}
\hfill\\\noindent\textbf{D5.1: Mask \ac{IoU} versus \ac{Boundary IoU} versus \ac{IoR}} \\
The following aspects should be taken into account when deciding between Mask and \ac{Boundary IoU}:
\begin{itemize}
\item \textbf{Small structures:} Mask \ac{IoU} over-penalizes small structures in tasks with high variability of structure sizes (F3.2) because boundary pixels increase linearly (or quadratically) with size, while total pixels increase quadratically (or cubically) with size. \ac{Boundary IoU} \cite{cheng2021boundary} addresses this issue by selecting only pixels with a maximum distance of “d” with regard to the boundary for validation (see Fig.~\ref{fig:boundary-mask-iou}).
\item \textbf{Hyperparameters:} However, for the computation of \ac{Boundary IoU}, the distance “d” constitutes an additional and sensitive hyperparameter to be determined by the experimenter. Reference points are the degree of inconsistency if annotations from two raters are available, or qualitative assessment of general annotation quality. Note that the \ac{Boundary IoU} can be fooled to result in a perfect value of $1.0$ (see Fig.~\ref{fig:boundary-iou}).
\item \textbf{Boundary focus:} While Mask \ac{IoU} measures the overlap of structures in general, \ac{Boundary IoU} allows to focus on the correctness of boundaries (F2.1, see Fig.~\ref{fig:boundary-mask-iou}).
\item \textbf{Popularity:} While Mask \ac{IoU} represents an established concept that is well-known to the community, \ac{Boundary IoU} is a recently proposed modification that might require careful introduction when used for validation.
\item \textbf{Touching structures:} In the case of a high ratio of touching reference objects, “non-split errors” (one prediction overlaps with multiple reference objects) might occur frequently. While the \ac{IoU} criterion might heavily penalize this scenario resulting in \ac{FN} and multiple \ac{FP}, a more differentiated penalization might be desired (check F2.5.7), e.g. by explicitly separating such errors into "split errors" as well as "merge errors" \cite{caicedo2019evaluation}, or in the form of the Intersection over Reference (\ac{IoR}) \cite{matula2015cell}, where only the ratio of a reference object’s area covered by a prediction is measured (see Fig.~\ref{fig:od-ior}).
\end{itemize}
\noindent\textbf{D5.2: Discarding information of provided annotations} \\
Selecting a localization criterion operating on a lower/coarser resolution with regard to provided reference annotations effectively discards spatial information and should be well motivated by the given task (see Fig.~\ref{fig:od-information-loss}). For instance, Box \ac{IoU} is sometimes employed despite access to pixel-mask annotations (F4.3) because associated models (object detectors) are considered simpler approaches (compared to instance segmentation models). Such simplification may cause problems if structures are not well-approximated by a box shape (especially for 3D shapes, boxes usually constitute poor approximations), or if structures can overlap (F3.5), causing multi-component masks (see Fig.~\ref{fig:disconnected}).
\noindent\textbf{D5.3: Localization without outlining of structures} \\
When choosing a localization criterion for tasks where the mere existence of objects is of interest (as opposed to the outlining of objects), the following aspects should be considered:
\begin{itemize}
\item \textbf{Loose criterion:} The intuitive choice of a very loose \ac{IoU} criterion (e.g. “\ac{IoU} > 0“ or “at least one pixel overlap”) comes with the pitfall that the size of the predicted structure is in theory unbounded, i.e. the predicted location can be ambiguous (see Fig.~\ref{fig:bb-2d-3d}b).
\item \textbf{Point-based criteria:} A preferable alternative for the case of pure localization (without interest in outlines) is to constrain the prediction to a single coordinate. A common criterion for this scenario is the distance to the center point of the structure (which can also be of explicit interest, see F2.3, Fig.~\ref{fig:hit-criteria}).
The center point\footnote{Depending on what kind of information the center point is derived from, different definitions are possible, for instance: (1) geometric center of the box/approximation shape, (2) geometric center of a binary mask (i.e. average of positions of all pixels), (3) center of mass of a binary mask overlaid with the original image, i.e. weighted average of positions of all pixels with weight equal to (or derived from) the intensity of a particular pixel.}, however, might not be a good reference for tubular structures(check F3.3) or disconnected structures (check F3.6). In such cases (and if annotations are provided in the form of masks), a binary “Point inside Mask” criterion might be the better choice. On the other hand, the “Point inside Mask” criterion does not allow for a variation of the criterion’s strictness (i.e. threshold). Application despite this shortcoming should be well-justified.
\end{itemize}
\noindent\textbf{D5.4: Box \ac{IoU} versus \ac{IoR}} \\
The following aspects should be taken into account when deciding between Box \ac{IoU} and \ac{IoR}:
\begin{itemize}
\item \textbf{Default choice:} The default choice in this setting is Box \ac{IoU}.
\item \textbf{Touching structures:} In the case of a high ratio of touching reference objects, “non-split errors” (one prediction overlaps with multiple reference objects) might occur frequently. In this case, the Intersection over Reference (\ac{IoR}) \cite{matula2015cell}, where only the ratio of a reference object’s area covered by a prediction is measured, might be considered as an alternative to \ac{IoU} (see Fig.~\ref{fig:od-ior}).
\end{itemize}
\subsubsection{Decision guide S6}
\label{ssec:dg6}
\hfill\\\noindent\textbf{D6.1: Assignment without predicted class probabilities on instance level} \\
The following aspects should be considered when selecting the assignment strategy:
\begin{itemize}
\item \textbf{Common practice:} In the biomedical domain, more sophisticated matching strategies are often avoided by setting the localization criterion to \ac{IoU} > 0.5 (\ac{IoU} being any of Mask \ac{IoU}, \ac{Boundary IoU}, or \ac{IoR} as selected in S5; for \ac{IoR} see also D5.1) and only allowing non-overlapping object predictions (which inherently precludes matching conflicts). However, this setting substantially constrains the space of suitable methods as well as the strictness of the localization criterion.
\item \textbf{Cost function-based optimization:} The Hungarian algorithm optimizes the matching between predictions and reference objects while minimizing a given cost function, such as the average overlap for all matched pairs. Notably, this optimization generally leads to optimistic interpretation/validation of ambiguous model outputs, but might not represent the most realistic approximation of model performance upon applications.
\item \textbf{New proposal:} Greedy \ac{IoU} -- instead of sorting predictions per reference object by class score, one can also sort them by \ac{IoU} score and match the prediction with the highest score while dealing with double assignments according to F2.5.6.
\end{itemize}
\subsubsection{Decision guide S7}
\label{ssec:dg7}
\hfill\\\noindent\textbf{D7.1: Dice vs \ac{IoU}} \\
The \ac{DSC} is identical to the F$_1$ Score on pixel level and closely related to the \ac{IoU}, which, in turn, is identical to the Jaccard Index (see equations~\ref{eq:iou-dsc} and~\ref{eq:dsc-iou}). The two metrics will yield the same ranking (of aggregated metric values) in most applications (theoretically, deviations are possible), such that there is no value in combining them. Commonly, the computer vision community prefers the \ac{IoU}, while the medical image community favors the \ac{DSC}.
\noindent\textbf{D7.2: How to determine $\beta$ in F$_\beta$ Score} \\
The F$_\beta$ Score is defined as:
\begin{equation}
F_\beta = (1 + \beta^2) \cdot \frac{\ac{PPV} \cdot \text{Sensitivity}}{(\beta^2 \cdot \ac{PPV}) + \text{Sensitivity}} = \frac{(1 + \beta^2) \cdot \ac{TP}}{(1 + \beta^2) \cdot \ac{TP} + \beta^2 \cdot \ac{FN} + \ac{FP}}
\end{equation}
The most common choice is to set $\beta$ to $1$ resulting in equal weighting of \ac{FP} and \ac{FN} penalties. Higher values of $\beta$ result in higher weights on \ac{FN} penalties (undersegmentation) compared to \ac{FP} penalties (oversegmentation) and thus imply a focus on Sensitivity compared to \ac{PPV}.
\subsubsection{Decision guide S8}
\label{ssec:dg8}
\hfill\\\noindent\textbf{D8.1: \ac{NSD} and \ac{Boundary IoU}} \\
The following aspects should be considered when deciding between \ac{NSD} and \ac{Boundary IoU}:
\begin{itemize}
\item \textbf{Different research questions:} Both metrics set the focus on the boundary/contour of structures, but fundamentally differ in what they measure: \ac{NSD} measures the \ac{DSC} score on the surface voxels (often interpreted as the ratio of correctly predicted contour), where the strictness for what constitutes a correct boundary is controlled by a tolerance parameter. This way, noise in the image, limited resolution (propagating to noise in the reference annotations) or imprecise reference annotations can be accounted for. \ac{Boundary IoU} directly measures the overlap between predicted and reference contours (without tolerance) up to a certain width (which is controlled by a width parameter). Thus, \ac{NSD} is preferable if a tolerance accounting for imprecise annotations is requested. \ac{Boundary IoU}, on the other hand, is preferable if errors at the contour are thought of as crucial inconsistencies that should be assessed, or if a wider area around the contour line is of interest (dynamic transition to the classical \ac{IoU}).
\item \textbf{Setting the hyperparameter:} The \ac{NSD} and \ac{Boundary IoU} both require users to manually set a hyperparameter. \ac{NSD}: Boundary distances below the tolerance threshold will be considered \ac{TP} (deviations do not count as errors). This parameter can be set according to the inter-rater variability or, if not available, heuristics. \textbf{\ac{Boundary IoU}:} The distance parameter determines the thickness of the considered boundary and thus also influences the sensitivity to contour errors (the smaller the distance, the higher the sensitivity). This parameter can also be set according to the inter-rater variability (here in order to capture potential inconsistencies as opposed to disregarding noise like in \ac{NSD} or, if not available, heuristics.
\end{itemize}
\noindent\textbf{D8.2: \ac{MASD} vs \ac{ASSD}} \\
The \ac{ASSD} puts all boundary distances (all distances from boundary A to boundary B and all distances from boundary B to boundary A) in a list, then takes the mean. Thus, if one boundary is much larger than the other, this boundary will impact the mean much more.
The \ac{MASD} computes the sum of the mean distances from boundary A to boundary B and the mean distances from boundary B to boundary A. Therefore, the reference and prediction boundaries contribute equally. While there are corner cases, in which \ac{MASD} features disadvantages compared to \ac{ASSD} as well we generally recommend \ac{MASD} because of the aforementioned advantage.
\noindent\textbf{D8.3: \ac{HD} versus \ac{X$^{th}$ Percentile HD}} \\
The \ac{HD} calculates the maximum of all shortest distances for all points from one object boundary to the other, which is why it is also known as the Maximum Symmetric Surface Distance \cite{yeghiazaryan2018family}. The \ac{X$^{th}$ Percentile HD} calculates the X$^{th}$ percentile (e.g. 95\% percentile for \ac{HD95}) instead of the maximum, and should therefore be used instead if spatial outliers should be disregarded (F2.5.4, see Fig.~\ref{fig:DSC-artifact}). \\ \\
\section{Introduction}
Validation of biological and medical image analysis algorithms is of the utmost importance for making scientific progress and for translating methodological research into practice. Validation metrics\footnote{Not to be confused with distance metrics in the pure mathematical sense.}, the measures according to which performance of algorithms is quantified, constitute the core component of validation design. However, an increasing body of work shows that the metrics used often do not appropriately reflect the underlying biomedical problems, diminishing the validity of the investigated algorithms~\cite{honauer2015hci, correia2006video, kofler2021DICE, gooding2018comparative, vaassen2020evaluation, konukoglu2012discriminative, margolin2014evaluate, maier2018rankings}. This especially holds true for so-called challenges, internationally respected competitions that have over the last few years become the de facto standard for comparative performance assessment in the field. These challenges are often published in prestigious journals~\cite{chenouard2014objective, sage2015quantitative, ulman2017objective} and receive tremendous attention from both the scientific community and industry. Despite their crucial importance, a number of shortcomings in design and quality control have recently been unveiled, notably by a multi-center initiative~\cite{maier2018rankings} performing the first comprehensive evaluation of biomedical image analysis challenges. Among other things, an international survey performed as part of the study revealed the choice of inappropriate metrics as a core problem related to performance assessment in biomedical image analysis. Common issues with respect to metric choice include (see Fig.~\ref{fig:metrics_matter_overview}):
\begin{description}
\item[Inappropriate phrasing of the problem:] The chosen metrics do not always reflect the biomedical need. For example, the popular segmentation metric \ac{DSC} is frequently chosen as a metric for object detection problems although it does not reflect the critical need of detecting as many structure instances\footnote{An instance refers to an object or structure in an image.} as possible (Fig.~\ref{fig:metrics_matter_overview}b, top).
\item[Poor metric selection:] Certain characteristics of a given biomedical problem render particular metrics inadequate. Mathematical metric properties are often neglected, for example when applying the \ac{DSC} in the presence of particularly small structures (Fig.~\ref{fig:metrics_matter_overview}b, middle).
\item[Poor metric application:] Applying metrics to a given data set comes with several pitfalls. For example, a common flaw is related to ignoring hierarchical data structure, as in data from multiple hospitals or a variable number of images per patient (Fig.~\ref{fig:metrics_matter_overview}b, bottom), when aggregating metric values.
\end{description}
Furthermore, poor validation design choices and even wrong metric definitions are often propagated. One impressive example is the successive modification of the "Segmentation Accuracy" metric proposed by the PascalVOC challenge \cite{everingham2010pascal}: A widely-known challenge on cell segmentation \cite{caicedo2019nucleus} substantially altered the originally intended use of pixel-level validation by employing the metric at object level without explicitly commenting on the changes in the manuscript. A subsequent popular competition \cite{schmidt2018cell} followed this altered usage and further changed the name to "Average Precision" (AP), a highly confusing change given that this name is already occupied by a fundamentally different and widely accepted metric for object-level validation~\cite{everingham2010pascal} (Fig.~\ref{fig:ap-example}). The altered naming and usage have since been adopted by further prominent studies and competitions \cite{stringer2021cellpose,satorius}, indicating that the cell segmentation community currently broadly relies on a metric with inappropriate naming and unreflected properties.\footnote{In the meantime, \cite{caicedo2019nucleus} corrected their primary metric to F$_1$ Score and \cite{schmidt2018cell} corrected the name of their metric to "Accuracy".}
\begin{figure}[H]
\centering
\includegraphics[width=0.8\linewidth]{images/General/Figure1_new_A4.pdf}
\caption{\textbf{Pitfalls related to validation metrics in image analysis.} \textbf{a)} This paper addresses biomedical problems that can be interpreted as a classification task. Specifically, we focus on problems with categorical labels at various scales (image level vs. pixel level vs. object level). \textbf{b)} Common problems typically arise from (top) inappropriate phrasing of the problem (here: object detection confused with semantic segmentation), (middle) poor metric selection (here: neglecting the small size of structures) and (bottom) poor metric application (here: inappropriate aggregation scheme).}
\label{fig:metrics_matter_overview}
\end{figure}
As a result of all of these flaws related to metric selection and application, the scientific community requests a priority to be set on best practice recommendations for metrics~\cite{maier2018rankings}. To address this community need, we have compiled an international consortium of more than 60 image analysis experts and representing a large number of relevant biomedical imaging initiatives and societies. The core mission is to provide researchers with guidelines and tools to choose the performance metrics in a problem-aware manner. For the present work, we focused on biomedical problems that can be interpreted as a classification task and are thus mathematically closely related. Specifically, we included problems with categorical labels at various scales, as illustrated in Fig.~\ref{fig:metrics_matter_overview}. Based on a kickoff workshop held in December 2020, the framework for metric recommendations was developed with the help of a multi-stage Delphi process \citep{brown1968delphi} for consensus building.
The core of our framework is the \textit{problem fingerprinting}, which is the generation of a structured representation of the given biomedical problem that captures all properties that are relevant for the purpose of metric selection (Fig.~\ref{fig:fingerprint}). Specifically, the fingerprint comprises \textit{domain interest-related} properties, such as the particular importance of structure boundaries, \textit{target structure-related} properties, such as the size of the structures relative to the image grid size, \textit{data set-related} properties, such as class imbalance, as well as \textit{algorithm output-related} properties, such as the theoretical possibility of the algorithm output not containing any target structure. Based on the problem fingerprint, the user is then guided through the process of selecting an appropriate set of metrics while considering potential pitfalls related to the specific characteristics of the underlying biomedical problem (Fig.~\ref{fig:meta-mapping}).
In this paper, we consider problems in which categorical output for a given \textit{n}-dimensional input image (possibly enhanced with context information) is sought at pixel, object or image level. More specifically, we put a focus on problems that can be assigned to one of the following four problem categories: image-level classification, semantic segmentation, object detection or instance segmentation problem. Examples for the fields of radiology, biology and surgery, respectively, are provided in Fig.~\ref{fig:metrics_matter_overview}.
The following section~\ref{sec:framework} presents the general concept of the recommendation framework, while sections~\ref{sec:rec-classification}-\ref{sec:rec-is} present the specific recommendations for the four problem categories. Cross-topic recommendations are then summarized in section~\ref{sec:cross-topic}.
\begin{figure}[H]
\centering
\includegraphics[width=0.9\linewidth]{images/MetricMappings/Figures_Annika/MetaMapping.pdf}
\caption{\textbf{\textit{Metrics Reloaded} recommendation framework from a user's perspective.} Initially, the characteristics of the given biomedical problem are captured in a \textit{problem fingerprint}, which is a structured representation of the given biomedical problem. The problem fingerprinting further comprises a step of mapping the given biomedical image analysis problem to the appropriate image \textit{problem category}, namely \textcolor{ILCblue}{\textit{image-level classification (ILC)} (blue arrows $\rightarrow$)}, \textcolor{SSyellow}{\textit{semantic segmentation (SS)} (yellow arrows $\rightarrow$)}, \textcolor{ISpink}{\textit{instance segmentation (IS)} (pink arrows $\rightarrow$)}, or \textcolor{ODgreen}{\textit{object detection (OD)} (green arrows $\rightarrow$)}. Based on the problem fingerprint (referred to with "FX.Y", where F indicates a fingerprint and X and Y are placeholders for numbers, see App.~\ref{app:fingerprint-category}), the user is guided through the process of selecting and applying an appropriate set of validation metrics while being made aware of potential pitfalls related to individual choices. All subprocesses, indicated by the $\boxplus$-symbol, are provided in dedicated figures or sections. An overview of the symbols used in the process diagram is provided in Fig.~\ref{fig:process-diagram-symbols}.}
\label{fig:meta-mapping}
\end{figure}
\section{Metric Recommendation Framework}
\label{sec:framework}
The purpose of our framework is to enable users to make educated decisions on which validation metrics to select for a given biomedical problem. The overall process is depicted in Fig.~\ref{fig:meta-mapping}. A user should begin by reading the general instructions of the recommendation framework, provided in Sec.~\ref{ssec:fundamentals}. Next, a \textit{problem fingerprint} should be generated as a structured representation of the given biomedical, as detailed in Sec.~\ref{ssec:fingerprinting}. Based on the problem fingerprint, the user is then guided through the process of selecting an appropriate set of metrics as summarized in Sec.~\ref{ssec:metric_mapping}. The problem category-specific recommendations are provided separately in Sec.~\ref{sec:rec-classification}-\ref{sec:rec-is}. Finally, the user is supported in applying the metrics and reporting the results according to cross-topic recommendations, summarized in Sec.~\ref{sec:cross-topic}).
\subsection{General Instructions and Terminology}
\label{ssec:fundamentals}
A user of our recommendation framework should begin by reading the following instructions, which present fundamental terminology as well as the guiding principles that the framework is based on.
\subsubsection{Fundamentals}
\paragraph{Problem categories} In this paper, we consider problems of the following four categories (see Figs.~\ref{fig:metrics_matter_overview}a and~\ref{fig:scenario-table} for examples).
\begin{description}
\item[Image-level classification] refers to the assignment of one or multiple category labels to the entire image. Deciding on the presence or absence of a certain condition/pathology would be a typical example, such as disease classification in dermoscopic images, or fracture detection on X-ray images.
\item[Semantic segmentation] refers to the assignment of one or multiple category labels to each pixel. Common examples include organ segmentation in \ac{CT} images and labeling full laparoscopic image frames with all structures/organs/pathologies that appear (e.g. for the purpose of surgical scene understanding or autonomous robotics).
\item[Object detection] refers to the detection and localization of structures of one or multiple categories. The detection and bounding box-based localization of polyps in colonoscopy sequences is a popular example.
\item[Instance segmentation] refers to the detection and delineation of each distinct object of a particular class. It can be regarded as delivering the tasks of object detection and semantic segmentation at the same time. In contrast to object detection, instance segmentation also involves the accurate marking of the object boundary. In contrast to semantic segmentation, it distinguishes different instances of the same class. Cell nuclei segmentation with a subsequent goal of cell tracking or counting is a common example.
\end{description}
Notably, the four different categories are mathematically closely related as illustrated in Fig.~\ref{fig:metric-families}.
A comprehensive description of the problem categories can be found in App.~\ref{sec:pitf:fundamentals}.
\newpage
\input{Metric_Table}
\paragraph{Metric families}
As an important prerequisite for the development of the recommendation framework, the expert panel identified the most relevant reference-based metrics for the image analysis categories addressed in this paper (Tab.~\ref{tab:metrics}). All of these metrics are directly or indirectly based on the cardinalities of the so-called \textit{confusion matrix} (i.e., the true (T)/false (F) positives (P)/negatives (N) in binary problems). They are typically computed by comparing the algorithm's prediction to a reference annotation. Modern neural network-based approaches commonly require a threshold to be set in order to convert the algorithm output comprising predicted class scores\footnote{Sometimes referred to as predicted class probabilities, continuous class scores or pseudo-probabilities.} to a confusion matrix, as illustrated in Fig.~\ref{fig:metric-families}. For the purpose of metric recommendation, we classify the identified metrics into \textbf{counting metrics} that operate directly on the confusion matrix and express the metric value as a function of the cardinalities (see Figs.~\ref{fig:def-classification-1}, \ref{fig:def-classification-2} and~\ref{fig:definition-overlap}), \textbf{multi-threshold metrics} that operate on a dynamic confusion matrix, such as \textit{\ac{AUROC}} (see Fig.~\ref{fig:def-auc}), and \textit{\ac{AP}} (see Fig.~\ref{fig:ap-example}) and \textbf{distance-based metrics} that typically rely on the explicit definition of object boundaries (see Figs.~\ref{fig:definition-distance} and~\ref{fig:definition-nsd}).
\paragraph{Reference versus ground truth:} We assume that the validation process is based on the comparison of the algorithm output and a \textbf{reference} (sometimes called \textbf{gold standard}), which is assumed to be close or equal to the correct result; the (often forever unknown) \textbf{ground truth}. In terms of metrics, we distinguish between \textit{reference-based metrics}~\cite{jannin2006model}, which use the image-based reference, and \textit{non-reference-based metrics} that assess complementary properties, such as runtime, memory consumption, or carbon footprint.
\paragraph{Conflicting terminology} Terminology may differ substantially across communities. For example, the statistics community prefers the term \ac{PPV} over \textit{Precision}, as the latter can be confused with the confidence of an output. In the medical domain, the term \textit{validation} is used for an independent assessment (untouched test set) of an algorithm, while the machine learning community commonly uses a \textit{validation set} for hyperparameter tuning. To avoid confusion resulting from unclear terminology, the final version of this manuscript will provide a glossary in the Appendix.
\subsubsection{Guiding principles}
Our framework is based on the following guiding principles:
\paragraph{Phrasing of the biomedical task}
The recommendation framework has been designed in a way to support the metric selection and application process for one specific driving biomedical question. In practice, multiple questions are often addressed with one given data set. For example, a clinician may have the ultimate interest of diagnosing brain cancer in a patient based on a given \ac{MRI} data set. While this would be phrased as an image-level classification task, an interesting \textit{surrogate task} could be that of segmentation to assess the quality of tumor delineation. In the case of multiple different driving biomedical questions, a recommendation is generated separately for each question.
\paragraph{Dealing with multiple classes}
In non-binary problems, a per-class validation is always recommended. As problem properties may differ from class to class (e.g. the size or size variability of target structures), the problem fingerprint needs to be generated separately for each class. In consequence, each subprocess (denoted by the $\boxplus$-symbol in the framework overview shown in Fig.~\ref{fig:meta-mapping}) needs to be traversed separately for each class in case the fingerprint properties relevant for the respective subprocess differ. Although not common in current validation practice, this may - in theory - lead to different validation metrics for different classes. Note that in addition to metrics applied to individual classes ("One versus rest" setting), a multi-class metric operating on the entire confusion matrix (e.g. \ac{MCC}) may be applied, as detailed in the problem category-specific instructions.
\paragraph{Model-agnostic metric recommendation}
Metrics should be chosen based solely on the driving biomedical problem and not be effected by algorithm design choices. For example, the error functions applied in common neural network architectures do not justify the use of corresponding metrics (e.g. validating with \ac{DSC} to match the Dice loss~\cite{drozdzal2016importance} used for training a U-net~\cite{ronnebergerUNetConvolutionalNetworks2015}).
\paragraph{Comparative benchmarking versus diagnostics}
In general, the biomedical interest cannot be captured with a single metric. In segmentation tasks, for example, the popular \ac{DSC} (which measures the overlap between the prediction and the reference) is typically complemented by a contour-based metric to explicitly assess the quality of boundaries. The framework has therefore been designed to recommend multiple complementary metrics for a given task. We assume two primary use cases of metrics in this paper. In comparative benchmarking studies (e.g. competitive challenges), multiple algorithms or algorithm variants are compared on identical data sets. This requires the ranking of the competing algorithms according to performance. Typically multiple complementary validation metrics are applied in this use case, resulting in either multiple rankings or a merged ranking that takes all or several metric values into account, as detailed in Sec.~\ref{sec:cross-topic}. We refer to the metrics that contribute to the (primary) ranking(s) as \textit{primary metrics}. \textit{Secondary metrics} can additionally be applied for comprehensive reporting, for example because they reflect complementary properties of interest (e.g. compute time, carbon footprint), or for providing performance measures that are comparable across publications. The computer vision community, for example, typically reports the \ac{IoU} rather than the \ac{DSC}. While our mappings focus on the recommendation of primary metrics, users are invited to complement them by further secondary metrics according to their specific needs. The second use case of metrics addressed by our framework are validation studies centered around a single algorithm that focus on comprehensive diagnostics rather than comparative assessment. In this case, it is often desired to report as many complementary metrics as possible in order to comprehensively analyse the properties of an algorithm. If a user of our framework is interested in this second type of study, the notion of primary and secondary metrics can be ignored.
\paragraph{Predefined target values}
Modern algorithms output (continuous) predicted class scores. To classify cases in an actual biomedical application (e.g. in a screening tool), however, it is required to set a cutoff value on the scores. Sometimes, the underlying problem provides a specific target metric value to be reached (e.g. a certain Sensitivity or a certain ratio of false detections (\ac{FP}) versus misses (\ac{FN})), requiring a corresponding cutoff value. If this is not the case, there are two widely-adapted coping strategies that are not transparently motivated or distinguished in current practice: 1) determining a cutoff based on default values (e.g. "argmax" operation in semantic segmentation, or "0.5" in binary image classification) or based on optimizing a primary metric (e.g. F$_1$ Score) using a validation set; 2) abstaining from validating algorithms at a certain cutoff and exclusively reporting results on multi-threshold metrics (averaging over various cutoffs) instead. The deciding factor between the two strategies should be how much focus is to be put on a certain application at hand versus general and application-agnostic algorithm assessment. While some communities seem to have converged on cutoff-based validation (e.g. cell instance segmentation \cite{caicedo2019nucleus}), recent clinical initiatives advocate for cutoff-agnostic validation arguing that cutoffs are often over-optimized on a specific data set and that associated results are not transferable across study cohorts (e.g. with differing disease prevalence) and clinical applications (e.g. with differing cost-benefit trade-offs for patients) \cite{vickers2016net,moons2015transparent,bejnordi2017diagnostic}. We handle this controversy in current practices by making validation at certain cutoffs optional (for all tasks except semantic segmentation).
\paragraph{Notation:} The notation for our recommendations have been based on \ac{BPMN}. The individual components used in the recommendation diagrams are explained in Fig.~\ref{fig:process-diagram-symbols}.
\subsection{Problem Fingerprinting}
\label{ssec:fingerprinting}
As an important foundation for the metric recommendation framework, the expert panel identified common and rare failure cases of metrics in a community-powered process process. The results are provided in App.~\ref{app:pitfalls} and include a wide variety of pitfalls ranging from those related to domain interest, data set and properties of the target structure all the way to mathematical considerations with respect to analyses and post-processing. These pitfalls served as a foundation for developing the \textit{problem fingerprint}, whose purpose is to capture all properties of the underlying biomedical problem that are relevant for selecting appropriate validation metrics. Common problems often relate to selecting metrics from the wrong problem category, as illustrated in App.~\ref{sec:pitf:underlying-task}. To avoid such problems, the problem fingerprinting comprises the step of mapping a given problem with all its intrinsic and data set-related properties to the corresponding problem category via the \textit{category mapping} (Fig.~\ref{fig:category_mapping}).
\newpage
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/Fingerprint/Fingerprint_selection.png} \caption{\textbf{Relevant properties of a driving biomedical image analysis problem are captured by the \textit{problem fingerprint}} (selection shown here). Besides the problem category, the fingerprint comprises (1) domain interest-related properties, (2) target structure-related properties, (3) data set-related properties and (4) algorithm output-related properties. The relevance of the properties for the problem categories image-level classification (ILC), semantic segmentation (SS), object detection (OD) and instance segmentation (IS) is indicated by a $\Rightarrow$. A comprehensive version of the fingerprint for the individual problem categories can be found in Fig.~\ref{fig:fingerprint-ilc} (ILC), Figs.~\ref{fig:fingerprint-ss-1}/\ref{fig:fingerprint-ss-2} (SS), Figs.~\ref{fig:fingerprint-od-1}/\ref{fig:fingerprint-od-2} (OD) and Figs.~\ref{fig:fingerprint-is-1}~-~\ref{fig:fingerprint-is-3} (IS).}
\label{fig:fingerprint}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/MetricMappings/Figures_Annika/S1_category_mapping.pdf}
\caption{\textbf{Subprocess S1 for selecting a problem category.} The \textit{Category Mapping} maps a given research problem to the appropriate problem category with the goal of \textbf{grouping problems by similarity of validation.} The leaf nodes represent the categories: image-level classification, object detection, instance segmentation or semantic segmentation). F3.1 refers to fingerprint 3.1 (see Fig.~\ref{fig:fingerprint-ss-2}). An overview of the symbols used in the process diagram is provided in Fig.~\ref{fig:process-diagram-symbols}.}
\label{fig:category_mapping}
\end{figure}
Finally, a structured representation of the biomedical problem is generated, which not only includes the appropriate problem category, but also comprises (1) \textit{domain interest-related} properties, such as the unequal importance of classes or the particular importance of structure boundaries, (2) \textit{target structure-related} properties, such as the size of the structures relative to the image grid size or the shape complexity, (3) \textit{data set-related} properties, such as class imbalance and annotation quality, as well as (4) \textit{algorithm output-related} properties, such as the theoretical possibility of the algorithm output not containing any target structure. The category-specific fingerprints are provided in Fig.~\ref{fig:fingerprint-ilc} (image-level classification), Figs.~\ref{fig:fingerprint-ss-1}/\ref{fig:fingerprint-ss-2} (semantic segmentation), Figs.~\ref{fig:fingerprint-od-1}/\ref{fig:fingerprint-od-2} (object detection) and Figs.~\ref{fig:fingerprint-is-1}/\ref{fig:fingerprint-is-2} (instance segmentation). Individual fingerprints are from hereon referred to with the prefix \textit{F} (e.g. \textit{F2.2: Particular importance of structure volume}) The metric recommendation is then performed with a \ac{BPMN}-based flowchart (see Fig.~\ref{fig:process-diagram-symbols}), in which conditional operations are based on one or multiple fingerprint properties, as detailed in the following sections.
\subsection{Metric Selection}
\label{ssec:metric_mapping}
The fingerprint is leveraged to enable the guided selection of a suitable set of metrics for the driving biomedical problem, as illustrated in Fig.~\ref{fig:meta-mapping}. While the selection of the primary reference-based metrics is performed in a problem category-specific manner, a common routine is applied for selecting further property-specific metrics as well as non-reference-based metrics. The latter include metrics for assessing speed, memory consumption or carbon footprint, for example. The following sections present the category-specific selection process for the reference-based metrics. Exemplary traversals through the recommendation framework for four different biomedical scenarios can be found in App.~\ref{app:scenarios} with the resulting metric recommendations summarized in Fig.~\ref{fig:scenario-table}.
\section{Recommendations for Image-level Classification}
\label{sec:rec-classification}
Image-level classification refers to the process of assigning one or multiple labels, or \textit{classes}, to an image. Modern algorithms usually output continuous scores between 0 and 1 for every image and class, which are often interpreted as predicted class probabilities. By introducing a threshold (e.g. 0.5), predictions are considered as positive (e.g. cancer = true) if they are above the threshold or negative if they are below the threshold. Subsequently, a confusion matrix can be determined based on matching predictions with reference labels. The most common pitfalls related to metric selection in classification are summarized in App.~\ref{sec:pitf:classification} and include pitfalls related to class imbalance, unequal importance of classes, missing prevalence correction as well as the hierarchical structure of the classes and/or the data. The identified pitfalls served as a basis for the generation of the category-specific fingerprint (Fig.~\ref{fig:fingerprint-ilc}) and metric mapping (dark blue path in Fig.~\ref{fig:meta-mapping}). The following information is relevant as a basis for traversing the mapping:
\begin{description}
\item[Recommendation at a glance:] We recommend picking one multi-class counting metric (subprocess S2, Fig.~\ref{fig:metric-selection:s2-multi-class}) and complementing it with a multi-threshold metric (subprocess S3, Fig.~\ref{fig:metric-selection:s3-multi-threshold}) and (optionally) a per-class counting metric (subprocess S4, Fig.~\ref{fig:metric-selection:s4-single-threshold}). Multi-class metrics have the unique advantage that they capture the performance of all classes in a single value. By taking into account all entries of the multi-class confusion matrix, they provide a holistic measure for the problem in a single score without the need for customized class-aggregation schemes. On the other hand, detailed class-specific analyses are not possible with multi-class metrics.
To address this weakness, we recommend an additional per-class validation based on multi-threshold metrics and/or per-class counting metrics, where each class is separately assessed in a "One-vs-the-Rest" fashion (merging remaining other classes together), although other variants are also possible~\cite{hand2001simple}.
If desired, further customized metrics and non-reference-based metrics can be added to the metric pool.
\item[Output Calibration:] In application scenarios that involve interpreting the raw algorithm output (specifically the predicted class scores), \textit{output calibration} can be used to obtain a reliable measure of confidence associated with the decision. Please check decision guide D3.3 in App.~\ref{ssec:dg3} and Fig.~\ref{fig:calibration} for further information.
\item[Expected format of reference and algorithm output:] The metric mapping expects the following format for image-level classification with $C$ classes: For each image $I$ there is a reference annotation $y_I$ that is either indicating the class for the image ($y_I \in \{1, ..., C\}$) or in the case of multi-label classification indicating presence for each class ($y_I \in \{0, 1\}^C$). Similarly the algorithm is expected for each image $I$ to output continuous class scores for each of the classes ($\hat{y}_I \in [0, 1]^C$), indicating the predicted class probability. In case the provided reference annotations deviate from the expected format, matching can be achieved via various measures (e.g. aggregation of pixel-level reference to required image-level reference).
\end{description}
The traversal through the decision tree of our framework for the specific task of disease classification in dermoscopic images is illustrated in Fig.~\ref{fig:scenario-ilc-skin}. The resulting metric recommendation can be found in Fig.~\ref{fig:scenario-table}.
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/MetricMappings/Figures_Annika/S2_subroutine_multi-class.pdf}
\caption{\textbf{Subprocess S2 for selecting multi-class metrics (if any)}. Applies to: Image-level classification (ILC). Based on the problem fingerprint (referred to as "FX.Y"), the user is guided through the process of selecting a multi-class counting metric from the family of counting metrics while being made aware of potential pitfalls related to individual choices. Metric definitions can be found in Tab.~\ref{tab:metrics} and App.~\ref{sec:pitf:fundamentals_ilc}. Decision guides are provided in App.~\ref{ssec:dg2}. Detailed descriptions of the problem fingerprint are provided in Fig.~\ref{fig:fingerprint-ilc}. An overview of the symbols used in the process diagram is provided in Fig.~\ref{fig:process-diagram-symbols}.}
\label{fig:metric-selection:s2-multi-class}
\end{figure}
\newpage
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/MetricMappings/Figures_Annika/S3_subroutine_multi-threshold.pdf}
\caption{\textbf{Subprocess S3 for selecting a multi-threshold metric (if any)}. Applies to: Image-level classification (ILC), object detection (OD) and instance segmentation (IS). Based on the problem fingerprint (referred to as "FX.Y"), the user is guided through the process of selecting a multi-threshold metric while being made aware of potential pitfalls related to individual choices. Metric definitions can be found in Tab.~\ref{tab:metrics} and App.~\ref{sec:pitf:fundamentals_ilc} and~\ref{sec:pitf:fundamentals_od}. Decision guides are provided in App.~\ref{ssec:dg3}. Detailed descriptions of the problem fingerprint are provided in Figs.~\ref{fig:fingerprint-ilc}, \ref{fig:fingerprint-od-1}~-~\ref{fig:fingerprint-is-3}. An overview of the symbols used in the process diagram is provided in Fig.~\ref{fig:process-diagram-symbols}.}
\label{fig:metric-selection:s3-multi-threshold}
\end{figure}
\newpage
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/MetricMappings/Figures_Annika/S4_subroutine_single-threshold.pdf}
\caption{\textbf{Subprocess S4 for selecting a per-class counting metric (if any)}. Applies to: Image-level classification (ILC), object detection (OD) and instance segmentation (IS). Based on the problem fingerprint (referred to as "FX.Y"), the user is guided through the process of selecting an appropriate validation metrics from the family of counting metrics while being made aware of potential pitfalls related to individual choices. Metric definitions can be found in Tab.~\ref{tab:metrics} and App.~\ref{sec:pitf:fundamentals_ilc},~\ref{sec:pitf:fundamentals_od} and~\ref{sec:pitf:fundamentals_is}. Decision guides are provided in App.~\ref{ssec:dg4}. Detailed descriptions of the problem fingerprint are provided in Figs.~\ref{fig:fingerprint-ilc}, \ref{fig:fingerprint-od-1}~-~\ref{fig:fingerprint-is-3}. An overview of the symbols used in the process diagram is provided in Fig.~\ref{fig:process-diagram-symbols}.}
\label{fig:metric-selection:s4-single-threshold}
\end{figure}
\newpage
\section{Recommendations for Semantic Segmentation}
\label{sec:rec-ss}
In semantic image segmentation, classification is performed at pixel level, i.e. each pixel is assigned to one or multiple categories. For many segmentation problems, object boundaries are generated in addition to the pixel-wise classification images. This enables the computation of distance-based metrics, such as the \ac{NSD}. Common pitfalls in segmentation problems are summarized in App.~\ref{sec:pitf:segmentation} and are primarily related to the small size, shape and size variability of target structures as well as data set-related properties, such as the uncertainties in reference annotation. The pitfalls served as a basis for generating the category-specific fingerprint (Figs.~\ref{fig:fingerprint-ss-1} and~\ref{fig:fingerprint-ss-2}) and metric mapping (orange path in Fig.~\ref{fig:meta-mapping}) for semantic segmentation. The following information is relevant as a basis for traversing the mapping:
\begin{description}
\item[Recommendation at a glance:] The semantic segmentation mapping for reference-based metrics comprises three parts: First, a per-class counting metric (subprocess S7, Fig.~\ref{fig:metric-selection:s7-overlap}) -- in segmentation tasks referred to as an \textit{overlap-based metric} -- is selected. Overlap-based metrics, such as the \ac{DSC} or \ac{IoU}, measure the overlap between the reference annotation and the prediction of the algorithm and provide powerful insights into algorithm performance. Key weaknesses, however, include shape unawareness (Fig.~\ref{fig:DSC-shapes}) and limitations when dealing with small structures (Fig.~\ref{fig:DSC-small}) or high size variability (Fig.~\ref{fig:high-variability}). A general recommendation is therefore to complement an overlap-based metric with a boundary-based metric (subprocess S8, Fig.~\ref{fig:metric-selection:s8-boundary}). Finally, specific property-related metrics may be selected to assess additional algorithm properties. A popular example are volume-based metrics, which explicitly measure absolute or relative volume differences of structures as these are of key relevance from a domain perspective. The reference-based metrics can then be complemented by non-reference-based metrics.
%
\item[Requirements for distance-based metrics:] While overlap-based metrics, such as the \ac{DSC} are almost always recommended in segmentation problems (see subprocess S7, Fig.~\ref{fig:metric-selection:s7-overlap}), distance-based metrics are not appropriate under several circumstances. In scenarios in which multiple structures of the same type can be seen within the same image (e.g. in multiple sclerosis lesion segmentation), for example, a potential pitfall is related to comparing a given structure boundary to the boundary of the wrong instance in the reference. Similar problems arise in the case of completely missed instances. In such scenarios, we recommend reconsideration to phrase the problem as an instance segmentation problem. If semantic segmentation remains the chosen category, we advise against the use of distance-based metrics, as these are not designed for cases where mix-up of contours across different instances can occur.
\item[Multi-threshold metrics for semantic segmentation:] Empirically, segmentation networks are very confident for most pixels of the image (close to 0 and 1). Only at the boundary of objects, changing the threshold would have an impact, essentially controlling over- and undersegmentation. Cases, where threshold variations affect whether or not entire smaller objects are found, and there is an inherent interest in identifying these objects (as opposed to the entirety of all pixels), are better formulated as instance segmentation tasks (see subprocess S1, Fig.~\ref{fig:category_mapping}).
\item[Specific property-related metrics:] Overlap-based and contour-based metrics can be complemented with further reference-based metrics that assess additional properties that are relevant from a domain perspective. They can, for example, address the particular importance of structure volume (F2.2) with the Relative Volume Difference \citep{nai2021comparison}, Volume Similarity \citep{nai2021comparison} or the Relative Symmetric Volume Difference \citep{warburton2008balance} metrics. Similarly, the compliance with prior knowledge, such as hierarchical label structure (F3.4) can be measured.
\item[Expected format of reference and algorithm output:] We assume the reference annotation and the algorithm output to be in the same coordinate system with identical spacing. The metric mapping expects the following format for semantic segmentation with $C$ classes: For each pixel $P$ there is a reference annotation $y_P$ that either assigns a single class to $P$ ($y_P \in \{1, ..., C\}$) or, in case of possible multiple labels per pixel, indicates assignment for each class ($y_P \in \{0, 1\}^C$). As for the algorithm output, for each pixel $P$ there is expected to be either a single prediction ($\hat{y}_P \in \{1, ..., C\}$) or, in case of multiple possible labels per pixel, a prediction for each class ($\hat{y}_P \in \{0, 1\}^C$). Some segmentation metrics are defined only on the border pixels of the reference and predicted segmentation. Border pixels are defined as the set of all pixels of class $c$ that have an immediate neighbor not containing the class $c$.
\end{description}
The traversal through the decision tree of our framework for the specific task of liver segmentation in computed tomography images is illustrated in Fig.~\ref{fig:scenario-ss-liver}. The resulting metric recommendation can be found in Fig.~\ref{fig:scenario-table}.
\newpage
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/MetricMappings/Figures_Annika/S7_subroutine_overlap.pdf}
\caption{\textbf{Subprocess S7 for selecting overlap-based segmentation metrics (if any)}. Applies to semantic segmentation (SS) and instance segmentation (IS). Based on the problem fingerprint (referred to as "FX.Y"), the user is guided through the process of selecting an appropriate set of overlap-based validation metrics from the family of counting metrics while being made aware of potential pitfalls related to individual choices. Metric definitions can be found in Tab.~\ref{tab:metrics} and App.~\ref{sec:pitf:fundamentals_ss}. Decision guides are provided in App.~\ref{ssec:dg7}. Detailed descriptions of the problem fingerprint are provided in Figs.~\ref{fig:fingerprint-ss-1}~-~\ref{fig:fingerprint-ss-2} and \ref{fig:fingerprint-is-1}~-~\ref{fig:fingerprint-is-3}. An overview of the symbols used in the process diagram is provided in Fig.~\ref{fig:process-diagram-symbols}.}
\label{fig:metric-selection:s7-overlap}
\end{figure}
\newpage
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/MetricMappings/Figures_Annika/S8_subroutine_boundary.pdf}
\caption{\textbf{Subprocess S8 for selecting a boundary-based segmentation metric (if any)}. Applies to semantic segmentation (SS) and instance segmentation (IS). Based on the problem fingerprint (referred to as "FX.Y"), the user is guided through the process of selecting an appropriate boundary-based segmentation metric from the family of distance-based metrics while being made aware of potential pitfalls related to individual choices. Metric definitions can be found in Tab.~\ref{tab:metrics} and App.~\ref{sec:pitf:fundamentals_ss}. Decision guides are provided in App.~\ref{ssec:dg8}. Detailed descriptions of the problem fingerprint are provided in Figs.~\ref{fig:fingerprint-ss-1}~-~\ref{fig:fingerprint-ss-2} and \ref{fig:fingerprint-is-1}-~\ref{fig:fingerprint-is-3}. An overview of the symbols used in the process diagram is provided in Fig.~\ref{fig:process-diagram-symbols}.}
\label{fig:metric-selection:s8-boundary}
\end{figure}
\newpage
\section{Recommendations for Object Detection}
\label{sec:rec-od}
Object detection refers to the detection of one or multiple objects, or instances, of a particular class (e.g. lesion) in an image \cite{lin2014microsoft}. The following description assumes single-class problems, but generalization to multi-class problems is straightforward, as validation for multiple classes on object level is performed individually per class. Notably, as multiple predictions and reference instances may be present in one image, the predictions need to include localization information, such that a matching between reference and predicted objects can be performed. The validation process in in object detection comprises three parts (see also \ref{sec:pitf:fundamentals_od}: 1) localization of objects (i.e. matching of prediction and reference objects), 2) final assignment (i.e. resolving ambiguities that occurred during localization) to enable determining the confusion matrix, and 3) actual method assessment given a set of suitable validation metrics. Note that the entire process is performed on a per-class basis and that a key characteristic of object detection problems is the absence of \ac{TN}, which renders many popular classification metrics invalid. Suitable counting metrics can only be based on three of the four entries of the confusion matrix. Relevant pitfalls identified for object detection problems are summarized in ~\ref{sec:pitf:detection} and are mainly related to these three aspects. The identified pitfalls served as the foundation for the generation of the category-specific fingerprint (Figs.~\ref{fig:fingerprint-od-1} and ~\ref{fig:fingerprint-od-2}) and metric mapping (light blue path in Fig.~\ref{fig:meta-mapping}) for object detection. The following information is relevant as a basis for traversing the mapping:
\begin{description}
\item[Recommendation at a glance:] Following the three-step process for object detection validation described above, the associated metric selection process is divided into three parts: First, a criterion for deciding whether a predicted object matches a reference object ("localization") is selected (subprocess S5, Fig.~\ref{fig:metric-selection:s5-localization-criterion}). Second, a strategy for handling ambiguous assignments is chosen (subprocess S6, Fig.~\ref{fig:metric-selection:s6-assignment-strategy}). Finally, the validation metrics are selected, which comprise a multi-threshold metric (subprocess S3, Fig.~\ref{fig:metric-selection:s4-single-threshold}) and (optionally) a single-threshold counting metric (subprocess S4, Fig.~\ref{fig:metric-selection:s4-single-threshold}).
%
These standard reference-based metrics can then be complemented by customized metrics and non-reference-based metrics.
\item[Strictness of localization criterion:] Determining whether an object is detected requires deciding on a threshold on the selected localization criterion (e.g. \ac{IoU} > 0.5 counts as detected). However, such cutoff renders the validity of results limited to the specific threshold. To increase robustness of reported metrics, it is common practice in the computer vision community to average metrics over multiple cutoff values (default for IoU criteria: from 0.5 until 0.9 in steps of 0.05). On the other hand, certain properties of the problem at hand may limit the relevance of evaluated cutoff values to lower or higher values.
The following properties might warrant validation with lower thresholds: interest in the existence of objects rather than their precise localization, small size of structures (F3.1), high variability of structure sizes (F3.2), 3D input images (as volume increases cubically with size, the desired overlap ratio might require adaptation), uncertainties in the reference (F4.2.1). Conversely, these properties typically warrant validation at higher thresholds: interest in precise localization, dense distribution of structures in images (F3.5).
\item[Expected format of reference and algorithm output:] The metric mapping expects the following format for object detection with $C$ classes: For each object $O$ the reference consists of a tuple $(y_O, l_O)$, where $y_O \in \{1, .., C\}$ indicates the class of the object and $l_O$ is some location information (box, center point, radius, etc.). The algorithm output for an object prediction $O$ is expected to comprise a tuple $(\hat{y}_O, \hat{l}_O)$ as well, where $\hat{y}_O$ indicates a single predicted class ($\hat{y}_O \in \{1, .., C\}$) optionally accompanied by an associated predicted class score ($\hat{c}_O \in [0, 1]$). See F5.1 in case no predicted class score is provided. $\hat{l}_O$ is expected to provide location information about the prediction in a similar format as the reference (box, center point, radius, etc.). In case reference objects are represented by rough outlines (F4.3) we assume that the chosen shapes (e.g. bounding box or ellipsoid) represent the underlying object adequately. Particular attention needs to be given to this aspect if objects feature a tubular shape (F3.3) or can potentially appear disconnected (F3.6).
\end{description}
The traversal through the decision tree of our framework for the specific task of polyp detection in colonoscopy images is illustrated in Fig.~\ref{fig:scenario-od-polyp}. The resulting recommendations for localization/assignment strategies and metrics can be found in Fig.~\ref{fig:scenario-table}.
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/MetricMappings/Figures_Annika/S5_subroutine_localization.pdf}
\caption{\textbf{Subprocess S5 for selecting the localization criterion}. Applies to object detection (OD) and instance segmentation (IS). Based on the problem fingerprint (referred to as "FX.Y"), the user is guided through the process of selecting an appropriate localization criterion while being made aware of potential pitfalls related to individual choices. Definitions of the localization criteria can be found in App.~\ref{sec:pitf:fundamentals_od}. Decision guides are provided in App.~\ref{ssec:dg5}. Detailed descriptions of the problem fingerprint are provided in Figs.~\ref{fig:fingerprint-od-1}~-~\ref{fig:fingerprint-is-3}. An overview of the symbols used in the process diagram is provided in Fig.~\ref{fig:process-diagram-symbols}.}
\label{fig:metric-selection:s5-localization-criterion}
\end{figure}
\newpage
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/MetricMappings/Figures_Annika/S6_subroutine_assignment.pdf}
\caption{\textbf{Subprocess S6 for selecting the assignment strategy.} Applies to object detection (OD) and instance segmentation (IS). Based on the problem fingerprint (referred to as "FX.Y"), the user is guided through the process of selecting an appropriate assignment criterion while being made aware of potential pitfalls related to individual choices. Assignment strategies are defined in App.~\ref{sec:pitf:fundamentals_od}. Decision guides are provided in App.~\ref{ssec:dg6}. Detailed descriptions of the problem fingerprint are provided in Figs.~\ref{fig:fingerprint-od-1}-~\ref{fig:fingerprint-is-3}. An overview of the symbols used in the process diagram is provided in Fig.~\ref{fig:process-diagram-symbols}.}
\label{fig:metric-selection:s6-assignment-strategy}
\end{figure}
\newpage
\section{Recommendations for Instance Segmentation}
\label{sec:rec-is}
In contrast to semantic segmentation, instance segmentation problems distinguish different instances of the same class (i.e. different lesions). Similarly as in object detection problems, the task is to detect individual instances of the same class, but detection performance is measured by pixel-level correspondences, as in semantic segmentation problems. Instances can be optionally assigned to one of multiple classes. Validation metrics in instance segmentation problems often combine common detection metrics with segmentation metrics applied per instance. Thus, their pitfalls are the combination of identified pitfalls in object detection (App.~\ref{sec:pitf:detection}) and semantic segmentation (App.~\ref{sec:pitf:segmentation}). The identified pitfalls served as a foundation for the generation of the category-specific fingerprint (Figs.~\ref{fig:fingerprint-is-1}~-~\ref{fig:fingerprint-is-3}) and metric mapping (purple path in Fig.~\ref{fig:meta-mapping}) for instance segmentation. The following information is relevant as a basis for traversing the mapping:
\begin{description}
\item[Recommendation at a glance:] The metric selection process for instance segmentation first traverses the same path as in object detection (subprocesses S5, Fig.~\ref{fig:metric-selection:s5-localization-criterion}, S6, Fig.~\ref{fig:metric-selection:s6-assignment-strategy}, S3, Fig.~\ref{fig:metric-selection:s3-multi-threshold}, S4, Fig.~\ref{fig:metric-selection:s4-single-threshold}). One main difference to object detection is the fact that localization criteria in S5 are based on pixel correspondence. Furthermore, an instance segmentation-specific metric, referred to as \ac{PQ} (see subprocess S4) can be selected to reflect the hybrid nature of the task; more specifically, the metric combines the assessment of overall detection performance and segmentation quality of successfully matched (\ac{TP}) instances in a single score. If, instead, a separate assessment of segmentation quality for \ac{TP} instances is desired, additionally to selected detection metrics, the semantic segmentation path (subprocesses S7, Fig.~\ref{fig:metric-selection:s7-overlap} and S8, Fig.~\ref{fig:metric-selection:s8-boundary}) can be traversed to select corresponding metrics. The segmentation metrics are then applied per instance.
These resulting set of standard reference-based metrics can finally be complemented by customized metrics and non-reference-based metrics.
\item[Metrics avoiding reference matching:] While we have found our generic recommendation to match the majority of biomedical problems, the standard reference-based metrics are not well-suited for some applications. In such cases, specialized metrics targeted to the specific problem may be required, as discussed in Sec.~\ref{sec:cross-topic}. Metrics such as \ac{RI} \cite{rand1971objective} and \ac{VoI} \cite{meilua2003comparing}, for example, allow to skip the steps of matching predicted instances with reference instances (subprocesses S5, Fig.~\ref{fig:metric-selection:s5-localization-criterion} and S6, Fig.~\ref{fig:metric-selection:s6-assignment-strategy}). This is crucial for tasks with extremely dense and at the same time complex shapes (e.g. tissue images in electron microscopy) that feature similar size scales, where overlap-based localization criteria fail miserably. These metrics are further useful in cases where changes in topology are important which cannot be evaluated based on overlap-based criteria. On the downside, \ac{RI} and \ac{VoI} are based on counting pixel pairs and are thus not normalized on object size (large objects will dominate validation compared to smaller objects; see Fig.~\ref{fig:DSC-small}). Finally, as shown in \cite{arganda2015crowdsourcing}, both \ac{RI} and \ac{VoI}, while conceptually very different, potentially lead to the same ranking of predicted segmentations if the boundaries of the reference are thinned.
\item[Expected format of reference and algorithm output] The metric mapping expects the following format for instance segmentation with $C$ classes: For each object $O$ the reference consists of a tuple $(y_O, m_O)$, where $y_O \in \{1, .., C\}$ indicates the class of the object and $m_O \in \{0, 1\}^{H \times W}$ is a binary pixel map per instance matching the size of the image (height $H$ and width $W$) and indicating pixel-wise location. The algorithm output for an object prediction $O$ is expected to comprise a tuple $(\hat{y}_O, \hat{m}_O)$, where, similarly to object detection, $\hat{y}_O$ indicates a single predicted class ($\hat{y}_O \in \{1, .., C\}$) optionally accompanied by an associated predicted class score ($\hat{y}_O \in [0, 1]$). See F5.1 in case no predicted class probability is provided. $\hat{m}_O$ denotes a binary pixel map per instance analogously to $m_O$. Note that annotations from semantic segmentation (not distinguishing instances of the same class) can be transformed to the instance segmentation format via connected component analysis (in case of purely non-touching instances).
\end{description}
The traversal through the decision tree of our framework for the specific task of cell nuclei instance segmentation in time-lapse light microscopy is illustrated in Fig.~\ref{fig:scenario-od-polyp}. The resulting recommendations for localization/assignment strategies and metrics can be found in Fig.~\ref{fig:scenario-table}.
\begin{figure}[H]
\centering
\includegraphics[width=1\linewidth]{images/Scenarios/Scenarios_table.pdf}
\caption{\textbf{Instantiation of the framework with recommendations for concrete biomedical questions.} \textbf{a)} Disease classification in dermoscopic images \citep{codella2019skin}, \textbf{b)} liver segmentation in computed tomography images \citep{antonelli2021medical, simpson2019large}, \textbf{c)} polyp detection in colonoscopy videos with predefined sensitivity of 0.98 \citep{sanchez2019computer, bernal2019gtcreator} and \textbf{d)} cell nuclei instance segmentation in time-lapse light microscopy with a subsequent goal of cell tracking \citep{ulman2017objective}. The corresponding traversals through the decision trees are shown in App.~\ref{app:scenarios}.}
\label{fig:scenario-table}
\end{figure}
\newpage
\section{Cross-category Recommendations}
\label{sec:cross-topic}
The consortium is currently compiling the cross-category recommendations on the following topics:
\subsection{Selecting Non-Reference-Based Metrics}
For a given biomedical application, properties beyond the agreement of the algorithm output and a reference may be of crucial importance. This section will therefore give recommendations on how to assess common complementary properties, namely run time, memory consumption and carbon footprint.
\subsection{Determining the Global Decision Threshold}
Metrics from the families of counting metrics and distance-based metrics require a threshold to be set on the predicted class scores in order to generate the confusion matrix or the structure boundaries. Importantly, this threshold needs to be globally used for all validation metrics. This paragraph will give recommendations with respect to setting the global decision threshold.
\subsection{Aggregating Metric Values}
Aggregating metric values from multiple test cases of a given test set is not necessarily trivial and multiple pitfalls exist, as demonstrated in App.~\ref{sec:pitf:aggregation-combination}. This section will therefore provide recommendations with respect to metric aggregation.
\subsection{Reporting Metric Results}
Finally, several pitfalls exist with respect to reporting metrics results (see e.g. Fig.~\ref{fig:raw-metric-values-boxplot}). This section will therefore give recommendations with respect to result reporting.
\newpage
\section{Current Status and How to Provide Feedback}
The most important intermediate results of the international Delphi process have been summarized in the previous section. The consortium is currently working on (1) cross-category recommendations with a specific focus on how to apply selected metrics appropriately to a given data set as well as on (2) a toolkit implementing the entire framework in a user-friendly manner. At this stage, we explicitly invite the research community to challenge our current proposal and provide constructive feedback by replying to this questionnaire: \textcolor{blue}{\url{https://onlinesurvey.dkfz.de/index.php/454312?lang=en}}; both short one-click and comprehensive feedback is possible. The final recommendation will be made publicly available once the Delphi process has been completed.
\section*{Acknowledgements}
This work was initiated by the Helmholtz Association of German Research Centers in the scope of the Helmholtz Imaging Incubator (HI), the MICCAI special interest group on biomedical image analysis challenges and the benchmarking working group of the MONAI initiative. It was further supported in part by the Intramural Research Program of the National Institutes of Health Clinical Center as well as by the National Cancer Institute (NCI) and the National Institute of Neurological Disorders and Stroke (NINDS) of the National Institutes of Health (NIH), under award numbers NCI:U01CA242871 and NINDS:R01NS042645. The content of this publication is solely the responsibility of the authors and does not represent the official views of the NIH. S.A. Tsaftaris acknowledges the support of Canon Medical and the Royal Academy of Engineering and the Research Chairs and Senior Research Fellowships scheme (grant RCSRF1819\textbackslash 825).
We would like to thank Silvia D. Almeida, Michael Baumgartner, Ahmad Bin Qasim, Dimitrios Bounias, Till Bungert, Kris Dreher, Maximilian Fischer, Niklas Holzwarth, Marco Hübner, Lukas Klein, Gregor Köhler, Bálint Kovács, Xiao Liu, Dominik Michael, Lucas-Raphael Müller, Tobias Norajitra, Maike Rees, Melanie Schellenberg, Silvia Seidlitz, Jan Sellner, Akriti Srivastava, Andrea Marheim Storås, Vajira Thambawita, Constantin Ulrich and Tassilo Wald for testing the metric mappings.
\bibliographystyle{ACM-Reference-Format}
\subsection{Fundamentals of Metrics}
\label{sec:pitf:fundamentals}
The present work focuses on biomedical image analysis problems that can be interpreted as a classification task at image, object or pixel level. The vast majority of metrics for these problem categories is directly or indirectly based on epidemiological principles of \acf{TP}, \acf{FN}, \acf{FP}, \acf{TN}, i.e. the \textit{cardinalities} of the so-called confusion matrix, depicted in Fig.~\ref{fig:metric-families}. The \ac{TP}/\ac{FN}/\ac{FP}/\ac{TN}, from now on referred to as cardinalities. In the case of more than two classes $C$ we also refer to the entries of the $C \times C$ confusion matrix as cardinalities. For simplicity and clarity in notation, we restrict ourselves to the binary case in most examples. Cardinalities can be computed for image (segment), object or pixel level. They are typically computed by comparing the prediction of the algorithm to a reference annotation. Modern neural network-based approaches typically require a threshold to be set in order to convert the algorithm output comprising predicted class scores (also referred to as continuous class scores) to a confusion matrix, as illustrated in Fig.~\ref{fig:metric-families}. For the purpose of metric recommendation, the available metrics can be broadly classified as follows:
\begin{itemize}
\item \textbf{Counting metrics} operate directly on the confusion matrix and express the metric value as a function of the cardinalities (see Figs.~\ref{fig:def-classification-1}, \ref{fig:def-classification-2} and~\ref{fig:definition-overlap}). In the context of segmentation, they have typically been referred to as \textbf{overlap-based} metrics~\cite{taha2015metrics}. We distinguish \textbf{multi-class counting metrics}, which are defined for an arbitrary number of classes and invariant under class order, from \textbf{per-class counting metrics}, which are computed by treating one class as foreground/positive class and all other classes as background. Popular examples for the former include \textit{\ac{MCC}}, \textit{Accuracy}, and \textit{Cohen's Kappa $\kappa$}, while examples for the latter are \textit{Sensitivity}, \textit{Specificity}, \textit{\ac{PPV}}, \textit{\ac{DSC}} and \textit{\ac{IoU}}.
\item \textbf{Multi-threshold metrics} operate on a dynamic confusion matrix, reflecting the conflicting properties of interest, such as high \textit{Sensitivity} and high \textit{Specificity}. Popular examples include the \textit{\ac{AUROC}} (see Fig.~\ref{fig:def-auc}) and \textit{\ac{AP}} (see Fig.~\ref{fig:ap-example}).
\item \textbf{Distance-based metrics} have been designed for semantic and instance segmentation tasks. They operate exclusively on the \ac{TP} and rely on the explicit definition of object boundaries (see Figs.~\ref{fig:definition-distance} and~\ref{fig:definition-nsd}). Popular examples are the \textit{\ac{HD}} and the \textit{\ac{NSD}} (see Fig.~\ref{fig:definition-nsd}).
\end{itemize}
Depending on the context (e.g. image-level classification \textit{vs.} semantic segmentation task) and the community (e.g. medical imaging community \textit{vs.} computer vision community), identical metrics are referred to with different terminology. For example, \textit{Sensitivity}, \textit{\ac{TPR}} and \textit{Recall} refer to the same concept. The same holds true for the \textit{\ac{DSC}} and the \textit{F$_1$ Score}. The most relevant metrics for the problem categories in the scope of this paper are introduced in the following.
Most metrics are recommended to be applied per class (except the multi-class counting metrics), meaning that a potential multi-class problem is converted to multiple binary classification problems, such that each relevant class serves as the positive class once. This results in different confusion matrices depending on which class is used as the positive class.
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Relationships between metric families, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Fig1_zoom2_v5.pdf}
\caption{Most popular metric families and their relationships relevant for the problem categories addressed by this paper. The vast majority of metrics is directly or indirectly based on the cardinalities of the confusion matrix. The available metrics can be broadly classified into \textbf{counting metrics} that operate directly on the confusion matrix generated for a fixed threshold, \textbf{multi-threshold metrics} that operate on a dynamic confusion matrix (depending on threshold) and \textbf{distance-based metrics} that take into account the structure contour(s) or other spatial information, such as the structure center. Further abbreviations: \acf{AUROC}, \acf{AP}, \acf{DSC}, \acf{FPPI}, \acf{FPR}, \acf{HD}, \acf{IoU}, \acf{NSD}, \acf{PPV}, \acf{TNR}, \acf{TPR}.}
\label{fig:metric-families}
\end{tcolorbox}
\end{figure}
\subsubsection{Image-level Classification}
\label{sec:pitf:fundamentals_ilc}
\hfill\\\textbf{Image-level classification} refers to the process of assigning one or multiple labels, or \textit{classes}, to an image. If there is only one class of interest (e.g. cancer \textit{vs.} no cancer), we speak of \textit{binary classification}, otherwise of \textit{categorical classification}. Modern algorithms usually output \textbf{predicted class probabilities} (or continuous class scores) between 0 and 1 for every image and class, indicating the probability of the image belonging to a specific class. By introducing a threshold (e.g. 0.5), predictions are considered as positive (e.g. cancer = true) if they are above the threshold or negative if they are below the threshold. Afterwards, predictions are assigned to the cardinalities (e.g. a cancer patient with prediction cancer = true is considered as \ac{TP}) \cite{davis2006relationship}. The most popular classification metrics are counting metrics, operating on a confusion matrix with fixed threshold on the class probabilities, and multi-threshold metrics, as detailed in the following.
\paragraph{\textbf{Counting metrics}}
The most common binary counting metrics used for image-level classification are presented in Figs.~\ref{fig:def-classification-1} (per-class) and \ref{fig:def-classification-2} (multi-class). Please note that these metrics are also commonly used in segmentation and object detection tasks. For segmentation tasks, they are often referred to as overlap-based metrics. Each of the presented metrics covers specific properties.
The \textit{Sensitivity} (also referred to as \textit{Recall}, \textit{\ac{TPR}} or \textit{Hit rate}) focuses on the actual positives (\ac{TP} and \ac{FN}) and represents the fraction of positives that were correctly detected as such. In contrast, \textit{\ac{PPV}} (or \textit{Precision}) divides the \ac{TP} by the total number of predicted positive cases, thus aiming to represent the probability of a positive prediction corresponding to an actual positive. A value of 1 would imply that all positive predicted cases are actually positives, but it might still be the case that positive cases were missed. Please note that the term \textit{\ac{PPV}} has multiple meanings. In the context of computer assisted interventions, for example, it typically refers to the measured variance. Hence, the usage of its synonym \textit{\ac{PPV}} may be preferred.
In analogy to the \textit{Sensitivity} for positives, \textit{Specificity} (also referred to as \textit{Selectivity} or \textit{\ac{TNR}}) focuses on the negative cases by computing the fraction of negatives that were correctly detected as such. Similarly to the \textit{\ac{PPV}}, the \textit{\ac{NPV}} divides the \ac{TN} by the total number of predicted negative cases and measures how many of the predicted negative samples were actually negative. \textit{Specificity} and \textit{\ac{NPV}} require the definition of \ac{TN} cases, which is not always possible. In object detection tasks, for example (see App.~\ref{sec:pitf:fundamentals_od}), \ac{TN} are typically ill-defined and not provided. Therefore, these measures can not be computed in those cases.
\textit{\ac{PPV}} and \textit{\ac{NPV}} provide quantities of direct interest to the medical practitioner, namely the probability of a certain event given the prediction of the classifier. However, unlike \textit{Sensitivity} and \textit{Specificity}, they are not only functions of the classifier but also of the study population. Hence, one cannot extrapolate from one population (e.g. from a case-control study) to another (general population without correcting for prevalence). In the case of the prevalence being unequal to 0.5, prevalence correction should be applied (see Fig.~\ref{fig:prevalence}):
\begin{equation}
PPV = \frac{Sensitivity \cdot Prevalence}{Sensitivity \cdot Prevalence + (1 - Specificity) \cdot (1 - Prevalence)}
\end{equation}
\begin{equation}
NPV = \frac{Specificity \cdot (1 - Prevalence)}{Specificity \cdot (1 - Prevalence) + (1 - Sensitivity) \cdot Prevalence}
\end{equation}
As illustrated in Fig.~\ref{fig:class-imbalance}, reporting of a single metric such as \textit{Sensitivity}, \textit{\ac{PPV}} or \textit{Specificity} can be highly misleading because, for example, non-informative classifiers can achieve high values on imbalanced classes. The \textit{F$_1$ Score} (also known as \textit{\ac{DSC}} in the context of segmentation), overcomes this issue by representing the harmonic mean of \textit{\ac{PPV}} and \textit{Sensitivity} and therefore penalizing extreme values of either metric~\cite{hicks2021evaluation}, while being relatively robust against imbalanced data sets~\cite{Sun2009imbalanced}. The \textit{F$_1$ Score} is a specification of the \textit{F$\beta$ score}, which adds a weighting between \textit{\ac{PPV}} and \textit{Sensitivity}. For higher values of $\beta$, \textit{Sensitivity} is given a higher weight over \textit{\ac{PPV}}, which might be desired depending on the application. More specifically, the \textit{F$\beta$ Score} weights between \ac{FP} and \ac{FN} samples. Another metric which combines the metrics above is the \ac{LR+}, which is the ratio of the \textit{Sensitivity} and 1-\textit{Specificity} (\textit{\ac{FPR}}). This metric is described as the "probability that a positive test would be expected in a patient divided by the probability that a positive test would be expected in a patient without a disease" \citep{shreffler2020diagnostic}. It is defined as odds ratio and therefore invariant to the prevalence \citep{vsimundic2009measures}.
All of the metrics presented so far are bounded between 0 and 1 with 1 representing a perfect value and 0 the worst possible prediction of this metric. However, all of them rely on the definition of the positive class, which may be straightforward in some cases but can be based on a rather arbitrary choice in others. Notably, metric values may be completely different depending on the choice of positive class \cite{powers2020evaluation}.
To overcome the need for selecting one class as the positive class, other metrics have been suggested that can be based on all entries of a \textit{multi-class} confusion matrix, in which each class is assigned a row and a column of the matrix. The \textit{Accuracy} is one of the most commonly used metrics and measures the ratio between all correct predictions (\ac{TP} and \ac{TN}) and the total number of samples. \textit{Accuracy} is not robust against imbalanced data sets (see Fig.~\ref{fig:class-imbalance}), and is therefore often replaced by the more robust \textit{\ac{BA}} that averages the \textit{Sensitivity} over all classes \cite{grandini2020metrics}. For two classes, the metric averages \textit{Sensitivity} and \textit{Specificity}. An alternative is \textit{Youden's Index J} or \textit{\ac{BM}}, similarly summing up \textit{Sensitivity} per class (or for two classes, summing up \textit{Sensitivity} and \textit{Specificity}). Note that \textit{Youden's Index J} and \textit{\ac{BA}} are closely related and can directly be calculated from the other as $J = 2BA - 1$ and $BA = (J+1)/2$.
The \textit{\ac{MCC}}, also known as \textit{Phi Coefficient}, measures the correlation between the actual and predicted class. The metric is bounded between -1 and 1, with high positive values referring to a good prediction which can only be achieved when all cardinalities are good, i.e. with a low number of \ac{FP}/\ac{FN} and high \ac{TP}/\ac{TN}. Another popular metric is \textit{Cohen's Kappa $\kappa$}, which calculates the agreement between the reference and prediction while incorporating information on the agreement by chance. It is therefore a form of chance-corrected \textit{Accuracy}. Similarly to \textit{\ac{MCC}}, it incorporates all values of the confusion matrix and is bounded between -1 and 1. In contrast to \textit{\ac{MCC}}, negative values do not indicate anti-correlation, but less agreement than expected by chance. \textit{Cohen's Kappa $\kappa$} can be generalized by introducing a weighting scheme for the cardinalities in the \textit{Weighted Cohen's Kappa $\kappa$} metric. For those three metrics, a value of 0 refers to a prediction which is not better than random guessing.
All of the presented binary counting metrics can be transferred to the multi-class case~\cite{hossin2015review, grandini2020metrics}, where \textit{\ac{MCC}} and \textit{(Weighted) Cohen's Kappa $\kappa$} have explicit definitions, whereas the others become the implicit result of an aggregation across a rotating one-versus-the-rest binary perspective for each of the classes.
\paragraph{\textbf{Multi-threshold metrics}}
The classical counting metrics presented above rely on fixed thresholds to be set on the predicted class probabilities (if available), resulting in them being based on the cardinalities of the confusion matrix.\textbf{ Multi-threshold metrics} overcome this limitation by calculating metric scores based on multiple thresholds. For instance, to emphasize how well a prediction distinguishes between the positive and negative class, the \textit{\ac{AUROC}} can be utilized. The \textit{\ac{ROC}} curve plots the \textit{\ac{FPR}}, which is equal to $1-Specificity$, against the \textit{Sensitivity} for multiple thresholds of the predicted class probabilities, contrarily to just choosing one fixed threshold. For computation of the ROC curve, the class scores can be ordered in descending order and each score regarded as a potential threshold. For each threshold, the resulting \textit{Sensitivity} and \textit{Specificity} are computed, and the resulting tuple is added to the \textit{\ac{ROC}} curve as one point (cf. Fig.~\ref{fig:def-auc}); note that the lower the threshold, the higher the \textit{Sensitivity} but the lower (potentially) the \textit{Specificity}. This leads to a monotonic increase of the curve. To interpolate between all points, i.e. to approximate the values between the calculated \textit{Sensitivity} and \textit{Specificity} tuples, a simple linear interpolation can be employed by drawing a line between each pair of points~\cite{davis2006relationship}. An optimal classifier would lead to \textit{Sensitivity} and \textit{Specificity} of 1 (1-\textit{Specificity} of 0), therefore corresponding to a single point $(0,1)$ on the \textit{\ac{ROC}} curve. In contrast, a classifier with no skill level (random guessing) would result in a diagonal line from $(0,0)$ to $(1,1)$ (dashed line in Fig.~\ref{fig:def-auc}). The area under the \textit{\ac{ROC}} curve is referred to as \textit{\ac{AUROC}}, also called \textit{AUC ROC} or simply \textit{AUC}.
\textit{\ac{AUROC}} comes with two advantages: threshold and scale invariance. \textit{\ac{AUROC}} measures the quality of the predictions regardless of the threshold, as it is calculated over a number of thresholds. Furthermore, \textit{\ac{AUROC}} does not focus on the absolute values of predictions, but rather on how well they are ranked. However, those properties are not always desired. If a specific penalization of \ac{FP} or \ac{FN} is desired (cf. Fig.~\ref{fig:unequal-class}), \textit{\ac{AUROC}} is not the best metric choice as it is invariant to the threshold. If the predicted class probabilities are intended to be well calibrated, the scale invariance feature will prevent from doing so.
Per definition, \textit{\ac{AUROC}} measures the complete area under the \textit{\ac{ROC}} curve. If only a specific range is of interest, a partial or ranged \textit{\ac{AUROC}} can also be computed \cite{ma2013use}. Similarly, metrics can be assessed at a certain point of the \textit{\ac{ROC}} curve, for example the \textit{Sensitivity} value at a specific score of the \textit{Specificity} (e.g. 0.9), also referred to as \textit{Sensitivity@Specificity}. This approach can similarly be used for other curve measures, e.g. the \textit{\ac{PR}} curve, introduced in App.~\ref{sec:pitf:fundamentals_od}, and is illustrated in Fig.~\ref{fig:def-auc}.
\begin{figure}[H]
\begin{tcolorbox}[title= Common binary classification metrics: Per-class counting-based, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Classification/Classification_counting_simple.png}
\caption{Overview of the most commonly used per-class counting classification measures that are based on the cardinalities of the confusion matrix, i.e. the true (T)/false (F) positives (P)/negatives (N) in the binary case.}
\label{fig:def-classification-1}
\end{tcolorbox}
\end{figure}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Common binary classification metrics: Multi-class counting-based, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Classification/Classification_counting_complex.png}
\caption{Overview of the most commonly used multi-class counting classification measures that are based on the cardinalities of the confusion matrix, i.e. the true (T)/false (F) positives (P)/negatives (N) in the binary case.}
\label{fig:def-classification-2}
\end{tcolorbox}
\end{figure}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Common classification metrics: Multi-threshold-based, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Classification/AUC_PR.png}
\caption{Principle of multi-threshold metrics (top) and per-class counting metrics with application-driven thresholds (bottom). Rather than being based on a static threshold (e.g. for generating the confusion matrix), multi-threshold-based metrics integrate over a range of thresholds. Prominent examples are the \textit{\acf{AUROC}} (also known as \textit{\acf{AUC}} or \textit{AUC \acf{ROC}}) and the Area under the \textit{\acf{PR}} curve (\textit{AUC PR}). Cardinalities, i.e. the true (T)/false (F) positives (P)/negatives (N), are computed based on a threshold (e.g. 0.5) of predicted class probabilities (left). Based on those values, \textit{Sensitivity} (also known as \textit{Recall}) and \textit{1 - Specificity}/\textit{\acf{PPV}} are calculated and plotted against each other (right). The procedure is repeated for several thresholds, resulting in the \textit{\ac{ROC}}/\textit{\ac{PR}} curve. The area under the \textit{\ac{ROC}}/\textit{\ac{PR}} curve is referred to as \textit{\ac{AUROC}}/\textit{AUC PR}. The latter is often interpolated by the \textit{\acf{AP}} metric as detailed in Fig.~\ref{fig:ap-example}. The dashed gray lines refer to a classifier with no skill level (random guessing). In the case of an application-driven threshold (e.g. required \textit{Sensitivity} of 0.9), the metrics \textit{Sensitivity@Specificity}, \textit{Specificity@Sensitivity}, \textit{\ac{PPV}@Sensitivity} and \textit{Sensitivity@\ac{PPV}} can be calculated on the basis of the the \textit{\ac{ROC}}/\textit{\ac{PR}} curves.}
\label{fig:def-auc}
\end{tcolorbox}
\end{figure}
\newpage
\subsubsection{Semantic Segmentation}
\label{sec:pitf:fundamentals_ss}
\hfill\\\textbf{Semantic segmentation} Semantic segmentation is commonly defined as the process of partitioning an image into multiple segments/regions. To this end, one or multiple labels are assigned to every pixel such that pixels with the same label share certain characteristics. Semantic segmentation can therefore also be regarded as pixel-level classification. As in image-classification problems, predicted class probabilities are typically calculated for each pixel deciding on the class affiliation based on a threshold over the class scores \cite{asgari2021deep}. In semantic segmentation problems, the pixel-level classification is typically followed by a post-processing step, in which connected components are defined as objects, and object boundaries are created accordingly. Semantic segmentation metrics can roughly be classified into three classes: (1) counting metrics or overlap-based metrics, for measuring the overlap between the reference annotation and the prediction of the algorithm, (2) distance-based metrics, for measuring the distance between object boundaries, and (3) problem-specific metrics, measuring, for example, the volume of objects.
\paragraph{\textbf{Counting metrics}} The most frequently used segmentation metrics are \textbf{counting metrics}. In the context of segmentation they are also referred to as \textbf{overlap metrics}, as they essentially measure the overlap between a reference mask and the algorithm prediction. According to a comprehensive analysis of biomedical image analysis challenges~\cite{maier2018rankings}, the \textit{\ac{DSC}} \citep{dice1945measures} is the by far most widely used metric in the field of medical image analysis. As illustrated in Fig.~\ref{fig:definition-overlap}, it yields a value between 0 (no overlap) and 1 (full overlap). The \textit{\ac{DSC}} is identical to the \textit{F$_1$ Score} and closely related to the \textit{\ac{IoU}}, which is identical to the \textit{Jaccard Index}:
\noindent\hspace{-1cm}\begin{minipage}{.5\linewidth}
\begin{equation}
\label{eq:iou-dsc}
IoU = \frac{DSC}{2-DSC}
\end{equation}
\end{minipage}
\begin{minipage}{.5\linewidth}
\begin{equation}
\label{eq:dsc-iou}
DSC = \frac{2 IoU}{1+IoU}
\end{equation}
\end{minipage}
\paragraph{\textbf{Distance-based metrics}} Overlap-based metrics are often complemented by \textbf{distance-based metrics} that operate exclusively on the \ac{TP} and compute one or several distances between the reference and the prediction. Apart from a few exceptions, distance-based metrics are often \textbf{boundary-based metrics} which focus on assessing the accuracy of object boundaries. According to~\cite{maier2018rankings}, the \textit{\ac{HD}} and its 95\% percentile variant (\textit{\ac{HD95}})~\citep{huttenlocher1993comparing} are the most commonly used boundary-based metrics. The \textit{\ac{HD}} calculates the maximum of all shortest distances for all points from one object boundary to the other, which is why it is also known as the \textit{Maximum Symmetric Surface Distance} \cite{yeghiazaryan2018family}. The \textit{\ac{HD95}} calculates the 95\% percentile instead of the maximum, therefore disregarding outliers (see Fig.~\ref{fig:definition-distance}). Another popular metric is the \textit{\ac{ASSD}}, measuring the average of all distances for every point from one object to the other and vice versa \citep{van20073d, yeghiazaryan2018family}. However, if one boundary is much larger than the other, it will impact the score much more. This is avoided by the \textit{\ac{MASD}} \cite{benevs2015performance}, which treats both structures equally by computing the average distance from structure $A$ to structure $B$ and the average distance from structure $B$ to structure $A$ and averaging both (see Fig.~\ref{fig:definition-distance-assd-masd}). For the \textit{\ac{HD}(95)}, \textit{\ac{MASD}} and \textit{\ac{ASSD}} metrics, a value of 0 refers to a perfect prediction (distance of 0 to the reference boundary), while there exists no fixed upper bound. The \textit{Boundary \ac{IoU}} (cf. Fig.~\ref{fig:definition-boundary-iou}) is another option for measuring the boundary quality of a prediction. It measures the overlap between prediction and reference up to a certain width (which is controlled by the width parameter $d$) (see App.~\ref{sec:pitf:fundamentals_od} for details) and is bounded between 0 and 1.
A major problem related to boundary-based metrics are the error-prone reference annotations (see Figs.~\ref{fig:low-quality} and \ref{fig:DSC-artifact}). In fact, domain experts often disagree on the definition and annotation of objects and their boundaries \cite{joskowicz2019inter}. While the \textit{\ac{HD}(95)} and \textit{\ac{ASSD}} are not robust with respect to uncertain reference annotations, the \textit{\ac{NSD}} was explicitly designed for this purpose as a hybrid metric between boundary-based and counting-based approaches. Known uncertainties in the reference as well as acceptable deviations of the predicted boundary from the reference are captured by a threshold $\tau$ \cite{nikolov2021clinically}, as shown in Fig.~\ref{fig:definition-nsd}. Only boundary parts within the border regions defined by $\tau$ are counted as \ac{TP}. The metric is bounded between 0 (no boundary overlap) and 1 (full boundary overlap), so that it can be interpreted similarly to the classical \textit{\ac{DSC}} (though restricted to the boundary). Please note that $\tau$ is another important hyperparameter which should be chosen wisely, based on inter-rater agreement, for example.
\paragraph{\textbf{Problem-specific segmentation metrics}}
While overlap-based metrics and distance-based metrics are the standard metrics used by the general computer vision community, biomedical applications often have special domain-specific requirements. In medical imaging, for example, the actual volume of an object may be of particular interest (for example tumor volume). In this case, \textbf{volume metrics} such as the \textit{Absolute} or \textit{Relative Volume Error} and the \textit{Symmetric Relative Volume Difference} can be computed \cite{nai2021comparison}. However, they are less common than overlap metrics, as the location of objects is not considered at all (see Fig.~\ref{fig:center}). If the structure center or center line is of particular interest (e.g. in cells or vessels), \textbf{connectivity metrics} come into play, which measure the agreement of the center line between two objects. This is of special interest if linear or tube-like objects are present in a data set, for example in brain vascular analysis. In these cases, over- or undersegmentation are typically not of special interest, with the focus rather being on connectivity or network topology. For this purpose, the \textit{\ac{clDice}} \cite{shit2021cldice} has been designed. For computation, the reference and prediction skeletons need to be extracted from the binary masks. Multiple approaches have been proposed, as described in \cite{shit2021cldice}. As shown in Fig.~\ref{fig:definition-cldice}, the \textit{\ac{clDice}} is then defined as the harmonic mean of \textit{Topology Precision} and \textit{Topology Sensitivity}. The \textit{Topology Precision} measures the ratio of the overlap of the skeleton of the prediction skeleton and the reference mask and the skeleton of the prediction. Similarly to \textit{Precision}, it measures the \ac{FP} samples. On the other hand, \textit{Topology Sensitivity} incorporates \ac{FN} samples by measuring the ratio of the overlap of the skeleton of the reference and the prediction mask and the reference skeleton.
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Common segmentation metrics: Overlap-based, colback=white]
\centering
\hspace{-0.5cm}
\includegraphics[width=0.8\linewidth]{pitfall-paper/images/Segmentation/Definition_DSC_IoU.pdf}
\caption{Most commonly used overlap-based segmentation metrics: \textbf{(a)} the \textit{\acf{DSC}} and \textbf{(b)} the \textit{\acf{IoU}}, with $\vert A\vert$ denoting the cardinality of set $A$, $A \cap B$ the intersection between sets $A$ and $B$, and $A \cup B$ the union of sets $A$ and $B$. The \textit{\ac{DSC}} can furthermore be computed as the harmonic mean of \textit{\acf{PPV}} and \textit{Sensitivity}. Note that the \textit{\ac{DSC}} is equivalent to the \textit{F$_1$ Score} and the \textit{\ac{IoU}} is equivalent to the \textit{Jaccard index}.}
\label{fig:definition-overlap}
\end{tcolorbox}
\end{figure}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Common segmentation metrics: Boundary-based (Part 1), colback=white]
\centering
\hspace{-0.5cm}
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/Definition_HD_HD95.png}
\caption{Most commonly used distance-based segmentation metrics: \textbf{(a)} the \textit{\acf{HD}} and \textbf{(b)} the 95\% percentile (denoted as $x_{95}$) \textit{\acf{HD95}}. The Euclidean distance between boundary pixels $a$ and $b$ is defined as $d(a,b)$. Only True Positives (TP) are considered.}
\label{fig:definition-distance}
\end{tcolorbox}
\end{figure}
\begin{figure}[H]
\begin{tcolorbox}[title= Common segmentation metrics: Boundary-based (Part 2), colback=white]
\centering
\hspace{-0.5cm}
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/Definition_ASSD_MASD.png}
\caption{Most commonly used distance-based segmentation metrics: \textbf{(a)} the \textit{\acf{ASSD}} and \textbf{(b)} the \textit{\acf{MASD}}. The Euclidean distance between boundary pixels $a$ and $b$ is defined as $d(a,b)$. Only \acf{TP} are considered.}
\label{fig:definition-distance-assd-masd}
\end{tcolorbox}
\end{figure}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Common segmentation metrics: \acf{NSD}, colback=white]
\centering
\hspace{-0.5cm}
\includegraphics[width=0.9\linewidth]{pitfall-paper/images/Segmentation/Definition_NSD_v2.pdf}
\caption{\textbf{(a)} The \textit{\acf{NSD}} is an \textbf{uncertainty-aware} segmentation metric that measures the overlap between two boundaries. The parameter $\tau$ represents the tolerated difference between the prediction and the reference boundary $S$ and defines the border regions $\mathcal{B^{(\tau)}}$ for each structure, i.e. the pixels within the range of $\tau$ from the boundary. They are defined as all pixels within distance $\tau$ from the boundary $S$. The threshold can be based on the domain-related requirements and/or the inter-rater variability, for example. \textbf{(b)} Example showing how the \textit{\ac{NSD}} can handle outliers in the prediction by adjusting the tolerance value to $\tau=2$ pixels. The \textit{\acf{DSC}} and other metrics (\textit{\acf{IoU}}, \textit{\acf{HD}(95)}, \textit{\acf{ASSD}}), in contrast, penalize these tolerated errors.}
\label{fig:definition-nsd}
\end{tcolorbox}
\end{figure}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Common segmentation connectivity metrics: \acf{clDice}, colback=white]
\centering
\hspace{-0.5cm}
\includegraphics[width=\linewidth]{pitfall-paper/images/Segmentation/clDice_def.png}
\caption{The \textit{\acf{clDice}} measures the \textbf{connectivity} of structures. As designed for tubular structures, the metric relies on the skeletons of the structures, given by $S_A$ and $S_B$ for structures $A$ and $B$ in this case. The \textit{\ac{clDice}} is defined as the harmonic mean of the \textit{Topology precision} and \textit{Topology sensitivity}. $\vert S_A\vert$ denotes the cardinality of the skeleton $S_A$ and $S_B \cap A$ refers to the intersection between the skeleton $S_B$ and mask $A$ (similar for $S_A \cap B$).}
\label{fig:definition-cldice}
\end{tcolorbox}
\end{figure}
\newpage
\subsubsection{Object Detection}
\label{sec:pitf:fundamentals_od}
\hfill\\\textbf{Object detection} refers to the detection of one or multiple objects (or: instances) of a particular class (e.g. lesion) in an image \cite{lin2014microsoft}. The following description assumes single-class problems, but translation to multi-class problems is straightforward, as validation for multiple classes on object level is performed individually per class. Notably, as multiple predictions and reference instances may be present in one image, the predictions need to include localization information, such that a matching between reference and predicted objects can be performed. Important design choices with respect to the validation of object detection methods include:
\begin{enumerate}
\item \textit{How to represent an object?} Representation is typically composed of location information and a class affiliation. The former may take the form of a bounding box (i.e. a list of coordinates), a pixel mask, or the object's center point. Additionally, modern algorithms typically assign a confidence value to each object, representing the probability of a prediction corresponding to an actual object of the respective class. Note that a confusion matrix is later computed for a fixed threshold on the predicted class probabilities.\footnote{Please note that we will use the term confidence scores analogously to predicted class probabilities in the context of object detection and instance segmentation.}
\item \textit{How to decide whether a reference instance was correctly detected?} This step is achieved by applying the \textit{localization criterion}. This may, for example, be based on comparing the object centers of the reference and prediction or computing their overlap (Figs.~\ref{fig:hit-criteria} and~\ref{fig:bb-2d-3d}).
\item \textit{How to resolve assignment ambiguities?} The above step might lead to ambiguous matchings, such as two predictions being assigned to the same reference object. Several strategies exist for resolving such cases.
\end{enumerate}
\noindent
The following sections provide details on (1) applying the localization criterion, (2) applying the assignment strategy and (3) computing the actual performance metrics.
Please note that localization performance does not regard anatomical constraints. A tumor growing invasively into neighboring structures might have good metric scores, while clinically the localization/classification/impact for the patient might be disastrous.
\paragraph{\textbf{Localization criterion}}
As one image may contain multiple objects or no object at all, the \textbf{localization criterion} or \textbf{hit criterion} measures the (spatial) similarity between a prediction (represented by a bounding box, pixel mask, center point or similar) and a reference object. It defines whether the prediction \textit{hit/detected} (\ac{TP}) or \textit{missed} (\ac{FP}) the reference. Any reference object not detected by the algorithm is defined as \ac{FN}. Please note that \ac{TN} are not defined for object detection tasks, which has several implications on the applicable metrics, as detailed below.
There are multiple ways to define the localization or hit criterion (see Figs.~\ref{fig:definition-overlap}, \ref{fig:definition-boundary-iou} and \ref{fig:hit-criteria}). Popular center-based localization criteria are (a) \textit{the center-cover criterion}, for which the reference object is considered hit if the center of the reference object is inside the predicted detection, (b) the \textit{distance-based hit criterion}, which considers a \ac{TP} if the distance $d$ between the center of the reference and the detected object is smaller than a certain threshold $\tau$ and (c) the \textit{center-hit criterion}, which holds true if the center of the predicted object is inside the reference bounding box or mask.
The most commonly used overlap-based hit criterion is determined by computing the \textit{\ac{IoU}} \citep{jaccard1912distribution} (cf. Fig.~\ref{fig:definition-overlap}b). The prediction is considered as \ac{TP} if the overlap is larger than a certain threshold (e.g. 0.3 or 0.5) and as \ac{FP} otherwise. If bounding boxes are considered, the \textit{\ac{IoU}} is computed between the reference and predicted bounding boxes (\textit{Box IoU}). For more fine-grained annotations in form of a pixel mask, the \textit{\ac{IoU}} may be computed for the complete mask (\textit{Mask IoU}). The \textit{Mask IoU} is less sensitive to structure boundary quality in larger objects (cf. App.~\ref{sec:pitf:segmentation}). This is due to the fact that boundary pixels will increase linearly while pixels inside the structure will increase quadratically with an increase in structure size. The \textit{Boundary IoU} measures the \textit{\ac{IoU}} of two structures for mask pixels within a certain distance $d$ from the structure boundaries \cite{cheng2021boundary}, as illustrated in Fig.~\ref{fig:definition-boundary-iou}.
\begin{figure}[H]
\begin{tcolorbox}[title= Common localization criterion: Boundary Intersection over Union (Boundary IoU), colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/Definition_Boundary_IoU.pdf}
\caption{The \textit{Boundary Intersection over Union (Boundary IoU)} is an \textbf{uncertainty-aware} metric that measures the overlap between two boundaries. The overlap is computed for the structures $A$ and $B$ for mask pixels within a certain distance $d$ from the structure boundaries ($A_d$ and $B_d$), by computing the \textit{\ac{IoU}} between $A_d$ and $B_d$.}
\label{fig:definition-boundary-iou}
\end{tcolorbox}
\end{figure}
The localization criterion should be carefully chosen according to the underlying motivation and research question and depending on the available coarseness of annotations. However, it should be noted that annotations of a lower resolution will result in an information loss, as illustrated in Fig.~\ref{fig:od-information-loss}. For example, the \textit{Box IoU} is sometimes used although pixel-mask annotations are available because algorithms are expected to output rough localization in the shape of boxes. Such a simplification might cause problems if structures are not well-approximated by a box shape, or if structures can overlap causing multi-component masks (cf. App.~\ref{sec:pitf:detection}, Fig.~\ref{fig:disconnected}). Lastly, it should be noted that the decision for a cutoff value on the localization criterion leads to instabilities in the validation (e.g. see Fig.~\ref{fig:bb-2d-3d}). For this reason, it is common practice in the computer vision community to average metrics over multiple cutoff values (default for \textit{\ac{IoU}} criteria: 0.50:0.05:0.95 \cite{lin2014microsoft}). Generally speaking, the cutoff values should be chosen according to the driving biomedical question. For example, if particular interest lies on the exact outlines, higher thresholds should be chosen. On the other hand, for noisy reference standards, a low cutoff value is preferable.
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Discarding information of provided annotations, colback=white]
\centering
\includegraphics[width=0.7\linewidth]{pitfall-paper/images/Detection/od_annotation_information_loss.png}
\caption{Selection of a localization criterion that discards spatial information should be well motivated by the given task.}
\label{fig:od-information-loss}
\end{tcolorbox}
\end{figure}
\paragraph{\textbf{Assignment strategy}}
The localization criterion alone is not sufficient to extract the final confusion matrix based on a fixed threshold for the predicted class probabilities (confidence scores), as ambiguities can occur. For example, two predictions may have been assigned to the same reference object in the localization step, or vice versa. These ambiguities need to be resolved in a further \textbf{assignment step}, as exemplarily shown in Fig.~\ref{fig:od-assignment-strategy}.
This assignment and thus the resolving of potential assignment ambiguities can be done via different strategies. The most common strategy in the computer vision community is the \textit{Greedy by Score} strategy \cite{everingham2015pascal}. All predictions in an image are ranked by their predicted class probability and iteratively (starting with the highest probability) assigned to the reference object with the highest localization criterion for this prediction. The selected reference object is subsequently removed from the process since it can not be matched to any other prediction (unless double assignments are allowed). The \textit{Hungarian Matching} \cite{kuhn1955hungarian} is associated with a cost function, usually depending on the localization criterion, which is minimized to find the optimal assignment of predictions and reference. In the biomedical domain, more sophisticated matching strategies are often avoided by setting the localization criterion threshold to \textit{\ac{IoU}} > 0.5 and only allowing non-overlapping object predictions (which inherently avoids matching conflicts). In the case of a high ratio of touching reference objects and common non-split errors, meaning that one prediction overlaps with multiple reference objects, the Intersection over Reference (\textit{IoR}) \cite{matula2015cell} might be considered as an alternative to \textit{\ac{IoU}} \cite{matula2015cell} (see Fig.~\ref{fig:od-ior}).
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Example process of resolving a matching ambiguity, colback=white]
\centering
\includegraphics[width=0.7\linewidth]{pitfall-paper/images/Detection/AssignmentStrategy.pdf}
\caption{In case of multiple predictions that may be assigned to the same reference object, an assignment strategy needs to be chosen. This includes a decision on how to treat the remaining predictions. For example, they can be penalized with a \acf{FP} assignment or may be ignored. Used abbreviations: \textit{\acf{IoU}}, \textit{\acf{IoR}} and \acf{TP}.}
\label{fig:od-assignment-strategy}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Metric computation}}
Similar to image-level classification and semantic segmentation algorithms, object detection algorithms are commonly assessed with counting metrics, assuming a fixed confusion matrix, (cf. Figs.~\ref{fig:def-classification-1} and \ref{fig:def-classification-2}). However, one of the most popular object detection metrics is the multi-threshold metric \textit{\acf{AP}} \citep{lin2014microsoft}, which is the area under the \textit{\acf{PR}} curve for a certain interpolation scheme. The \textit{\ac{PR}} curve is computed similarly to the \textit{\ac{ROC}} curve by scanning over confidence thresholds and computing the \textit{Precision (\ac{PPV})} and \textit{Recall (Sensitivity)} for every threshold (cf. Fig.~\ref{fig:def-auc}). Note in this context that the popular \textit{\ac{ROC}} curve is not applicable in object detection tasks because \ac{TN} are not available. Also, while the ROC curve is monotonically rising, this behaviour may not be expected from the \textit{\ac{PR}} curve, which typically features a zigzag shape, as illustrated in Fig.~\ref{fig:ap-example}. Specifically "as the level of \textit{Recall} varies, the \textit{Precision} does not necessarily change linearly due to the fact that \ac{FP} replaces \ac{FN} in the denominator of the \textit{Precision} metric." \cite{davis2006relationship}. A linear interpolation would therefore be overly optimistic, which is why more complex interpolation is needed, as detailed in \cite{davis2006relationship}.
The area under the \textit{\ac{PR}} curve is typically calculated as the \textit{\ac{AP}} implying a conservative simplification of curve interpolation,
\begin{equation}
AP = \sum_n (R_n - R_{n-1})P_n,
\end{equation}
with $R_n$ and $P_n$ denoting the \textit{Recall} and \textit{Precision} at the $n$th threshold\footnote{\url{https://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.html}} (cf. dashed gray line in Fig.~\ref{fig:ap-example}). For the \textit{\ac{PR}} curve, an optimal model would lead to \textit{Recall (Sensitivity)} and \textit{Precision (\ac{PPV})} of 1, therefore being the point $(1,1)$ on the \textit{\ac{PR}} curve. Conversely, a model with no skill level (random guessing) would result in a horizontal line with a precision proportional to the portion of positive samples, i.e. the prevalence (dashed line in Fig.~\ref{fig:def-auc}). For computation of the metric (for a given class), the predictions are sorted in descending order of the confidence for each prediction (for that class). For each possible confidence threshold, the cardinalities are computed and the resulting tuple of \textit{Recall (Sensitivity)} and \textit{Precision} is added to the curve (cf. Fig.~\ref{fig:ap-example}).
In contrast to drawing the \textit{\ac{PR}} curve and computing the \textit{\ac{AP}}, \textit{\ac{FROC}} curve is often favoured in the clinical context due to its easier interpretability. It operates at object level and plots the average number of \textit{\ac{FPPI}} (in contrast to the \textit{\ac{FPR}}) against the \textit{Sensitivity} \cite{chakraborty2019analysis, van2010comparing} (cf. Fig.~\ref{fig:def-froc}). The \textit{\ac{FROC} Score}, measured as the area under the \textit{\ac{FROC}} curve, however, is not bounded between 0 and 1 and the employed \textit{\ac{FPPI}} scores vary across studies, such that there exists no standardized definition of an area under the respective curve. Overall, the decision between the two metrics often boils down to a decision between a standardized and technical validation versus an interpretable and application-focused validation.
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Common object detection metrics: Average Precision (AP), colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/AP_example.pdf}
\caption{Exemplary computation of the \textit{\acf{AP}} in object detection tasks. Predictions are ranked according to their predicted class probabilities, represented by the confidence (conf.). Based on the \textit{\acf{IoU}} or a similar localization/hit criterion, it is determined whether the prediction is a \acf{TP} or \acf{FP} (here: \textit{\ac{IoU}} > 0.3). For the creation of the \textit{\acf{PR}} curve, \textit{Precision} and \textit{Recall} are computed for the accumulated \ac{TP} and \ac{FP} for every confidence score (conf.). The \textit{\ac{AP}} interpolates the points of the \textit{\ac{PR}} curve as shown by the dashed gray line.}
\label{fig:ap-example}
\end{tcolorbox}
\end{figure}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Common classification metrics: \acf{FROC}, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Classification/FROC.png}
\caption{Principle of the \textit{\acf{FROC}} curve. Rather than being based on a static threshold (e.g. for generating the confusion matrix), the \textit{\ac{FROC}} curve is generated by applying a range of thresholds. The \textit{\acf{FROC} Score} measures the area under the \textit{\ac{FROC}} curve. In contrast to \textit{\acf{AUROC}}, \textit{\ac{FROC}} operates on object level by plotting the \textit{Sensitivity} against the \textit{\acf{FPPI}} per threshold (e.g. 0.5). In the case of an application-driven threshold (e.g. required \textit{Sensitivity} of 0.9), the metrics \textit{Sensitivity@\ac{FPPI}} and \textit{\ac{FPPI}@Sensitivity} can be calculated on the basis of the the \textit{\ac{FROC}} curve.}
\label{fig:def-froc}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{Counting cardinalities at different scales}
In image-level classification problems, validation is naturally performed on the entire data set, while segmentation typically relies on computing metrics for each image and then aggregating metric values. This latter approach is not applicable in object detection in a straightforward manner because of the relatively small amount of samples per image (typically a few objects rather than thousands of pixels). Fig.~\ref{fig:perimage-perdataset} illustrates the per-image and the per-data set validation of objects. In the per-image aggregation approach, special care needs to be taken in the case of an empty reference or prediction, as detailed in App.~\ref{sec:pitf:detection} (Fig.~\ref{fig:empty-ref-pred-od}).
A few comments on how to compute evaluation metrics while aggregating matched objects per image:
\begin{itemize}
\item \textbf{Counting metrics:} Computing per-class metrics such as Sensitivity, \ac{PPV}, or F$_1$ Score (see Fig.~\ref{fig:def-classification-1}) works intuitively (as depicted in Fig.~\ref{fig:perimage-perdataset}) by computing a score per image and averaging scores over the data set while considering the \texttt{\ac{NaN}} conventions shown in Fig.~\ref{fig:empty-ref-pred-od}.
\item \textbf{Multi-threshold metrics:} While scanning over all thresholds in the data set (analogously to per data set evaluation), for every threshold the Precision (\ac{PPV}) and Recall (Sensitivity) scores are computed per image/patient (while considering the \texttt{\ac{NaN}} conventions in Fig.~\ref{fig:empty-ref-pred-od}) and averaged over the data set. The averaged Precision and Recall score pairs per threshold form the \ac{PR} curve. The \ac{AP} (see Fig.~\ref{fig:ap-example}) can be computed for this curve analogously to the per-data set evaluation. The \ac{FROC} curve computation works analogously while replacing Precision per image with \ac{FPPI}.
\item \textbf{Single working point evaluation:} A single working point (e.g. \ac{PPV}@Sensitivity) can be retrieved based on the curves resulting from multi-threshold evaluation described above.
\end{itemize}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Validating objects per data set \textit{vs.} validating objects per image, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/per_image-vs-per_dataset.pdf}
\caption{Validation on object level can be performed per data set (left) or per image (right). For the per-data set validation of objects, the cardinalities are calculated over the whole data set. For the per-image validation of objects, metric scores are computed per image and aggregated afterwards. $\varnothing$ refers to the average \textit{F$_1$ Score}.}
\label{fig:perimage-perdataset}
\end{tcolorbox}
\end{figure}
\newpage
\subsubsection{Instance Segmentation}
\label{sec:pitf:fundamentals_is}
\hfill\\In contrast to semantic segmentation, instance segmentation problems distinguish different instances of the same class (e.g. different lesions). Similarly to object detection problems, the task is to detect individual instances of the same class, but detection performance is measured by pixel-level correspondences (as in semantic segmentation problems). Optionally, instances can be applied to one of multiple classes. Validation metrics in instance segmentation problems often combine common detection metrics with segmentation metrics applied per instance.
If detection and segmentation performance should be assessed simultaneously in a single score, the \textit{\ac{PQ}} metric can be utilized \cite{kirillov2019panoptic}. As shown in Fig.~\ref{fig:definition-pq}, the segmentation quality is assessed by averaging the \textit{\ac{IoU}} scores for all \ac{TP} instances. While this part alone would neglect \ac{FP} and \ac{FN} predictions, it is multiplied with the detection quality, which is equal to the \textit{F$_1$ score}. For perfect segmentation results, i.e. an average \textit{\ac{IoU}} of 1, the \textit{\ac{PQ}} would simply equal the \textit{F$_1$ Score}. In other words, while segmentation quality in the \textit{F$_1$ Score} is merely integrated via a hard cutoff during localisation (e.g. \textit{\ac{IoU}} > 0.5) affecting the counts of \ac{TP} versus \ac{FP} and \ac{FN}, \textit{\ac{PQ}} allows for a continuous measurement of segmentation quality by 1) employing a lose prior localization criterion (e.g. \textit{\ac{IoU}} > 0, i.e. any prediction overlapping with a reference instance is treated as \ac{TP}) and 2) replacing the simple counting of \ac{TP} by adding up the continuous \textit{\ac{IoU}} scores per \ac{TP}. \textit{\ac{PQ}} was introduced for panoptic segmentation problems that are a combination of semantic and instance segmentation \cite{kirillov2019panoptic}. It is computed per class (including background classes) and can therefore be directly used for instance segmentation problems by only assessing the foreground instances. If needed, the background quality can also be assessed.
\begin{figure}[H]
\begin{tcolorbox}[title= Common instance segmentation metrics: \acf{PQ}, colback=white]
\centering
\hspace{-0.5cm}
\includegraphics[width=\linewidth]{pitfall-paper/images/Segmentation/PQ_def.png}
\caption{The \textit{\acf{PQ}} measures the \textbf{segmentation and detection quality} of a prediction in one score. The segmentation quality is assessed via the \textit{\acf{IoU}} for every predicted \acf{TP} instance. The detection quality is measured via the \textit{F$_1$ score} by taking into account the \acf{FP} and \acf{FN} predictions.}
\label{fig:definition-pq}
\end{tcolorbox}
\end{figure}
\newpage
It should be noted that instance segmentation problems are often phrased as semantic segmentation problems with an additional post-processing step, such as connected component analysis \cite{rosenfeld1966sequential}. In practice, predicted class probabilities, yielded by modern segmentation algorithms, are often discarded in the post-processing step and are thus not available for subsequent validation. Fig.~\ref{fig:class-scores} illustrates how to overcome this potential problem.
\begin{figure}[H]
\begin{tcolorbox}[title= Retaining class scores when extracting instances from semantic segmentation output, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/class_scores.png}
\caption{Retaining class scores when extracting instances from semantic segmentation output. Often, semantic segmentation methods are used for instance segmentation problems by post-processing the segmentation output (e.g. via connected component analysis). Predicted class probabilities are often lost during this process and therefore not available for further validation processes. However, instance-wise class scores can be retained by taking the maximum or average over all pixel-wise class scores of every instance.}
\label{fig:class-scores}
\end{tcolorbox}
\end{figure}
\subsubsection{Pitfalls due to category-metric mismatch}
\label{sec:pitf:underlying-task}
\hfill\\Performance metrics are typically expected to reflect a domain-specific validation goal (e.g. clinical goal). Previous research, however, suggests, that this is often not the case \cite{saha2021anatomical}. Before choosing validation metrics, the correct problem category needs to be defined. In the following, we will describe pitfalls related to metrics not being applied to the appropriate problem category.
\paragraph*{\textbf{Mismatch semantic segmentation $\leftrightarrow$ object detection}}
A common problem is that segmentation metrics, such as the \textit{\ac{DSC}}, are applied to \textit{object detection} tasks \citep{carass2020evaluating,jager2020challenges}, as illustrated in Fig.~\ref{fig:DSC-detection}. From a clinical perspective, for example, the algorithm producing \textit{Prediction 2} and covering all three structures of interest (e.g. tumors) would be clinically much more valuable compared to the one producing a highly accurate segmentation for one structure but missing the other two in \textit{Prediction 1}. This is not reflected in the metric values, which are substantially higher for \textit{Prediction 1}. In general, the \textit{\ac{DSC}} is strongly biased against single objects, therefore not appropriate for the detection of multiple structures \citep{yeghiazaryan2018family, kirillov2019panoptic}.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Mismatch semantic segmentation $\leftrightarrow$ object detection, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/DSC_detection_v1.pdf}
\caption{Effect of using a segmentation metric for object detection. In this example, the prediction of an algorithm only detecting one of three structures (\textit{Prediction 1}) leads to a higher \textit{\acf{DSC}} compared to that of another algorithm (\textit{Prediction 2}) detecting all structures.}
\label{fig:DSC-detection}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Mismatch semantic $\leftrightarrow$ instance segmentation}}
In segmentation problems, the driving research question should decide whether semantic or instance segmentation should be chosen for validation. This is particularly relevant when multiple objects within one image overlap or touch, as often occurring in cell images. For semantic segmentation problems, overlapping or touching objects (see F3.5 and F5.4) may end up merged into a single object without clear boundaries or distinction between the single objects. Instance segmentation problems, on the other hand, ensure that the borders of touching or overlapping structures can be accurately assigned and that objects can be differentiated. If instance segmentation is preferred, the labels need to be chosen accordingly. An example is shown in Fig.~\ref{fig:touching}: The desired annotation consists of two different instances, but only semantic labels are available (middle). A prediction will only be as accurate as the reference, hence detecting only one instance but yielding a perfect metric score although the desired task is not solved.
\begin{figure}[H]
\begin{tcolorbox}[title= Problem: Mismatch semantic $\leftrightarrow$ instance segmentation, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/touching.pdf}
\caption{Effect of using a semantic segmentation metric for instance segmentation. When only the presence of a certain class (e.g. tumor) is labeled, and instance information is not provided in the reference, a common means for assessing performance is to regard each connected component as one instance. This may yield misleading results.}
\label{fig:touching}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Mismatch image-level classification $\leftrightarrow$ object detection}}
Tasks that should be validated at image level are sometimes erroneously approached with object detection models instead of image-level classification models \cite{jaeger2020retina}. Object detection models are designed to handle different objects in an image rather than the complete image and will naturally introduce problems in a validation setting on image level. Object detection tasks are dependent on choosing a proper localization criterion, which is not needed for an image-level classification problem. For example, a \textit{\ac{ROC}} curve, typically used for assessing the performance of image-level classification algorithms, does not consider the localization step needed in object detection tasks, as it was designed to validate at image rather than object level. It therefore does not take into account whether a detected object is at the correct location in the image. Moreover, when validation on image level is conducted by using an object detection model, the detection with the largest class probability (confidence score) of all detections in one image is usually taken, neglecting all other predictions. This does not capture the performance of the model accurately. Fig.~\ref{fig:roc} illustrates some of the resulting problems:
\begin{enumerate}
\item The image-level \textit{\ac{ROC}} curve \textbf{does not measure the localization performance}. As can be seen from Fig.~\ref{fig:roc}a, the validation is performed per image, not per object, therefore not considering whether an object is actually hit (see \textit{Prediction 2}).
\item The image-level \textit{\ac{ROC}} curve is \textbf{invariant to the number of annotated objects}. As can be seen from Fig.~\ref{fig:roc}b, the curve can not discriminate between a model detecting all objects in an image (\textit{Prediction 1}) or just detecting one object (\textit{Prediction 2}), as long as the largest score is the same across predictions.
\item The image-level \textit{\ac{ROC}} curve is \textbf{invariant to the number of detected objects}. As can be seen from Fig.~\ref{fig:roc}c, the curve can not discriminate between a model detecting many \ac{FP} objects in an image (\textit{Prediction 2}) or only detecting one \ac{FP} (\textit{Prediction 1}), as long as the largest score is the same.
\end{enumerate}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Mismatch image-level classification $\leftrightarrow$ object detection, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/detection_ROC.png}
\caption{When image-level classification metrics such as the area under the \textit{\acf{ROC}} curve are used to validate object detection models, (1) information on the object matching (localization, number of objects etc.) is lost and typically (2) only one detection per image (the one with the highest confidence) is considered. This leads to several problems:
\textbf{(a)} The image-level \textit{\ac{ROC}} curve does not measure the localization performance. Both \textit{Prediction 1} and \textit{2} are considered as \acf{TP} due to their score being very high, although \textit{Prediction 2} is not hitting the annotated object. \textbf{(b)} The image-level \textit{\ac{ROC}} is invariant to the number of annotated objects in an image. The curve does not discriminate between a model detecting all positives (\textit{Prediction 1}) and a model detecting only one of the positives (\textit{Prediction 2}), as long as the maximum score is the same. \textbf{(c)} The image-level \textit{\ac{ROC}} is invariant to the number of detections in an image. The curve does not discriminate between a model with many False Positives (FP), (\textit{Prediction 2}) and a model with just one \ac{FP} (\textit{Prediction 1}), as long as the maximum score is the same. The class probabilities are represented by confidence scores (conf.).}
\label{fig:roc}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{No matching problem category}} Metrics should reflect a domain-specific validation goal. This goal may not align with commonly used technical measures like the \textit{\ac{DSC}}. Fig.~\ref{fig:context-ratio} shows an example with the property of interest being the accuracy of the ratio between two structure volumes, indicating, for example, the percentage of blood volume ejected in each cardiac cycle \cite{bamira2018imaging}. Both predictions will result in similar averaged \textit{\ac{DSC}} scores, although the ratio of the volumes vastly differs. A common segmentation metric thus does not reflect the actual research question in this case.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Metrics may be poor proxies for computing properties of interest, colback=white]
\centering
\includegraphics[width=\linewidth]{pitfall-paper/images/Segmentation/context_ratio.pdf}
\caption{It may not always be possible to find a common metric that ideally captures the domain interest. In this example, accuracy of the ratio between two volumes is the property of interest. \textit{Predictions 1} and \textit{2} result in similar averaged \textit{\acf{DSC}} metric values although both predictions result in a different ratio between structure volumes, which is the parameter of interest.}
\label{fig:context-ratio}
\end{tcolorbox}
\end{figure}
\subsubsection{Pitfalls related to analyses and post-processing}
\label{sec:pitf:aggregation-combination}
\hfill\\A data set typically contains several hundreds or thousands of images. When analyzing, aggregating and combining metric values, a number of factors need to be taken into account. Pitfalls in this step are primarily related to the following aspects:
\begin{itemize}
\item Uninformative visualization (Fig.~\ref{fig:raw-metric-values-boxplot})
\item Metric aggregation for invalid algorithm output (e.g. \texttt{\ac{NaN}}) (Figs.~\ref{fig:missings} and~\ref{fig:missings-hd}, F5.3)
\item Hierarchical data aggregation (Fig.~\ref{fig:hier-aggr}, F4.4)
\item Aggregation in the presence of multiple classes (Fig.~\ref{fig:aggr-per-class})
\item Combination of related metrics (Fig.~\ref{fig:combination})
\end{itemize}
\paragraph{\textbf{Uninformative visualization}} Relying on only reporting aggregated metric scores may result in missing essential information on algorithm performance. Therefore, raw metric values (e.g. per image) should always be shown, for example in the shape of boxplots, as depicted in the top left of Fig.~\ref{fig:raw-metric-values-boxplot}. However, boxplots will only provide information on some key descriptive statistics, like median or 1st and 3rd quartiles. Another choice can be violin plots, which further visualize the raw data distribution. The top right of Fig.~\ref{fig:raw-metric-values-boxplot} illustrates the multimodal distribution of the underlying data, invisible in the boxplot. Furthermore, using a violin plot and/or plotting the raw metric values for each data point on top (Fig.~\ref{fig:raw-metric-values-boxplot}, top right and bottom left) will reveal the complete data distribution. In the example below, many values lie below the 3rd quartile, although the box looks tight. Nevertheless, even these two visualizations may hide important information. Assume a data set with metric values of four different videos. Color- or shape-coding the metric values by the video type (Fig.~\ref{fig:raw-metric-values-boxplot} bottom right) reveals a huge cluster of extremely low \textit{\ac{DSC}} values only affecting Video 4 (pink), which would have been hidden by the other two types of visualization.
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Uninformative visualization, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/hierarch_struct_v2.png}
\caption{Effect of different types of visualization. A single boxplot (top left) does not give sufficient information about the raw metric value distribution (here: \textit{\acf{DSC}}). Using a violin plot (top right) or adding the raw metric values as jittered dots on top (bottom left) adds important information. In the case of non-independent validation data, color/shape-coding helps reveal data clusters (bottom right).}
\label{fig:raw-metric-values-boxplot}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Metric aggregation for invalid algorithm output (e.g. \texttt{\ac{NaN}})}} In challenges or benchmarking experiments, metric values are often aggregated over all test cases to produce a challenge ranking~\citep{maier2018rankings}. Missing data plays a crucial role when aggregating metric values and occurs primarily due to two reasons: invalid output of the algorithm or metric routine output resulting in \texttt{\ac{NaN}}, and non-submission of single cases (by accident or even for cheating~\cite{reinke2018exploit}). Figs.~\ref{fig:missings} and~\ref{fig:missings-hd} illustrate why a strategy on how to handle missing values may be crucial.
In the case of metrics with fixed boundaries, such as the \textit{\ac{DSC}} or the \textit{\ac{IoU}}, missing values can easily be set to the worst possible value (here: 0). For spatial distance-based measures without lower/upper bounds, the strategy of how to treat missing values is not trivial. In the case of the \textit{\ac{HD}}, for example, one may choose the maximum distance of the image or normalize the metric values to $[0,1]$ and use the worst possible value (here: 1). Another possibility is to employ a case-based ranking scheme \cite{maier2018rankings} and assign the last rank for every missing submission. Furthermore, aggregating with the mean may not be a good choice as results are unlikely to be normally distributed. Crucially, however, every choice will produce a different aggregated value (Fig.~\ref{fig:missings-hd}), thus potentially affecting the ranking. Another way of handling missing values would lie in rejecting the entire submission in a challenge.
However, metric values may also be undefined (\texttt{\ac{NaN}})) if either reference or prediction or both are empty. In the case of empty reference and prediction, an undefined metric value (e.g. \textit{\ac{DSC}}) may be a desirable outcome and should therefore not necessarily be penalized.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Missing values for metrics with fixed upper/lower bounds, colback=white]
\centering
\includegraphics[width=0.9\linewidth]{pitfall-paper/images/Segmentation/NA_DSC_v1.pdf}
\caption{Effect of missing values when aggregating metric values. In this example, ignoring missing values leads to a substantially higher \textit{\acf{DSC}}) compared to setting missing values to the worst possible value (here: 0).}
\label{fig:missings}
\end{tcolorbox}
\end{figure}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Missing values for metrics without fixed upper/lower bounds, colback=white]
\centering
\includegraphics[width=0.9\linewidth]{pitfall-paper/images/Segmentation/NA_HD_v2.pdf}
\caption{Effect of missing values when aggregating metric values for metrics without fixed boundaries (here: \textit{\acf{HD}}). In this example, ignoring or treating missing values in different ways leads to substantially different \textit{\ac{HD}} values.}
\label{fig:missings-hd}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Hierarchical data aggregation}} Nowadays, most data sets are inherently hierarchically structured, meaning that the test cases are not independent. Data may, for example, come from several centers or hospitals, and for every center or even within one, different devices may be used for image acquisition, and images may be drawn from different subjects or patients. This should be kept in mind when visualizing and aggregating data points, especially if the individual tree nodes end in a large variation in the size of images. Fig.~\ref{fig:hier-aggr} shows an example of five patients with an unequal number of images associated with them. Just averaging all metric values for every image would result in a high average \textit{\ac{DSC}} of 0.8. Averaging metric values per patient reveals that the \textit{\ac{DSC}} values are much higher for \textit{Patient 1}, overruling the other patients due to the high number of samples for this patient. Aggregating per patient first and averaging subsequently will resolve this issue.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Non-independence of validation data, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/hierarch_aggregation.pdf}
\caption{Effect of non-independence of validation data, caused here by an unequal number of data points per subject. The number of images taken from \textit{Patient 1} is much higher compared to that acquired from \textit{Patients 2-5}. Averaging over all \textit{\acf{DSC}} values results in a high averaged score. However, aggregating metric values per patient reveals much larger scores for \textit{Patient 1} compared to the others, which would have been hidden by simple aggregation. $\varnothing$ refers to the average \textit{\ac{DSC}} values.}
\label{fig:hier-aggr}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Aggregation per class}} Similar approaches should be chosen in the presence of multiple classes in a data set. The performance may differ significantly for the individual classes, as shown in Fig.~\ref{fig:aggr-per-class}. The background class in particular will result in a nearly perfect averaged \textit{\ac{DSC}} value, whereas the average scores for classes 2 and 3 are much lower. Aggregating over all values, not considering the class, would hide this information. An alternative approach to the problem lies in the application of metrics that explicitly handle class balance, such as using the \textit{Generalized DSC} \cite{sudre2017generalised}.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Ignoring multiple classes when aggregating, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/aggr_per_class_v2.png}
\caption{Effect of ignoring the presence of multiple classes when aggregating metric values. The overall average of all \textit{\acf{DSC}} scores for the four images results in a \textit{\ac{DSC}} score of 0.7. Averaging per class reveals a very low performance for classes 2 and 3. $\varnothing$ refers to the average \textit{\ac{DSC}} values.}
\label{fig:aggr-per-class}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Metric combination}} A single metric typically does not reflect all aspects that are essential for algorithm validation. Hence, multiple metrics with different properties are often combined. However, the selection of metrics should be well-considered as some metrics are mathematically related to each other~\citep{taha2014formal, taha2015metrics}. A prominent example is the \textit{\ac{IoU}} -- the most popular segmentation metric in computer vision -- which highly correlates with the \textit{\ac{DSC}} -- the most popular segmentation metric in medical image analysis. In fact, the \textit{\ac{IoU}} and the \textit{\ac{DSC}} are mathematically related (see App.~\ref{sec:pitf:fundamentals_ss}) \citep{taha2015metrics}.
Combining metrics that are related will not provide additional information for a ranking. Fig.~\ref{fig:combination} illustrates how the ranking can change when adding a metric that measures different properties.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Related metrics, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/Combination_v2.pdf}
\caption{Effect of using mathematically closely related metrics. The \textit{\acf{DSC}} and \textit{\acf{IoU}} typically lead to the same ranking, whereas metrics from different families (here: \textit{\acf{HD}}) may lead to substantially different rankings.}
\label{fig:combination}
\end{tcolorbox}
\end{figure}
\subsubsection{Pitfalls related to image-level classification}
\label{sec:pitf:classification}
\hfill\\Most issues related to classification metrics are related to one of the following properties of the underlying biomedical problem:
\begin{itemize}
\item High class imbalance (Fig.~\ref{fig:class-imbalance}, F4.1)
\item Presence of more than two classes (Fig.~\ref{fig:multi-class})
\item Unequal handling of classes (Fig.~\ref{fig:unequal-class}, F2.5.1 and F2.5.3)
\item Interdependencies between classes (Fig.~\ref{fig:multi-class-interdependencies})
\item Lack of stratification (Fig.~\ref{fig:stratification-gender})
\item Missing prevalence correction (Fig.~\ref{fig:prevalence})
\item Discrimination \textit{vs.} calibration (Fig.~\ref{fig:calibration})
\end{itemize}
Furthermore, metric-specific limitations may arise (Fig.~\ref{fig:kappa-max})
Please note that all of these also apply to semantic/instance segmentation or object detection problems. The discourse focuses on the most commonly used image-level classification metrics, as presented in Figs.~\ref{fig:def-classification-1}, \ref{fig:def-classification-2} and~\ref{fig:def-auc}. For most of the problems, it focuses on the \textit{Accuracy}, \textit{Sensitivity} or \textit{\ac{PPV}}, because those are the most common metrics for image-level classification in biomedical image analysis. Please note that we do not recommend their indiscriminate use, as they come with limitations (discussed in the following paragraphs), but rather wish to spotlight the problems and pitfalls of those most commonly used metrics.
To preserve the clarity of the illustrations, the most important of the presented metric values may be highlighted with color. Green metric values correspond to a "good" metric value (e.g. a high \textit{Sensitivity} score), whereas red values correspond to a "bad" value (e.g. a low \textit{Sensitivity}). Green check marks indicate desirable behaviour of metrics, red crosses indicate undesirable behaviour. Please note that a low metric value is not automatically a "bad" score. A metric value should always be put into perspective and compared to inter-rater variability. For simplicity, we still use the terms "good" and "bad/poor" throughout the section. Finally, our illustrations do not provide the concrete class probabilities of the presented classifiers.
\paragraph*{\textbf{High class imbalance}} \textit{Accuracy} is one of the commonly applied metrics in classification problems, presumably because it is particularly straightforward to interpret. However, the metric is not designed to handle imbalanced data sets, which often occur across all domains. Fig.~\ref{fig:class-imbalance} provides an example in which the positive class (orange circle) is heavily underrepresented. While \textit{Prediction 1} gives a reasonable separation of the classes, \textit{Prediction 2} results in the same \textit{Accuracy} value (0.97) although the algorithm only provides the majority vote as a result. In this specific example, \textit{Sensitivity}, \textit{\ac{PPV}} and \textit{F1 score} reveal the issue, as does \textit{Matthews correlation coefficient (MCC)}, a metric designed to handle class imbalance which reflects that \textit{Prediction 2} is not better than a random guess (0.00) \citep{chicco2020advantages}. As many classification measures are easily computable using the number of \ac{TP}, \ac{TN}, \ac{FP} and \ac{FN} samples, it is highly recommended to report these \ac{TP}, \ac{TN}, \ac{FP} and \ac{FN} values explicitly and then compute multiple metrics \citep{hicks2021evaluation}.
Plotting the \textit{\ac{ROC}} and \textit{\ac{PR}} curves (Figs.~\ref{fig:class-imbalance}b and c) also reveals the limitations of \textit{Prediction 2}, which yields an \textit{\ac{AUROC}} of 0.52 and \textit{\ac{AP}} of 0.04, indicating that the prediction is not better than random guessing.
Some metrics inherently address the problem of performance overestimation or distortion caused by class imbalance. \textit{\acf{MCC}} and \textit{Cohen's Kappa} $\kappa$, for example, are designed in such a way that they assign a (prevalence-aware) random guessing algorithm the value $0$. Similarly, \textit{\acf{AUROC}} assigns the value $0.5$ and \textit{Balanced Accuracy} yields a value of $\frac{1}{C}$, where $C$ is the number of classes. For all other metrics (see Fig.~\ref{fig:class-imbalance}), it is recommended in general to put the resulting values into perspective of a (prevalence-aware) random guessing algorithm baseline.
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Class imbalance, colback=white]
\centering
\includegraphics[width=0.9\linewidth]{pitfall-paper/images/Classification/Classification_imbalance_v7.png}
\caption{Effect of class imbalance. Not every metric is designed to reflect class imbalance (e.g. \textit{Accuracy}). In the case of underrepresented classes, such a metric yields a high value even if the classifier performs very poorly for one of the classes (here: \textit{Prediction 2}). Multi-threshold metrics, such as the \textit{\acf{AUROC}} and the \textit{\acf{AP}}, reveal the weakness, indicating that \textit{Prediction 2} is not better than random guessing. For comparison, a no skill classifier (random guessing) is shown as a black dashed line. For the \textit{\acf{PR} curves}, the interpolation applied to compute the \textit{\ac{AP}} metric is shown by a dashed grey line. Thresholds used for curve generation are provided as small numbers in the curve. Further abbreviations: \textit{\acf{PPV}}, \textit{\acf{NPV}}, \textit{\acf{MCC}}, \textit{Cohen's Kappa} $\kappa$.}
\label{fig:class-imbalance}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{More than two classes available}} Many binary metrics can directly be translated to the multi-class case by expanding the confusion matrix to all classes. These classes are often hierarchically structured, for example in the shape of one negative class (e.g. no pathology) and multiple positive classes (e.g. different types of pathologies). Fig.~\ref{fig:multi-class} shows an example of a classification into triangles and circles, for which the circle class is further separated into two distinct classes (green and orange). The binary performance into triangle \textit{vs.} circle, shown in the middle, is good (\textit{Accuracy} of 0.88). But when considering the three classes separately, the prediction struggles to identify the color of the circles, causing their per-class accuracy scores to drop significantly ($0.63$ each).
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Hierarchical structure of classes, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Classification/More_classes_class_v3.png}
\caption{Classes in categorical classification may be hierarchically structured, for example in the shape of multiple positive classes and one negative class. The phrasing of the problem as binary \textit{vs.} multi-class hugely affects the validation result. Binary classification (middle), differentiating triangles from circles, yields a good \textit{Accuracy}, while per-class validation yields a poor score because the two circle classes cannot be distinguished well. Incorrect predictions are indicated by a red cross.}
\label{fig:multi-class}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Unequal handling of classes}} In biomedical applications, classes are often not equally important. Consider the task of colon polyp detection in the gastrointestinal tract, for example. To provide the patient with the best care, it is crucial to detect all of these precancerous lesions. This requires a particular penalization of those samples containing a polyp which have been marked as 'no polyp' (\ac{FN}), and the metrics need to be chosen accordingly. The \textit{\ac{PPV}}, for example, does not include the \ac{FN} in its definition, hence would not be appropriate for this research question. \textit{Sensitivity}, on the other hand, would show the desired poor performance in the presence of many \ac{FN} predictions, as seen in the top row of Fig.~\ref{fig:unequal-class}a.
For image retrieval, the task of finding images for a specific content, it is not important to find every single existing image, but the images found should be correct. In this setting, the \ac{FP} (assigning an incorrect image as correct) need to be penalized. Since it includes the computation of \ac{FP}, in this case, the \textit{\ac{PPV}} would be a good metric. In contrast, \textit{Sensitivity} does not consider \ac{FP}, therefore being inappropriate in this context (see bottom row of Fig.~\ref{fig:unequal-class}a). Penalization in both cases is especially important in cases of imbalanced data sets (see Fig.~\ref{fig:class-imbalance}).
When it comes to multi-class problems, different approaches may be chosen to compute the metric values. One possibility is to first compute the metric values per class and aggregate them subsequently. Special care has to be taken in the case of unequal importance of the different classes. For example, identifying whether a patient harbors a pathology in general might be more important than identifying the specific type of pathology. In this case, one should not just average over all class metric scores, but instead apply a sufficient weighting scheme. In the example of Fig.~\ref{fig:unequal-class}b, the triangle class is the most important class but also the one with the lowest per-class \textit{Accuracy}. Simple averaging, so-called macro-averaging, would ignore that property and thus result in a higher aggregated \textit{Accuracy} than merited. This effect can be compensated with the \textit{Weighted Accuracy}.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Unequal handling of classes or misclassifications, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Classification/Unequal_importance_fpfn_punish_v3.pdf}
\caption{Effect of unequal handling of classes. \textbf{(a)} Effect of using metrics that are not suitable for penalizing \acf{FN}/\acf{FP}. The definition of the \textit{\acf{PPV}} metric does not incorporate \ac{FN} and is therefore not well-suited for penalizing \ac{FN}, as required in cancer screening tasks, for example. Analogously, the \textit{Sensitivity} is not well-suited for penalizing \ac{FP}, as required in many retrieval tasks, for example. \textbf{(b)} Simple averaging (macro-averaging) of the \textit{Accuracy} ignores the unequal importance of classes, given by pre-defined weights of classes. Incorrect predictions are indicated by a red square.}
\label{fig:unequal-class}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Interdependencies between classes}} If multiple classes are visible in the data set, one should carefully account for interdependencies between the classes. Interdependencies can happen in cases of multi-colinearities in which two classes are correlated, either inherently, such as for the body mass index (BMI) and the body fat percentage, or in the case of dependent data settings, for example multiple images per patient or the presence of confounders. An algorithm aiming to classify the dark blue triangle class in Fig.~\ref{fig:multi-class-interdependencies} may result in a nearly perfect \textit{Accuracy} of 0.94, but only because the dark blue triangle almost always appears in conjunction with the orange square. Computing the \textit{Accuracy} for those images individually without the square class would lead to a much lower performance.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Interdependencies between classes, colback=white]
\centering
\includegraphics[width=0.7\linewidth]{pitfall-paper/images/Classification/interdependencies_v2.pdf}
\caption{Effect of interdependencies between classes. A prediction may show a near-perfect \textit{Accuracy} score of 0.94 for the dark blue triangle as it frequently appears in conjunction with the orange square. By calculating the \textit{Accuracy} in the \textit{presence} and \textit{absence} of the square class, it can be seen that the algorithm only works well in the presence of the orange class. Incorrect predictions are indicated by a red cross.}
\label{fig:multi-class-interdependencies}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Stratification based on meta-information}} Different kinds of meta-information may be available for a data set, including the presence and relevance of artifacts or artificial structures (e.g. metal artifacts in CT images or text overlay in endoscopic data) as well as specifics of acquisition protocols (e.g. acquisition angle or viewpoint) or grid size (cf. Fig.~\ref{fig:DSC-grid-size}). Another typical example is the gender of a patient, as shown in Fig.~\ref{fig:stratification-gender}. In this case, the \textit{Accuracy} is computed over twelve cases, disregarding the available meta-information (gender). Stratification based on gender will reveal that the prediction performs much worse for women compared to men. These aspects are currently investigated in the fairness literature \cite{barocas2017fairness}.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Meta-information ignored, colback=white]
\centering
\includegraphics[width=0.6\linewidth]{pitfall-paper/images/Classification/stratification_gender.pdf}
\caption{Effect of disregarding relevant meta-information (here: gender). Ignoring the available meta-information of the patient's gender per image, the \textit{Accuracy} does not reveal that the algorithm performs much better for men compared to women.}
\label{fig:stratification-gender}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Missing prevalence correction}}
The \textit{\ac{PPV}} and the \textit{\acf{NPV}} are common measures to validate classification performances. In many cases, binary classification is considered, for example presence or absence of a disease.
In contrast to \textit{Sensitivity} and \textit{Specificity}, in case-control studies, \textit{\ac{PPV}} and \textit{\ac{NPV}} should be seen as the conditional probability of a disease being present based on a test result and the prevalence in a general population.
However, \textit{\ac{PPV}} and \textit{\ac{NPV}} are frequently used incorrectly. This is due to the fact that many practitioners assume the same prevalence in an analysed case-control study group as in the general population. However, a study group is often heavily biased, either due to the study design or due to the observation of patient groups from specialized clinics. Thus, the assumed disease prevalence in scientific literature is often higher than that found in the general population (cg. Fig.~\ref{fig:prevalence}). This problem is amplified by default implementations (e.g. in \texttt{scipy}~\cite{virtanen2020scipy}) which disregard wider population prevalence and calculate prevalence from the study group. Without prevalence correction, this can lead to misleading results, confusion among patients and ill-informed policy-making.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Missing prevalence correction, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Classification/Prevalence_correction_v3.pdf}
\caption{Effect of missing prevalence correction. For case-control studies, the \textit{\acf{PPV}} and \textit{\acf{NPV}} are required to apply prevalence correction based on the general population. Falsely used case-control prevalence leads to incorrect metric scores compared to using the general population prevalence (which is often significantly lower).}
\label{fig:prevalence}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Discrimination \textit{vs.} calibration}} A model's \textit{discrimination} capability refers to how well it separates samples with and without the class of interest. If all predicted class scores for the samples with the class of interest are higher than for the others, the model discriminates perfectly, reflected in an \ac{AUROC} score of 1. A \textit{calibrated model} outputs predicted class scores that match the empirical success rate (e.g. outputs with score 0.8 for a specific class, empirically belong to this class in $80\%$ of the cases). \cite{cook2007use}. However, it may happen a perfectly discriminating model, such as the one presented in Fig.~\ref{fig:calibration}, is not well calibrated. The \textit{Prediction} gives a confidence score of 0.52 for all samples of the positive class (orange circle) and a score of 0.51 for all samples of the negative class (blue triangle). Although this leads to a perfect discrimination, the calibration is very poor and the predicted probabilities would not be helpful in practice at all.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Perfect discrimination but poor calibration, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Classification/calibration.png}
\caption{Effect of a perfect discrimination but a poor calibration. The predicted classes are perfectly discriminated and yield a perfect \acf{AUROC} score of 1. However, the predicted class scores (0.52 for the positive and 0.51 for the negative class) are not well calibrated as there is very little correlation between the predicted class scores and actual probability.}
\label{fig:calibration}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Upper bound in \textit{Cohen's $\kappa$} calculation}} \textit{Cohen's $\kappa$} measures the agreement between ratings while incorporating information on the \textit{Accuracy} by chance. It therefore investigates how well a prediction follows the distribution of the actual class. The maximum \textit{Cohen's $\kappa$} helps interpreting the calculated \textit{$\kappa$} score by symbolizing the corner case in which either the \ac{FP} or \ac{FN} are equal to 0 \cite{umesh1989interjudge}:
\begin{equation}
\begin{split}
\kappa_{max} &= \frac{p_{max}-p_e}{1-p_e}, \\
p_{max} &= \min \left( \frac{TP+FN}{TP+TN+FP+FN}, \frac{TP+FP}{TP+TN+FP+FN}\right) \\
&+ \min \left( \frac{TN+FN}{TP+TN+FP+FN}, \frac{TN+FP}{TP+TN+FP+FN} \right)
\end{split}
\end{equation}
The maximum \textit{Cohen's $\kappa$} score will be lower as the number of the predicted positive and negative samples diverges more from the actual number of positive and negative samples. This is shown in Fig.~\ref{fig:kappa-max} with two predictions. \textit{Prediction 1} achieves lower \textit{Accuracy} and \textit{Cohen's $\kappa$} scores compared to \textit{Prediction 2}, as it only predicts a very low number of \ac{TP}. However, the predicted distribution of samples in \textit{Prediction 1} is closer to the actual distribution of samples (13 circle predictions \textit{vs.} 15 actual circles and 87 triangle predictions \textit{vs.} 85 actual triangles). The distribution of samples of \textit{Prediction 2} differs more from the actual distribution, yielding a lower \textit{Cohen's $\kappa_{max}$} value\footnote{\url{https://www.knime.com/blog/cohens-kappa-an-overview}}.
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Upper bound not equally obtainable in Cohen's $\kappa$, colback=white]
\centering
\includegraphics[width=0.95\linewidth]{pitfall-paper/images/Classification/kappa_v21.png}
\caption{Effect of different numbers of predicted positive and negative samples in comparison to the actual number of positive and negative samples. A prediction with a similar count of positive and negative samples to the actual distribution (\textit{Prediction 1}) reaches higher maximum \textit{Cohen's $\kappa$} values compared to a prediction with a dissimilar distribution (\textit{Prediction 2}), although the overall \textit{Accuracy} and \textit{Cohen's $\kappa$} is lower. Incorrect predictions are indicated by a red cross.}
\label{fig:kappa-max}
\end{tcolorbox}
\end{figure}
\subsubsection{Pitfalls related to object detection}
\label{sec:pitf:detection}
\hfill\\This section presents pitfalls relevant for object detection and instance segmentation. Note that these pitfalls equally apply to instance segmentation problems. While most issues related to the actual metric selection have already been mentioned in the previous paragraphs, this section is primarily dedicated to technical peculiarities related to the localization and assignment criteria. These include:
\begin{itemize}
\item Mathematical implications of center-based localization criteria (Fig.~\ref{fig:hit-criteria})
\item Mathematical implications of \textit{\ac{IoU}}-based localization criteria (Fig.~\ref{fig:bb-2d-3d})
\item Penalization of one prediction assigned to multiple reference objects requested (Fig.~\ref{fig:od-ior}, F2.5.7)
\item Effect of the provided annotations (Fig.~\ref{fig:disconnected}, F2.4 F3.3.2 and F4.3)
\item Effect of small structures on localization criterion (Fig.~\ref{fig:boundary-mask-iou}, F3.1)
\item Perfect \textit{Boundary \ac{IoU}} for imperfect prediction (Fig.~\ref{fig:boundary-iou})
\item Possibility of reference or prediction without the target structure and \texttt{\ac{NaN}} handling (Fig.~\ref{fig:empty-ref-pred-od}, F4.5 and 5.2)
\item \textit{Average Precision} \textit{vs.} \textit{Free-response ROC} score (Fig.~\ref{fig:ap-froc})
\item Effect of predicted class probabilities on multi-threshold metrics (Figs.~\ref{fig:AP-small-conf-changes}, \ref{fig:AP-conf-not-important} and~\ref{fig:AP-FP-tail}, F5.1)
\end{itemize}
\paragraph*{\textbf{Mathematical implications of center-based localization criteria}} Before calculating metrics for object detection tasks, it is necessary to define what qualifies a detection as a \textit{hit} (\ac{TP}) or \textit{miss} (\ac{FP}). There are multiple ways to define a hit, all of which come with their specific limitations. Below, the most commonly used center-based localization criteria are presented\footnote{For more details, please refer to the blogpost "Evaluation curves for object detection algorithms in medical images": \url{https://medium.com/lunit/evaluation-curves-for-object-detection-algorithms-in-medical-images-4b083fddce6e}.}.
\begin{itemize}
\item For the \textbf{center-cover criterion}, the reference object is considered a hit if the center of the reference object is inside the predicted detection. Fig.~\ref{fig:hit-criteria}a shows how this criterion can be fooled by a model outputting very large boxes to maximize the chance of a correct detection.
\item In the case of the \textbf{distance-based hit criterion}, a prediction is considered a hit if the distance $d$ between the center of the reference and the detected object is smaller than a certain threshold $\tau$. In Fig.~\ref{fig:hit-criteria}b, both predictions have the same distance to their corresponding reference object centers. However, the prediction on the top right shows no overlap with the reference and should therefore not be counted as a hit.
\item The \textbf{center-hit criterion} holds true if the center of the predicted object is inside the reference bounding box or contour. Given this definition, large reference objects are more likely to be hit, as shown in Fig.~\ref{fig:hit-criteria}c. The left prediction is defined as a missed object (\ac{FP}), the right detection as a hit because of its larger size.
\end{itemize}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Mathematical implications of center-based localization criteria, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/Hit_criteria_3.png}
\caption{Pitfalls for several center-based hit criteria in object detection. Reference objects are shown in dark blue, predictions in orange. The object centers are shown as blue/orange crosses. \textbf{(a)} The \textbf{center-cover criterion}, which requires the center of the reference to be inside the detection, can be fooled easily by predicting a very large bounding box/object. \textbf{(b)} Both predictions have the same distance to their corresponding reference center. The \textbf{distance-based criterion}, which requires the distance between center points not be exceeded, does not take into account the overlap between objects. However, the right prediction does not overlap with the reference and should, thus, not be considered a \acf{TP}. \textbf{(c)} The \textbf{center-hit criterion}, which requires the center of the prediction to be located inside the reference, favors large reference objects, as they are easier to detect. The left prediction is considered a \acf{FP}, as the reference center was not hit. The right prediction is considered a \ac{TP} because of the larger size of the object.}
\label{fig:hit-criteria}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Mathematical implications of \textit{\ac{IoU}}-based localization criteria}}
The most commonly used hit criterion is determined by computing the \textit{\ac{IoU}} between the predicted and the reference mask/bounding box/boundary. Pitfalls related to \textit{\ac{IoU}}-based criteria are mainly related to the setting of the threshold (Fig.~\ref{fig:bb-2d-3d}). Many biomedical applications involve 3D rather than 2D images. When working with a higher dimension, it should be kept in mind that metrics may be affected. The additional dimension will lead to overlap errors being punished even more. Fig.~\ref{fig:bb-2d-3d}a shows a comparison of the \textit{\ac{IoU}} for two rectangles (or bounding boxes) in 2D and 3D. Being mistaken by one voxel in the $z$-dimension will lead to a much lower \textit{\ac{IoU}} score in 3D compared to the 2D case.
As \textit{\ac{IoU}}-based criteria take the overlap between regions into account, it is only possible to cheat with very large boxes if the \textit{\ac{IoU}} threshold is set to a very small value (here: 0), as shown in Fig.~\ref{fig:bb-2d-3d}b. However, special care should be taken when applying the \textit{Box \ac{IoU}} in the presence of highly concave or elongated structures, as illustrated in Fig.~\ref{fig:bb-2d-3d}c. This is because bounding boxes may quickly grow for narrow and diagonally placed objects, such as medical instruments, and result in \ac{FP} although visual inspection would indicate a correct prediction.
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Mathematical implications of \textit{\ac{IoU}}-based localization criteria, colback=white]
\centering
\includegraphics[width=0.7\linewidth]{pitfall-paper/images/Detection/Math_IoU_v1.pdf}
\caption{The \textit{\acf{IoU}} is a commonly used localization criterion in object detection. It comes with several limitations:
\textbf{(a)} The image dimension should be considered when setting the \textit{\ac{IoU}} (here: \textit{Box \ac{IoU}}) threshold for object detection. In 3D settings, the additional z-dimension results in a cubical increase in erroneous pixels. \textbf{(b)} Effect of a loose \textit{\ac{IoU}} criterion for object detection. When defining a \acf{TP} by an \textit{\ac{IoU}} > 0, the resulting localizations may be fooled by very large predictions.
\textbf{(c)} Effect of defining \ac{TP} based on the \textit{\ac{IoU}} (here: \textit{Box \ac{IoU}}) threshold of the reference and predicted bounding boxes. Especially for diagonal, narrow objects, the number of bounding box pixels may change quadratically. Although \textit{Predictions 1} and \textit{2} are very similar, their bounding boxes diverge and lead to one of them being defined as \ac{TP}, the other as \acf{FP}.}
\label{fig:bb-2d-3d}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Penalization of one prediction assigned to multiple reference objects requested}} Object detection and instance segmentation algorithms typically involve the step of assigning predicted objects to reference objects. This may result in one prediction being assigned to multiple reference objects or vice versa. Using the \textit{\ac{IoU}} > 0.5 (or similar threshold) as assignment strategy may end up in a very strict penalty of two \ac{FN} and one \ac{FP} if the \textit{\ac{IoU}} for both reference objects is smaller than the threshold (as shown for two reference objects in Fig.~\ref{fig:od-ior}. Using the \textit{\ac{IoR}} may result in a less strict penalization for what could be interpreted as only a single error with an additional step of penalizing the non-split errors (either directly in object detection or indirectly in instance segmentation).
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: One prediction assigned to multiple reference objects, colback=white]
\centering
\includegraphics[width=0.7\linewidth]{pitfall-paper/images/Detection/IoR.pdf}
\caption{In case of a prediction assigned to multiple reference objects, an assignment strategy needs to be chosen. This may be based, for example, on the \textit{\acf{IoU}}>0.5 strategy, which may end up with a heavy penalty (two \acf{FN} and one \acf{FP}. Another option is to use the \textit{\acf{IoU}}>0.5 strategy, which examines whether the prediction was successfully assigned to the reference objects. In an additional step, the "non-split errors" will be penalized. Used abbreviations: \acf{FN}, \acf{FP} and \acf{TP}.}
\label{fig:od-ior}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Possibility of disconnected structures}} The \textit{Box \ac{IoU}} is sometimes employed despite access to pixel-mask annotations. A possible explanation is that researchers want to phrase their problem as an object detection problem and then apply the most commonly used validation methods. Such simplification might cause problems if structures are not well approximated by a box shape, or if structures yield multi-component masks, appearing to be disconnected. This may occur in the case of a tubular structure shown in a 2D tomographic image or a medical instrument occluded by tissue in an endoscopic image, for example. Fig.~\ref{fig:disconnected} provides examples of a complex diagonal (top) and a disconnected structure (bottom). Both box predictions yield a \textit{Box \ac{IoU}} larger than 0.3, and are thus counted as \ac{TP} because of the chosen localization threshold. Nevertheless, \textit{Prediction 1} is not hitting the actual object at all. This is due to the fact that the target structures are not well approximated by the bounding box, leaving many empty pixels in the boxes.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Effect of annotation type, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/disconnected_v1.png}
\caption{Bounding boxes are not well-suited for representing complex (top) and disconnected (bottom) shapes. Specifically, they are not well-suited for capturing multi-component structures. \textit{Predictions 1} and \textit{2} would both end up in a \acf{TP} detection, as the \textit{Box \acf{IoU}} is larger than the threshold 0.3. However, \textit{Prediction 1} is not hitting the real objects at all, as the given annotation does not represent them well.}
\label{fig:disconnected}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Effect of small structures on localization criterion}}
\textit{Box IoU} and \textit{Mask IoU} are not sensitive to structure boundary quality in larger objects (cf. Section~\ref{sec:pitf:segmentation}). This is due to the fact that boundary pixels will increase linearly (quadratically in 3D) while pixels inside the structure will increase quadratically (cubically in 3D) with an increase in structure size. In consequence, the \textit{IoU}-scores tend to be higher for large objects compared to small objects. For this reason, localization criteria such as the \textbf{\textit{Boundary IoU}} were designed.
Fig.~\ref{fig:boundary-mask-iou} shows an example of \textit{Mask IoU} and \textit{Boundary IoU} for a large (top) and a rather small structure (bottom). In the case of the \textit{Mask IoU}, the score drops substantially for the small structure, while the scores are more consistent for the \textit{Boundary IoU} when comparing small and large structures. This pitfall also applies to segmentation problems in which the \textit{(Mask) IoU} and \textit{Boundary IoU} are applied as overlap-based metrics.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Effect of small structures on localization criterion, colback=white]
\centering
\includegraphics[width=0.9\linewidth]{pitfall-paper/images/Detection/BoundaryIoU_MaskIoU_v2.pdf}
\caption{Comparison of \textit{Mask} and \textit{Boundary Intersection over Union (Boundary IoU)} localization criteria in the case of particular importance of structure boundaries. Overlapping pixels from the reference and prediction are shown in light blue. The \textit{Mask IoU} (second column) is less sensitive to boundary errors for large objects. The \textit{Boundary IoU} (third and fourth column) especially considers contours, (1) yields smaller metric scores, thus penalizing errors in the boundaries and (2) is more invariant to structure sizes, as it leads to very similar values for large and small structures (fourth column). }
\label{fig:boundary-mask-iou}
\end{tcolorbox}
\end{figure}
It should further be noted that the \textit{Boundary IoU} is highly dependent on the chosen distance $d$, as illustrated in Fig.~\ref{fig:boundary-mask-iou} (third vs fourth column). Similarly to the example provided in Fig.~\ref{fig:outline}, the \textit{Boundary IoU} can be fooled to result in a perfect value of $1.0$. A prediction with a hole in the middle of the structure may result in a perfect metric score if the distance is chosen in a way that it incorporates all pixels of the predicted mask, as shown in Fig.~\ref{fig:boundary-iou} \cite{cheng2021boundary}. The \textit{Mask IoU}, however, will be able to recognize the problem, as it completely measures the overlap between both structures. \cite{cheng2021boundary} propose to use the $\min(Boundary IoU, Mask IoU)$ to resolve this issue. Please note that the same limitations also affect other distance-based measures, such as the \textit{\ac{NSD}} or \textit{\ac{HD}} metrics. This pitfall also applies to segmentation tasks.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Perfect \textit{Boundary IoU} for imperfect prediction, colback=white]
\centering
\includegraphics[width=\linewidth]{pitfall-paper/images/Detection/BoundaryIoU_2.pdf}
\caption{Effect of a perfect \textit{Boundary Intersection over Union (Boundary IoU)} score for an imperfect prediction. Overlapping pixels from the reference and prediction are shown in light blue. For a prediction with a hole in the middle, the \textit{Boundary \ac{IoU}} may result in a score of 1.00 if the distance to border contains all mask pixels (here: distance = 2). However, the \textit{Mask \ac{IoU}} spots the problem and results in a lower score.}
\label{fig:boundary-iou}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Possibility of reference/prediction without the target structure and \texttt{\ac{NaN}} handling}} When validating an object detection problem per image rather than per data set, a reference or prediction image without the target structure(s) may become problematic as some metric values will turn into \texttt{\ac{NaN}} due to division by zero errors (cf. Fig.~\ref{fig:empty}). Fig.~\ref{fig:empty-ref-pred-od}a shows potential scenarios for a validation per image categorized by the presence and absence of \ac{TP}, \ac{FP} and \ac{FN}. Four occurrences of \texttt{\ac{NaN}} are presented. To proceed with the validation, namely aggregating metric values for every image over the entire data set, a \texttt{\ac{NaN}} strategy needs to be defined for every use case.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: \texttt{\acf{NaN}} handling for empty reference/prediction, colback=white]
\centering
\includegraphics[width=0.8\linewidth]{pitfall-paper/images/Detection/EmptyRefEmptyPred_OD.pdf}
\caption{Effect of handling a \texttt{\acf{NaN}} caused by reference or prediction without target structure(s) in object detection/instance segmentation problems validated per image. \textbf{(a)} Demonstration of how and when \texttt{\ac{NaN}} can occur. Each column represents a potential scenario for per-image validation of objects, categorized by whether \acf{TP}, \acf{FN}, and \acf{FP} are present (n > 0) or not present (n = 0) after matching/assignment. The sketches on the top showcase each scenario when setting "n > 0" to "n = 1". For each scenario, \textit{Sensitivity} and \textit{Precision} are calculated. \textbf{(b)} Effect of different \texttt{\ac{NaN}} handling strategies based on different conventions for the aggregation across multiple images. Four examples are shown for the \texttt{\ac{NaN}} scenarios from (a) (\textbf{\texttt{\ac{NaN}} 1-4}). \textbf{\texttt{\ac{NaN}} 1} and \textbf{4}: The intuitive penalization for FPs in "empty" images is already established by means of \textit{Precision} scores (see \textbf{\texttt{\ac{NaN}} 4}) and further penalization by means of \textit{Sensitivity} is neither required nor appropriate. Instead, images without reference objects should be ignored when averaging \textit{Sensitivity} scores over images. \textbf{\texttt{\ac{NaN}} 2}: The intuitive penalization for \ac{FP} in "empty" images is established when assigning a \textit{Precision} of 1. \textbf{\texttt{\ac{NaN}} 3}: The intuitive penalization for \ac{FP} is established when removing images with \ac{FN} and no \ac{FP} from the aggregation of \textit{Precision} scores.}
\label{fig:empty-ref-pred-od}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Average Precision \textit{vs.} Free-response ROC score}} While the \ac{AP} constitutes the standard metric for object detection and instance segmentation in the computer vision community, the \textit{\ac{FROC}} score is often favoured in the clinical context. In contrast to the \ac{AP}, the \ac{FROC} score takes into account the total number of images in the data set. As can be seen from Fig.~\ref{fig:ap-froc}, both data sets D1 and D2 will yield the same \ac{AP} score, although data set D1 contains two images and D2 contains four images. The \ac{FROC} score, however, will reflect that the number of images is different for both data sets and that data set D2 contains two images that do not contain any \ac{FP}. Thus, the \ac{FPPI} will be lower in data set D2, yielding a higher \ac{FROC} score.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: \acf{AP} disregards total number of images, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/AP_FROC.pdf}
\caption{Effect of the number of images per data set on the metric scores. The \acf{AP} metric does not take into account the total number of images, yielding the same score for data sets D1 and D2. The \acf{FROC} curve plots the average number of \acf{FPPI} against the \textit{Sensitivity}, therefore accounting for the number of images. The \ac{FPPI} is lower for D2, yielding a higher \ac{FROC} score.}
\label{fig:ap-froc}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\textbf{Multi-threshold metric-related properties}} In the next paragraphs, we highlight some limitations of the multi-threshold metrics, exemplarily for the \textit{\ac{AP}} metric, which can be transferred to other multi-threshold metrics, such as the \textit{\ac{AUROC}} \cite{oksuz2018localization}. By definition, multi-threshold metrics are ranking metrics, which rank the predicted class probabilities or confidence scores (cf. Fig.~\ref{fig:ap-example}). They are not designed to reflect the calibration of confidence or class scores, as shown in the following examples. Please note that we disregard the concrete choice of the localization criterion here for simplicity.
\paragraph{Predicted class probabilities} The \textit{\ac{PR}} curve and the resulting metric score \textit{\ac{AP}} highly depend on the ranking of predictions, based on their predicted class probabilities or confidence scores. Small changes in the scores can therefore significantly change the metric value, as shown in Fig.~\ref{fig:AP-small-conf-changes}. On the other hand, as long as the ranking remains unchanged among predictions, the predicted class probabilities themselves are not important for the result, although they should be (see Fig.~\ref{fig:AP-conf-not-important}).
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Large effects of small changes in predicted class probabilities, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/AP_smallChangesConf.pdf}
\caption{Effect of small changes in predicted class probabilities. Reference bounding boxes are shown in dark blue. \textit{Predictions 1} and \textit{2} detect the exact same bounding boxes with minor variations in their predicted class probabilities (represented by the confidence scores (conf.)). This leads to a different ranking and therefore varying \textit{\acf{PR}} curves, curve interpolations (dashed grey lines) and resulting \textit{\acf{AP}} scores.}
\label{fig:AP-small-conf-changes}
\end{tcolorbox}
\end{figure}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Predicted class probabilities neglected within ranking, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/AP_confNotChangeRanking.pdf}
\caption{Effect of neglecting (the absolute values of) predicted class probabilities within the ranking. Reference bounding boxes are shown in dark blue. \textit{Predictions 1} and \textit{2} detect the exact same bounding boxes with variations in their predicted class probabilities (represented by the confidence scores (conf.)) that do not affect the ranking. Therefore, the \textit{\acf{PR}} curves, curve interpolations (dashed grey lines) and resulting \textit{\acf{AP}} scores are the same; the predicted class probabilities are hence unimportant within the ranking.}
\label{fig:AP-conf-not-important}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph{\ac{FP} with low predicted class probabilities} False positive predictions with lower predicted class probabilities than the last correctly predicted reference, corresponding to the end of the \textit{PR} curve, do not affect the \textit{\ac{AP}} scores. Fig.~\ref{fig:AP-FP-tail} shows two examples that are very similar, only differing in the number of wrongly predicted objects. \textit{Prediction 2}, with two \ac{FP}, performs worse than \textit{Prediction 1} with only one \ac{FP}. Nevertheless, the \textit{\ac{AP}} scores are the same for both models, given the low confidence of the second \ac{FP} of \textit{Prediction 2}.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: \ac{FP} with low predicted class probabilities, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Detection/AP_FP_tail.pdf}
\caption{Effect of \acf{FP} predictions with low predicted class probabilities (represented by the confidence scores (conf.)). Reference bounding boxes are shown in dark blue. \textit{Predictions 1} and \textit{2} predict the exact same bounding boxes, but \textit{Prediction 2} shows one additional \ac{FP} detected box with low predicted class probabilities. This is not reflected in the \textit{\ac{AP}} score, as the \ac{FP} is located at the tail of the \textit{\acf{PR}} curve and does not change the curve interpolation (dashed grey lines).}
\label{fig:AP-FP-tail}
\end{tcolorbox}
\end{figure}
\subsubsection{Pitfalls related to segmentation}
\label{sec:pitf:segmentation}
\hfill\\This section focuses on limitations for semantic segmentation, but some of them are also transferable to other problem categories, such as instance segmentation. Limitations of metrics are typically related to the following properties:
\begin{itemize}
\item Small size of structures relative to pixel size (Figs.~\ref{fig:DSC-small} and~\ref{fig:clDice-small}, F3.1)
\item High variability of structure sizes (Fig.~\ref{fig:high-variability}, F3.2)
\item Complex shapes of structures (Fig.~\ref{fig:DSC-shapes}, F3.3)
\item Particular importance of structure volume (Fig.~\ref{fig:volume}, F2.2)
\item Particular importance of structure center (Fig.~\ref{fig:center}, F2.3)
\item Particular importance of structure boundaries (Fig.~\ref{fig:outline}, F2.1)
\item Possibility of multiple labels per unit (Fig.~\ref{fig:multi-labels}, F3.4)
\item High inter-rater variability (Fig.~\ref{fig:low-quality}, F4.2.1)
\item Possibility of spatial outliers in reference annotation (Fig.~\ref{fig:DSC-artifact}, F2.5.4 and F4.2.2)
\item Possibility of reference or prediction without the target structure (Fig.~\ref{fig:empty}, F4.5 and F5.2)
\item Preference for over- \textit{vs.} undersegmentation (Fig.~\ref{fig:DSC-overunder}, F2.5.2)
\end{itemize}
Further pitfalls are related to technical peculiarities, such as the choice of global decision threshold for creating the confusion matrix (Fig.~\ref{fig:seg-threshold}, F2.6 and F5.1) and the image resolution (Fig.~\ref{fig:DSC-grid-size}).
The limitations are presented for the most commonly used overlap segmentation metrics, namely \textit{\ac{DSC}}, \textit{\ac{IoU}}, and the most common boundary-based metrics, namely \textit{\ac{HD}}, \textit{\ac{HD95}}, \textit{\ac{ASSD}}, \textit{\ac{MASD}} and \textit{\ac{NSD}}. The \textit{\ac{NSD}} calculation is based on a user-defined threshold (cf. Fig.~\ref{fig:definition-nsd}). Results differ for different thresholds. Unless stated otherwise, we set the threshold to $\tau = 1$.\\
To preserve clarity of the illustrations, specific values may only be highlighted for one metric from each metric family, if the other metrics share similar properties (e.g. \textit{\ac{DSC}} and \textit{\ac{IoU}} share the same properties). Green metric values correspond to a "good" value (e.g. a high \textit{\ac{DSC}} or a low \textit{\ac{HD}} score), whereas red values correspond to a "bad" value (e.g. a low \textit{\ac{DSC}} or a high \textit{\ac{HD}} score). Green check marks indicate metric scores reflecting the research question, red crosses show those that do not. Please note that a low \textit{\ac{DSC}} value (or similar) is not automatically a "bad" score. A metric value should always be put into perspective and compared to inter-rater variability. We only use the terms "good" and "bad/poor" for simplicity.
\newpage
\paragraph*{\textbf{Small size of structures relative to pixel size}} Segmentation of small structures, such as brain lesions or cells imaged at low magnification, is essential for many image processing applications. In these cases, the \textit{\ac{DSC}} or \textit{\ac{IoU}} may not be appropriate metrics, as illustrated in Fig.~\ref{fig:DSC-small} (cf. \cite{cheng2021boundary}). In fact, a single-pixel difference between two predictions can have a large impact on the metric values. Given that the correct outlines (e.g. of pathologies) are often unknown and taking into account the potentially high inter-observer variability related to generating reference annotations~\citep{joskowicz2019inter}, it is typically not desirable for few pixels to influence the metrics as much. This problem is particularly amplified in cases of large variability of structure sizes (cf. Fig.~\ref{fig:high-variability}). The same problem arises for other versions of the \textit{\ac{DSC}} or \textit{\ac{IoU}}. For example, the \textit{\ac{clDice}} is often used in the case of tubular structures. Similarly to the original \textit{\ac{DSC}} metric, a single-pixel difference will have a larger influence on the \textit{\ac{clDice}} for small tube structures compared to larger ones. This pitfall also applies to object detection tasks. It should be noted that once a data set exclusively contains only very tiny structures, one may consider this problem to be an object detection rather than a segmentation problem.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Small structures, colback=white]
\centering
\includegraphics[width=0.85\linewidth]{pitfall-paper/images/Segmentation/small_large_v2.png}
\caption{Effect of structure size on the \textit{\acf{DSC}}. The predictions of two algorithms (\textit{Prediction 1/2}) differ in only a single pixel. In the case of the small structure (bottom row), this has a substantial effect on the corresponding metric value (similar for the \textit{\acf{IoU}}). The effects are considerably lower for the boundary-based metrics (\textit{\acf{HD}}, \textit{\acf{HD95}}, \textit{\acf{ASSD}} and \textit{\acf{NSD}}.}
\label{fig:DSC-small}
\end{tcolorbox}
\end{figure}
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Small tubular structures, colback=white]
\centering
\includegraphics[width=0.85\linewidth]{pitfall-paper/images/Segmentation/small_large_clDice.png}
\caption{Effect of structure size on the \textit{\acf{clDice}}. The predictions of two algorithms (\textit{Prediction 1/2}) differ in only a single pixel. In the case of the small tubular structure (bottom row), this has a substantial effect on the corresponding \textit{\ac{clDice}} value.}
\label{fig:clDice-small}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{High variability of structure sizes}} The size of target structures may vary substantially, both within an image and across images. For example, in medical instrument segmentation in laparoscopic video data, an image frame may contain full-sized instruments as well as only the tip of an instrument just entering the scene \cite{ross2021comparative}. In these cases, metrics need to be chosen carefully. As shown in the example above (Fig.~\ref{fig:DSC-small}), metrics such as the \textit{\ac{DSC}} or \textit{\ac{IoU}} are typically not well-suited for very small structures. Furthermore, size stratification -- the aggregation of metric values for objects of similar sizes to uncover differences between them -- should be employed. Fig.~\ref{fig:high-variability} shows an exemplary data set of four images, containing three large structures and one small structure. When aggregating over all \textit{\ac{DSC}} values, the average \textit{\ac{DSC}} is 0.82. Computing the average for large and small structures separately, however, shows that the performance is much lower for the small structures compared to the large ones, demonstrating the large influence of the low metric values of small objects. This pitfall also applies to object detection tasks and other metrics.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: High variability of structure sizes, colback=white]
\centering
\includegraphics[width=\linewidth]{pitfall-paper/images/Segmentation/High_variability_v3.pdf}
\caption{Effect of high variability of structure sizes across images. As shown in Fig.~\ref{fig:DSC-small}, \textit{\acf{DSC}} scores penalize errors in small structures much more, leading to large and small structures influencing the overall averaged performance to different extents. Only by computing the average for small and large structures separately can it be seen that the prediction in the present example is much poorer for the small structure. $\varnothing$ refers to the average \textit{\ac{DSC}} values.}
\label{fig:high-variability}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Complex shapes of structures}} Metrics measuring the overlap between objects are not designed to uncover differences in shapes. This is an important problem in many applications such as radiotherapy, for which identifying and treating all parts of the tumor is essential to avoid recurrence \cite{burnet2004defining}. Fig.~\ref{fig:DSC-shapes} illustrates that completely different object shapes may lead to the exact same \textit{\ac{DSC}} and \textit{\ac{IoU}} values. Boundary-based measures are able to detect the changes in shapes \cite{taha2015metrics}. Note that this pitfall also applies to object detection tasks.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Shape unawareness, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/shapes_v2.png}
\caption{Effect of different shapes. The shapes of the predictions of five algorithms (\textit{Predictions 1-5}) differ substantially, but lead to the exact same \textit{\acf{DSC}} and \textit{\acf{IoU}}, while boundary-based metrics (\textit{\acf{HD}}, \textit{\acf{HD95}}, \textit{\acf{ASSD}} and \textit{\acf{NSD}}) consider the shape differences.}
\label{fig:DSC-shapes}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Particular importance of structure volume}} Depending on the domain focus, a surgeon, radiologist or similar may be especially interested in the volume of a segmented structure. The most commonly used metrics may, however, result in predictions at entirely wrong locations if boundary or overlap are not considered. Fig.~\ref{fig:volume} shows two predictions of a 3x3 square structure, both of them being at the wrong position. While the volume difference is correct for both predictions, the overlap is zero. Only boundary-based metrics will indicate the magnitude of mislocalization of the predicted objects.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Ignoring structure location when focusing on volume, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/properties.png}
\caption{Effect of only focusing on the volume of an object. Both \textit{Predictions 1} and \textit{2} result in the correct volume difference of 0, but do not overlap with the reference (\textit{\acf{DSC}} and \textit{\acf{IoU}} of 0). Only the boundary-based measures (\textit{\acf{HD}}, \textit{\acf{HD95}}, \textit{\acf{ASSD}} and \textit{\acf{NSD}}) recognize the mislocalization.}
\label{fig:volume}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Particular importance of structure center}} The structure center point or center line may be more important than an accurate boundary or overlap of the structure, as for example in nerve segmentation \cite{mlynarski2020anatomically}. In these cases, the accuracy of the center point or line should be examined via an additional metric to make sure the center is correct for the prediction. Fig.~\ref{fig:center} shows two predictions yielding the same \textit{\ac{DSC}} values, as they have the same overlap to the reference annotation. However, only \textit{Prediction 1} is centered around the same point as the reference, while \textit{Prediction 2} is shifted slightly towards the upper left corner and thus centered incorrectly. This pitfall also applies to object detection tasks. It should be noted that once the center location is of particular importance to the task, one may consider it an object detection rather than a segmentation problem.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Center unawareness of overlap metrics, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/Center_v2.png}
\caption{The most common counting-based metrics are poor proxies for the center point alignment. Here, \textit{Predictions 1} and \textit{2} yield the same \textit{\acf{DSC}} value although \textit{Prediction 1} approximates the location of the object much better.}
\label{fig:center}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Particular importance of structure boundaries}} While boundary-based metrics such as the \textit{\ac{HD}(95)}, \textit{\ac{ASSD}} and others can help to detect shape differences between the reference and the predicted object, they do not focus on the object itself. As shown in Fig.~\ref{fig:outline}(top), the boundary-based metrics do not recognize a prediction with a large hole inside as poor (\textit{Prediction 2}). Furthermore, in Fig.~\ref{fig:outline}(bottom) \cite{taha2015metrics}, those metrics do not punish the spotted pattern within the object. It should be noted that this behaviour may also be desirable. For example, it may be highly difficult to decide whether a necrotic core (hole) is present in a tumor or not. A boundary-based metric would not punish errors resulting from such annotation uncertainties.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Holes in the segmentation ignored by boundary-based metrics, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/outline_2.png}
\caption{Boundary-based metrics commonly ignore the overlap between structures and are thus insensitive to holes in structures. \textbf{Upper part:} Here, \textit{Predictions 1} and \textit{2} feature holes within the object. The boundary-based metrics (\textit{\acf{HD}}, \textit{\acf{HD95}}, \textit{\acf{ASSD}}, \textit{\acf{NSD}}) do not recognize this problem, yielding very good or even perfect metric scores of 0.00 for the \textit{\ac{HD}(95)/\ac{ASSD}} and 1.00 for the \textit{\ac{NSD}} (\textit{Prediction 2}), whereas the overlap-based metrics (\textit{\acf{DSC}}, \textit{\acf{IoU}}) reflect the fact that the inner area is missed by the predictions. \textbf{Lower part:} Here, \textit{Predictions 1} and \textit{2} feature a spotted pattern within the object. Although the boundary of \textit{Prediction 2} is perfect, the holes are penalized by the boundary-based metrics compared to \textit{Prediction 1}. \textit{Prediction 1} shows an imperfect boundary. Depending on the surface-based metric used, slight deviations in the boundary (here in \textit{Prediction 1}) may be tolerated, reflected by calculating the \textit{\ac{NSD}} for $\tau=1$.}
\label{fig:outline}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Possibility of multiple labels per unit}} In several biomedical imaging scenarios, multiple labels per pixel may be possible. A prominent example would be the tumor core inside the tumor \citep{menze2014multimodal}. Often, however, prior knowledge related to such scenarios (e.g. a tumor core cannot lie outside the tumor) is not reflected by common metrics, which simply calculate the agreement of the reference and prediction per class. Fig.~\ref{fig:multi-labels} shows two predictions for a multi-label example. The \textit{\ac{DSC}} value of \textit{Label 2}, which is required to be inside of \textit{Label 1}, is higher for \textit{Prediction 2} although \textit{Label 2} is also found outside the\textit{ Label 1} area. For simplicity, we only show the results for the \textit{\ac{DSC}} metric. This pitfall also applies to object detection tasks.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Multiple labels per pixel, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/multiple_labels.png}
\caption{Effect of multiple labels per pixel. The requirement of \textit{Label 2} being inside of \textit{Label 1} is violated by \textit{Prediction 2}. Nevertheless, \textit{Prediction 2} shows a higher \textit{\acf{DSC}} score compared to \textit{Prediction 1}, which adheres to the requirement.}
\label{fig:multi-labels}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Noisy reference standard}} A high quality reference annotation is crucial to determine the performance of a supervised learning algorithm. A prediction can be almost perfect, but low quality reference images will still result in a bad metric score. Especially in the medical domain, the inter-rater variability is often very high as domain knowledge is required and experts themselves often disagree \cite{joskowicz2019inter}. Fig.~\ref{fig:low-quality} shows two masks from different annotators approximating the same structure. Although the annotations differ only slightly at the boundary, the \textit{\ac{DSC}} score is 0.7. With such inter-rater variability, a \textit{\ac{DSC}} score of 1 would not be achievable in practice. To address this issue, the \textit{\ac{NSD}} metric can be applied as an alternative or additional metric, as it is designed to allow a certain tolerance of outline pixels based on the threshold $\tau$. This pitfall can also be translated to object detection and image-level classification tasks.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Inter-rater variability , colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/low_annotation_quality_v4.pdf}
\caption{Effect of inter-rater variability between two annotators. Assessing the performance of \textit{Annotator 2} while using \textit{Annotator 1} for creating the reference annotation leads to a low \textit{\acf{DSC}} score because inter-rater variability is not taken into account by common overlap-based metrics. In contrast, the \textit{\acf{NSD}}, applied with a threshold of $\tau = 1$, captures this variability. It should be noted, however, that this effect occurs primarily in small structures as overlap-based metrics tend to be robust to variations in the object boundaries in large structures. Further abbreviations: \textit{\acf{IoU}}, \textit{\acf{HD}}, \textit{\acf{HD95}}, \textit{\acf{ASSD}}.}
\label{fig:low-quality}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Possibility of outliers in reference annotation}} The presence of spatial outliers, such as noise or reference annotation artifacts, may severely impact performance metric values. Fig.~\ref{fig:DSC-artifact} demonstrates how a single erroneous pixel in the reference annotation (or the prediction) leads to a substantial decrease in the measured performance, especially in the case of the \textit{\ac{HD}}. Using the 95\% percentile instead of the maximum (\textit{\ac{HD95}}) to compute the distance significantly improves the metric score as it can handle outliers. Please note that the presented example may also be seen vice versa, with a prediction including single pixel errors. It should further be noted that whether or not outliers should be considered depends on the respective research question.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Noise and artifacts, colback=white]
\centering
\includegraphics[width=0.9\linewidth]{pitfall-paper/images/Segmentation/noise_v2.pdf}
\caption{Effect of annotation errors/noise. A single erroneously annotated pixel may lead to a large decrease in performance, especially in the case of the \textit{\acf{HD}} when applied to small structures. The \textit{\acf{HD95}}, on the other hand, was designed to deal with spatial outliers. Further abbreviations: \textit{\acf{DSC}}, \textit{\acf{IoU}}, \textit{\acf{ASSD}}, \textit{\acf{NSD}}.}
\label{fig:DSC-artifact}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Possibility of reference/prediction without target structure(s)}} A given data set may contain reference annotations without the target structure(s). For example, the data set may consist of healthy and sick patients. A healthy patient will not have a tumor in the image, yielding an empty reference if the tumor is the targeted structure. An algorithm should be careful not to classify a healthy patient as tumourous as this may lead to unnecessary medical interventions. Similarly, a patient with a tumor should not be classified as healthy (empty prediction). These cases require special care to be taken in the validation, because some metrics may be undefined due to division by zero errors or similar. It is necessary to either choose appropriate metrics that consider empty references (or predictions) or account for it in the metric implementation. For example, boundary-based metrics such as the \textit{\ac{HD}(95)} and \textit{\ac{ASSD}} will be \texttt{\ac{NaN}} if one of the structures is empty. Fig.~\ref{fig:empty} shows three examples, for which several counting- and boundary-based metrics were computed. The top row depicts the case of an empty reference and a prediction of an object. Given the number of \ac{TP} and \ac{FN} being 0, this will result in a division by zero in the \textit{Sensitivity} calculation, yielding a \texttt{\ac{NaN}} score. A similar case is given in the second row, showing an empty prediction for a given target structure in the reference annotation, yielding an undefined \textit{Precision}. When both reference and prediction are empty (bottom row), all scores will be undefined.
Please note that this example is shown for a validation per image, as done for segmentation tasks. For classification and object detection tasks, the validation is typically performed over the whole data set, which would possibly preclude this problem. The presented pitfall also applies to object detection tasks.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Reference or prediction without target structure(s), colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/EmptyRefEmptyPred.pdf}
\caption{Effect of empty references or predictions when applying common metrics per image (here for semantic segmentation). Empty images lead to division by zero for many common metrics as the numbers of the true (T)/false (F) positives (P)/negatives (N) turn zero.}
\label{fig:empty}
\end{tcolorbox}
\end{figure}
\newpage
\paragraph*{\textbf{Technical peculiarities}} Several technical peculiarities also have an impact on metric behaviour. For example, the image resolution and pixel sizes highly influence the reference annotation and the predicted shapes in image processing tasks. Fig.~\ref{fig:DSC-grid-size} illustrates how the reference annotation differs between a low resolution image (top) and a high resolution image (bottom) compared to a circle. The latter is more exact. A prediction of the same size will therefore lead to different corresponding metric values, independent of the type of the metric. This pitfall also applies to object detection tasks.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Grid size resolution, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/grid.png}
\caption{Effect of different grid sizes. Differences in the grid size (resolution) of an image highly influence the image and the reference annotation (dark blue shape (reference) \textit{vs.} pink outline (desired circle shape)). A prediction of the exact same shape (\textit{Prediction 1}) leads to different metric scores due to the different resolution. Abbreviations: \textit{\acf{DSC}}, \textit{\acf{IoU}}, \textit{\acf{HD}}, \textit{\acf{HD95}}, \textit{\acf{ASSD}}, \textit{\acf{NSD}}.}
\label{fig:DSC-grid-size}
\end{tcolorbox}
\end{figure}
\newpage
In some applications such as radiotherapy, it may be highly relevant whether an algorithm tends to over- or undersegment the target structure. The \textit{\ac{DSC}} metric, however, does not represent over- and undersegmentation equally \citep{yeghiazaryan2018family}. As depicted in Fig.~\ref{fig:DSC-overunder}, a difference of a single layer of pixels in the outline yields different \textit{\ac{DSC}} scores (oversegmentation preferred) \cite{taha2015metrics}. Other boundary-based performance values such as the \textit{\ac{HD}} are invariant to these properties.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Oversegmentation \textit{vs.} undersegmentation, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/overunder.pdf}
\caption{Effect of undersegmentation \textit{vs.} oversegmentation. The outlines of the predictions of two algorithms (\textit{Prediction 1/2}) differ in only a single layer of pixels (\textit{Prediction 1}: undersegmentation, \textit{Prediction 2}: oversegmentation). This has no (or only a minor) effect on the \textit{\acf{HD}/(95\%)}, the \textit{\acf{NSD}} and the \textit{\acf{ASSD}}, but yields a substantially different \textit{\acf{DSC}} or \textit{\acf{IoU}} score.}
\label{fig:DSC-overunder}
\end{tcolorbox}
\end{figure}
Another technical peculiarity is the choice of global decision threshold. Most methods in modern image analysis output continuous class scores. While it is quite common to provide those scores in image-level classification and object detection tasks, segmentation architectures often do not output class probabilities per pixel. However, fuzzy segmentation masks are getting more and more common (for instance, see \cite{nida2019melanoma, alzu2020parallel, kaftan2008fuzzy}) and the choice of a global decision threshold $\tau$ is very important for the algorithm's result. Fig.~\ref{fig:seg-threshold} (cf. \cite{nair2018thesis}) shows the predicted class probabilities for a reference annotation. For a binarization typically required for segmentation outputs, a threshold needs to be defined based on which a pixel is assigned to a class (here: a pixel with class probability < $\tau$ corresponds to the background class, otherwise to the foreground class). The resulting segmentation masks are shown for the thresholds 0.2, 0.5 and 0.8. It can be seen that the respective masks completely differ across the thresholds. Consequently, metric values will also vastly change.
\newpage
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Choice of global decision threshold, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/segmentation_thresholds.png}
\caption{Effect of the choice of a global decision threshold for binarization in segmentation problems. The results and metric values for three decision thresholds (0.2, 0.5 and 0.8), from which predicted class probabilities per pixel are translated into a segmentation mask, are provided. Based on the threshold chosen, the predicted objects and resulting metric values change dramatically. }
\label{fig:seg-threshold}
\end{tcolorbox}
\end{figure}
\newpage
When it comes to instance segmentation, the \textit{\ac{PQ}} is an attractive metric as it covers segmentation and detection quality in a single score. However, this can be misleading, as shown in Fig.~\ref{fig:pq-sq-vs-dq}. \textit{Prediction 1} with a perfect segmentation and poor detection achieves a \textit{\ac{PQ}} score similar to that of \textit{Prediction 2}, which detects all objects correctly (without any \ac{FP} or \ac{FN}), but only provides moderate segmentation results. If segmentation and detection quality should be assessed individually, two separate metrics - one for segmentation quality and one for detection quality - should be preferred.
\begin{figure}[H]
\begin{tcolorbox}[title= Pitfall: Assessing segmentation and detection quality simultaneously, colback=white]
\centering
\includegraphics[width=1\linewidth]{pitfall-paper/images/Segmentation/PQ_SQvsDQ.png}
\caption{Effect of assessing segmentation and detection quality in a single score. \textit{Prediction 1} achieves a high segmentation but low detection quality (with several \acf{FP} predictions); vice versa for \textit{Prediction 2} (only predicting \acf{TP} instances; no \ac{FP} but low segmentation quality). However, both yield the same \acf{PQ} score.}
\label{fig:pq-sq-vs-dq}
\end{tcolorbox}
\end{figure} | {'timestamp': '2022-06-06T02:16:58', 'yymm': '2206', 'arxiv_id': '2206.01653', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01653'} | arxiv |
\section{Introduction} \label{sec:intro}
Modelling pedestrian behavior in traffic environments is a crucial step in the development and testing of autonomous vehicles (AV) and automated driving systems (ADS). As the environment's most vulnerable road users, misinterpretation of their behavior by an AV can lead to catastrophic consequences. Through rigorous testing of a wide range of traffic scenarios, safe interactions between AVs and pedestrians can be ascertained. A realistic and highly controllable pedestrian simulation model that supports the scenario-based testing process is a valuable tool in testing AV capabilities and responses to critical situations.
In this work, we present a hierarchical pedestrian behavior model that incorporates behavior trees to handle high-level decision-making processes and an adapted Social Force Model to drive low-level motion. Our model caters to scenario-based testing \cite{Kentaro2004} as it provides an explicit representation of decision processes, allowing engineers to inject desired pedestrian behaviors into existing scenarios. Through this process, rare and critical situations, which may be scarce or absent in existing data, can be generated and tested on AV systems to evaluate their responses safely in a simulation environment.
For example, consider the situation of a pedestrian running into the roadway directly in front of a vehicle, causing a collision. If the goal of this test scenario is to cause a collision independent of the agents' starting positions and velocities, recreation of this scenario is difficult with a simple trajectory-based pedestrian that only follows a set speed profile. However, with our model, we can dynamically adjust the pedestrian's speed to ensure a collision occurs, independent of the vehicle's approaching distance and speed. Pedestrians with pre-defined trajectories would require constant manual adjustments in their positioning and speed profiles whenever changes are made to the vehicle's approaching parameters. \Cref{fig:test_scenario_ex} visualizes our model recreating this situation in a test simulation scenario.
\begin{figure}[t]
\centering
\vspace{1em}
\begin{subfigure}{0.48\linewidth}
\includegraphics[width=\linewidth]{collision_scenario_frame_1}
\caption{Pedestrian (p1) speed is 0\,m/s as vehicle's collision with crosswalk is not yet detected.}
\label{subfig:test_scenario_frame_1}
\end{subfigure}
~
\begin{subfigure}{0.48\linewidth}
\includegraphics[width=\linewidth]{collision_scenario_frame_5}
\caption{p1 dynamically adjusts speed to ensure collision with v1 at crosswalk.}
\label{subfig:test_scenario_frame_2}
\end{subfigure}
\caption{Simulation of scenario in which a collision is guaranteed between a pedestrian and a vehicle at a crosswalk}
\label{fig:test_scenario_ex}
\end{figure}
Within the context of traffic simulation, existing microscopic models have a heavy focus on specific interaction scenarios \cite{Millard-Ball2018} \cite{CamaraFanta2018} \cite{LiChuanyao2021} leaving little room for extensibility or they employ a ``black-box'' or non-deterministic approach \cite{Li2012} \cite{Feng2013} \cite{Suo2021} where the pedestrian's actions and overall trajectory can not be derived given the scenario set up and inputs. There are existing models, including numerous Social Force and cellular automata models \cite{Helbing1998} \cite{Blue2001} \cite{Zhang2012}, that demonstrate higher-level behaviors and thought-processes, such as lane formation and bottle-necking; however, they largely do not allow engineers to customize these behaviors or inject specific desired actions into a test scenario. The presented simulation model provides a high degree of control over pedestrian actions and behaviors currently lacking in literature. Our model is explicitly decision-driven, through the use of behavior trees, while still producing realistic low-level movements. Such functionality can greatly benefit the scenario-based testing of AVs, since testers can force rare or possibly dangerous situations involving pedestrians in a safe simulation environment.
Aside from singular-concept approaches, multi-layered models have been developed to address pedestrian behaviors in traffic. Conjunctive use of trajectory-planning, rule-based, and Social Force layers have been implementing to assist the design of shared spaces \cite{Anvari2015} \cite{Rinke2017}. Another common approach is to combine a popular microscopic model, such as a cellular automaton, with higher-level game theoretic concepts \cite{Tanimoto2010} \cite{Guan2016} \cite{Lin2018} \cite{Wu2019}, to construct a multi-layered model in which high and low-level interactions can be handled by separate components. As before, such models lack the flexibility provided by behavior trees, which our model exposes to test engineers as a domain-specific language and allows them to create and customize diverse and realistic scenarios.
In summary, our work makes the following contributions:
\begin{enumerate}
\item a novel model for pedestrian motion simulation, with (i) highly controllable and customizable decision making via behavior trees, including a catalog of reusable pedestrian maneuvers and decision conditions, and (ii) realistic motion via an adapted Social Force Model;
\item an evaluation of the decision-making realism and motion fidelity of the model on two traffic trajectory data sets, showing the ability to replicate (i) the high-level decisions of the empirical pedestrians with a 98\% or better accuracy and (ii) the motion trajectories with an average deviation of 1.36\,m.
\end{enumerate}
\section{Background} \label{sec:background}
In this section we briefly describe some of the background technology and concepts used in our approach.
\subsection{Social Force Model} \label{subsec:sfm}
The Social Force model (SFM) treats pedestrian motion as if it is based on attractive and repulsive physical forces. Our model incorporates a variation of the classical SFM~\cite{Helbing2000} with additional forces. In its classical version, the SFM applies three main collections of forces to the agent: an attracting force drawing the agent towards their destination, a repelling force from each of the other agents in the scene, and a repelling force from each wall or border in the environment. These three forces are summed into an acceleration equation that describes the pedestrian's change in velocity throughout the scenario's duration.
The attracting force, \(\textbf{f}_\text{adapt}\), is responsible for propelling pedestrian \(i\) in the direction \(\textbf{e}_i^0(t)\), pointing towards their destination point. Given a current velocity, \(\textbf{v}_i(t)\), and a desired speed, \(v_i^0(t)\), the attracting force acting on pedestrian \(i\) with mass \(m_i\) is
\[ \textbf{f}_\text{adapt} = m_i \frac{v_i^0(t)\textbf{e}_i^0(t) - \textbf{v}_i(t)}{\tau_i} \]
\noindent
where their acceleration is over characteristic time \(\tau_i\).
Repelling forces acting on the pedestrian are divided into three groups of forces: \(\textbf{f}_\text{otherPeds}\), \(\textbf{f}_\text{vehicles}\), and \(\textbf{f}_\text{borders}\). Each of these forces is composed of a sum of sub-forces directed away from an object (pedestrian, vehicle, or wall). They describe the human tendency to avoid collision with and maintain a comfortable distance from other objects and agents in their surroundings. Further details on the \(\textbf{f}_\text{otherPeds}\) and \(\textbf{f}_\text{borders}\) forces can be found in Helbing et al.'s model \cite{Helbing2000} and \(\textbf{f}_\text{vehicles}\) is presented by Anvari et al.\ \cite{Anvari2015}.
The resulting sum of forces that drives each pedestrian's motion is given by
\begin{equation}
\label{eq:sfm}
m_i \, \frac{d\textbf{v}_i}{dt} = \textbf{f}_\text{adapt} + \textbf{f}_\text{otherPeds} + \textbf{f}_\text{vehicles} + \textbf{f}_\text{borders}
\end{equation}
\subsection{Behavior Trees} \label{BT_background}
Behavior trees can be used to concisely and explicitly model a wide range of decision making processes~\cite{Colledanchise2018}. Within our model, behavior trees are used to select an appropriate maneuver for each pedestrian at each simulation cycle. Each pedestrian contains a personal behavior tree which, at each time step in a given scenario, is ``ticked''. The ticking process traverses the tree with a certain path and ultimately outputs a selected maneuver. The behavior trees used in the presented model are composed of four types of nodes: \emph{selector}, \emph{sequence}, \emph{maneuver}, and \emph{condition}. Selectors and sequences are internal nodes and control the path of the tree traversal, while maneuvers and conditions are the tree's leaf nodes. Each leaf node, after being evaluated, returns a status to their parent node. Valid statuses are \textbf{Success}, \textbf{Failure}, and \textbf{Running}. These statuses affect which nodes are visited next by the tick.
Selector nodes, denoted by a question mark (?), are analogous to a short-circuit OR in that they tick their child nodes sequentially from left to right until a status of \textbf{Success} or \textbf{Running} is received. This status is then returned to the selector's parent node. If all of the child nodes return \textbf{Failure}, then \textbf{Failure} is returned to the selector's parent. On the other hand, sequence nodes, denoted by an arrow (\(\rightarrow\)), are similar to a short-circuit AND. They tick their child nodes sequentially from left to right until a status of \textbf{Failure} is received (or they run out of child nodes). Maneuvers and conditions are leaf nodes that are evaluated and return one of the three statuses to their internal parent node. The maneuver node that is visited last before the tick returns from the entire tree becomes the selected maneuver.
As a simple example, \Cref{fig:btree_example} shows a valid behavior tree an agent could use to determine whether to enter a crosswalk. The process flow of this tree first checks if the crossing signal is green. If so, the pedestrian enters the crosswalk and waits at the entrance otherwise. In the case that the crossing signal is not green, the tick returns from the left side of the tree with a status of \textbf{Failure} (from the diamond condition node). Since the root is a \emph{selector} node, it proceeds to tick the right side, consisting solely of a single maneuver node which will return a non-failure status and become the selected maneuver.
\begin{figure}[ht]
\centering
\includegraphics[width=.75\linewidth]{simple_BT_example}
\caption{Simple behavior tree for entering crosswalk decision demonstrating the use of condition (diamond), maneuver (ellipse), selector (?), and sequence (\(\rightarrow\)) nodes.}
\label{fig:btree_example}
\end{figure}
\section{Model Design} \label{sec:model-design}
To introduce our model, we first discuss the design requirements necessary for a practical pedestrian simulation model.
\subsection{Facilitation of Scenario Creation}
An essential component of scenario-based testing is a straight-forward and clear scenario creation process~\cite{modes2020-01-1204}. Test scenarios involving pedestrians running our model are expressed in GeoScenario~\cite{Queiroz2019}. GeoScenario is a domain-specific language for simple and extensible representation of traffic scenarios, built using the Open Street Map (OSM) standard. All of the essential components of a scenario can be represented in GeoScenario, including dynamic agents, static objects, and the underlying Lanelet2 map, among others. Through GeoScenario, pedestrian agents are represented by nodes containing tags to describe their individual attributes. As GeoScenario abides by the Open Street Map standard, we employ the OSM scenario editor tool, JOSM\footnote{\url{https://josm.openstreetmap.de}}, to create and edit scenarios. JOSM provides engineers with a simple visual tool to quickly add, move, and tag nodes and ways. Pedestrian-specific agents must include tags defining their identifying name, destination point, and the file containing their personal behavior tree.
\subsection{Customizable Pedestrian Behavior}
Behavior trees are an integral part of each scenario as they provide the tester with a fine-level of control over how each pedestrian behaves in a given context. Each pedestrian is assigned a behavior tree file in the scenario definition file which dictates their decision process at each simulation cycle. Our model comes with a library of reusable behavior trees that represent common behaviors, such as walking along a sidewalk and traversing signalized and unsignalized crosswalks. The explicit nature of behavior trees in representing discrete decision-making processes lends itself well to forcing desired behaviors within scenarios. Testers can intentionally trigger particular actions that can lead to critical or dangerous situations; for example, pedestrians unexpectedly running in front of a moving vehicle. The behavior trees designed for our model are also augmented with a number of tunable parameters that define the different ways pedestrians may execute the same maneuver. When importing behavior trees from a library, their parameters and sub-trees can be overridden to define the desired behavior.
\subsection{Dynamic Interactions Between Agents}
Dynamic interactions between agents within a scenario are handled by both the Social Force model and behavior tree components of our model, though in different ways. The Social Force model (SFM) is responsible for immediate, reactionary interactions with vehicles and other pedestrians. At the trajectory level, a collection of repulsive forces is applied to the pedestrian when another agent is in its proximity that causes the pedestrian to naturally avoid collisions. Behavior trees are designed to handle higher-level interactions proactively. Depending on their composition, behavior trees can check the relative states of other agents, such as their distance and speed, to output an informed response to another agent's actions. If required by a scenario, behavior trees can selectively and conditionally modify the forces for specific pedestrians by manipulating SFM parameters.
\subsection{Realistic Human Movements and Decisions}
A practical pedestrian behavior model needs to be able to simulate realistic movements and rational decision-making processes. We evaluate this requirement on our model against two naturalistic data sets with different road structures. Our hierarchical approach of handling high-level decisions with customizable behavior trees that inform low-level trajectory movements is shown to be effective in producing realistic movements and decisions that map to real-world scenarios.
\section{Model Architecture}
The model structure is composed of three layers: the Behavior layer, Maneuver layer, and Motion Planner layer. As an overview, the Behavior layer receives the environment state representation and decides on an appropriate maneuver to execute. This maneuver is then passed to the Maneuver layer, which plans how best to execute the selected maneuver. The layer forms instructions on how to adapt the current trajectory in the form of a vector containing the pedestrian's updated waypoint, direction vector, and desired speed, to pass to the Motion Planner layer. When the Motion Planner layer receives these instructions, it feeds the passed vector into the Social Force Model to determine the state information of the pedestrian for the next time step. Finally, this state information is updated and reflected in the environment. This process flow is visualized in~\Cref{fig:model_process_flow}.
\begin{figure}[ht]
\centering
\vspace{0.5em}
\includegraphics[width=\linewidth]{model_process_flow_2}
\caption{Multi-layered model diagram with process and information flow}
\label{fig:model_process_flow}
\end{figure}
The simulation traffic environment is represented in the two dimensional Cartesian coordinate frame and all computations for pedestrian movements are calculated within this frame. The physical traffic structure of the world is represented by Lanelet2~\cite{Poggenhans2018} compatible map files. Dynamic elements of the environment include the changing states of vehicles, other pedestrians, and traffic lights for both vehicle lanes and crosswalks.
We define two types of pedestrian agents: Empirical Pedestrians (EP) and Simulated Pedestrians (SP). Empirical Pedestrians follow a predefined sequence of trajectory points with preset time intervals and do not use our model to drive their motion. Simulated pedestrians do apply the presented model to determine their movements and are the focus of this paper. Agents' state information contains two dimensional positional, velocity, and acceleration components as well as heading in the vector \(|(x, \dot{x}, \ddot{x}, y, \dot{y}, \ddot{y}, \theta)|_t\). In our evaluation, Empirical Vehicle (EV) agents are used in the experiments; however, our pedestrian model does not depend on the particular implementation of vehicle agents, which allows for targeted testing of a desired ADS or AV system. The state vector format is shared between all types of pedestrian and vehicle agents.
\subsection{Behavior Layer}
The Behavior layer is tasked with determining an appropriate maneuver to execute given the current environmental context. At scenario creation, each SP agent is assigned a text-based behavior tree file representing their personal tree. The Behavior layer consumes the current traffic state estimation as well as configuration parameters for the overall tree and each possible maneuver. The output of this layer is a selected maneuver with its specific configuration parameters, which is subsequently passed to the Maneuver layer. \Cref{tab:maneuvers_and_conditions} contains the available maneuvers and conditions currently implemented in the model. Behavior trees are constructed with a subset of these lists as leaf nodes. This maneuver and condition catalog was derived manually in the process of developing the behavior trees required to simulate each of the pedestrians in the data sets discussed in Section~\ref{sec:evaluation}.
\begin{table}[ht]
\centering
\caption{Maneuvers and conditions implemented in model}
\label{tab:maneuvers_and_conditions}
\begin{tabular}{l l}
\toprule
Maneuvers & Conditions \\
\midrule
Keep in Lane & Reached goal \\
Stop & Has target crosswalk \\
Enter Crosswalk & Approaching target crosswalk \\
Wait at Crosswalk & At target crosswalk entrance \\
Increase Walking Speed & At target crosswalk exit \\
Select Crosswalk by Light State & Waiting at target crosswalk entrance \\
Return to Crosswalk Entrance & Target crosswalk has signal \\
& Crossing signal is green/red/yellow \\
& Can cross before signal turns red \\
& Vehicle approaching crosswalk \\
\bottomrule
\end{tabular}
\end{table}
As explained and visualized in Section~\ref{BT_background}, the internal nodes of a behavior tree are sequence and selector nodes and the leaf nodes are maneuver, condition, and, optionally, sub-tree nodes. The internal nodes dictate the traversal path of the ``tick'' based on the return statuses of leaf nodes. A sub-tree is itself a complete behavior tree that can be ``plugged in'' in place of a leaf node of a different tree. Sub-trees are simply an extension of their base tree that are useful to maintain modularity and, in our case, add varying levels of behavior to control how different pedestrians react to the same situation. In our model, we have designed three sub-trees, representing three levels of aggressiveness, to define different decision-making processes when a pedestrian is planning to enter a crosswalk. We label the three levels of aggressiveness as Low, Medium, and High. Briefly, low aggressiveness pedestrians only enter the crosswalk when the crossing signal is green (or there is no crossing signal at all). A medium aggressiveness pedestrian enters on green, but also on a yellow signal when they judge that they can sufficiently cross before the red signal. Finally, the pedestrians with a high level of aggressiveness choose to enter the crosswalk regardless of the signal state as long as they are not put in danger by a vehicle in doing so.
At each simulation cycle, the behavior tree of each pedestrian is ticked and an appropriate maneuver is selected to be executed by the following layers. This maneuver is passed as input to the Maneuver layer for interpretation.
\subsection{Maneuver Layer}
The job of the Maneuver layer is to translate a maneuver received from the Behavior layer into instructions on how the pedestrian should adjust their trajectory. The instructions must be interpretable by the subsequent Motion Planner layer. Each received maneuver is converted into low-level instructions containing the following three components: a waypoint, a desired direction unit vector, and a desired speed. A waypoint is defined as an intermediate goal point the pedestrian visits before its final destination. As an example of translating a selected maneuver, if the \emph{Enter Crosswalk} maneuver is received, the Maneuver layer determines the updated waypoint to be a point at the end of the crosswalk, the desired direction vector to be the unit vector pointing to the new waypoint, and the desired speed to be the default desired speed of the pedestrian. These three components are passed to the next layer, the Motion Planner layer, which handles the execution of the selected maneuver.
\subsection{Motion Planner Layer}
The Motion Planner layer is driven by an adaptation of the Social Force Model. It receives the three components passed by the Maneuver layer describing changes to the pedestrian's trajectory. This layer also has access to the traffic state estimation and therefore all positions and velocities of the other agents in the scene. Our model implements the classic SFM described in Section~\ref{subsec:sfm} extended by Anvari's method \cite{Anvari2015} for handling pedestrian-vehicle interactions. The parameters of our SFM were manually calibrated through simulation testing. Our traffic environments in Section~\ref{sec:evaluation}) did not contain any walls, and thus the wall forces are currently not included. Walking within a sidewalk or crosswalk's bounds is handled through the \emph{Keep in Lane} maneuver, which uses a desired walking direction vector (that may not necessarily point to the waypoint) to guide the pedestrian within the sidewalk or crosswalk (i.e., a pedestrian lane) and bias it along the right or left lane-boundary.
Wall forces may be added for future environments containing physical walls.
The Motion Planner layer is tasked with running an iteration of the Social Force model's formula~\eqref{eq:sfm} to determine the model pedestrian's change in velocity at each simulation time step. Subsequently, this layer directly updates the pedestrian's state information before the next simulation cycle.
\section{Implementation}
The presented model is written in Python and integrated into GeoScenario Server, a full scenario simulation environment capable of running traffic scenarios as a standalone application. The Server provides the necessary infrastructure for full scenario simulation. It parses GeoScenario scenario files and initializes the necessary elements (pedestrians and vehicle agents, agent goal points, traffic lights, etc.), reads and loads the Lanelet2 map file to provide the underlying road network structure for the scenario, maintains the static and dynamic environment and facilitates the information flow between agents and their surrounding environmental context, and finally runs the scenario by iterating through each of its agents to update their state in the environment at each simulation cycle. Vehicles are simulated with the SDV model from Queiroz et al.~\cite{Queiroz2022_arXiv}. Pedestrians originally used a simple model with Pre-defined Trajectories (PDTs). We extended the server by adding our pedestrian model as an alternative to replace the PDT-based model.
GeoScenario Server provides the optional integration with WISE Sim, a simulator based on UnrealEngine\footnote{\url{https://www.unrealengine.com}} to run the WISE Automated Driving System. The server incorporates a shared-memory interface with WISE Sim to integrate its dynamic agents and scenario environment into the simulator, but it also features an experimental integration with the CARLA simulator~\cite{CARLA-pmlr-v78-dosovitskiy17a}. More details on the GeoScenario Server and how to use the pedestrian model can be found at {\small\url{https://geoscenario2.readthedocs.io}}.
\section{Evaluation} \label{sec:evaluation}
We assess our model in terms of how well it can reproduce low-level trajectories and high-level decisions observed in a naturalistic data set, as well as its extensibility when it is applied to environments with different road structures and geometries.
\subsection{Evaluation Scenario Configuration}
To approach and assess our evaluation criteria, we need a standardized process for comparing a simulated pedestrian generated by our model against a real-world pedestrian from a naturalistic data set. We devise a process to create \textit{evaluation scenarios}. These generated scenarios assist in validating our model against real-world data and provide a standard process that can be applied to any data set in a compatible format.
The idea of an evaluation scenario is to replace a single pedestrian in a given traffic recording with a simulated pedestrian and observe how it interacts with other pedestrians and whether it follows the same trajectory as the empirical pedestrian it replaced. In terms of a GeoScenario scenario, one pedestrian is selected as the \textit{evaluation pedestrian} and is created as an SP agent while all other pedestrians and vehicles in the recording are created as EP and EV agents respectively, and follow their corresponding trajectories from the data set. We refer to the data set pedestrian that the SP agent replaced as the \textit{empirical pedestrian} or alternatively, the evaluation pedestrian's \textit{empirical counterpart}. The scenario begins when the evaluation pedestrian enters the recording and ends when they exit.
The SP agent is initialized with three pieces of knowledge about its empirical counterpart: its starting position, its last position, and its average walking speed. In terms of the SFM component of the model, the last position is set as the SP's destination point and the average walking speed is set as the SP's desired speed.
The evaluation scenario creation process is repeated for each individual pedestrian in the data set, resulting in a unique evaluation scenario for each real-world pedestrian. As a result, each pedestrian in the data set produces their own evaluation scenario in which they are replaced by a model pedestrian that dynamically interacts with the other agents. This process compiles a suite of evaluation scenarios on which we can perform analysis and draw conclusions in terms of our evaluation criteria.
Two separate naturalistic data sets from different locations in Ontario, Canada, were used in the evaluation process.\footnote{\url{https://wiselab.uwaterloo.ca/waterloo-multi-agent-traffic-dataset/}} Each data set contains video files recorded by an overhead drone. The video files were then analyzed and relevant information, such as road user trajectory tracking and traffic light timings, was extracted and saved into a database. The first data set, referred to as the \textit{intersection} data set, was recorded at a busy four-way intersection with four signalized pedestrian crosswalks and two additional unsignalized crosswalks, each one across a right-turn merge lane (or slip lane). The second, referred to as the \textit{single crosswalk} data set, contains a single unsignalized crosswalk across a two-way two-lane road at a university.
During evaluation, we noted that the scenarios at the intersection location had relatively longer durations with an average of 66.82 seconds. Due to the minimal knowledge about the empirical trajectory, a concern arose that small deviations in the trajectories early in the scenario may amplify and compound into large deviations further into the scenario. These large deviations may not be representative of the model's performance at each moment in time and may be consequences of previous error. To mitigate this, we introduce segmented scenarios, in which each full evaluation scenario is subdivided into multiple segmented scenarios. Each segmented scenario represents one section of the pedestrian's journey spanning, for example, a single crosswalk or a single segment of sidewalk. For each evaluation scenario from the intersection data set, one or more additional segmented evaluation scenarios are created and grouped separately.
\begin{figure*}[ht]
\captionsetup[subfigure]{justification=centering}
\begin{subfigure}{0.32\linewidth}
\includegraphics[trim=0 0cm 1.5cm 1.25cm,clip,width=\linewidth]{uni_weber_770_8}
\caption{Intersection location\\ED: 1.81\,m\\Fr\'{e}chet: 1.69\,m}
\label{subfig:uni_weber_ex_1}
\end{subfigure}
~
\begin{subfigure}{0.32\linewidth}
\includegraphics[trim=0 0cm 1.5cm 1.25cm,clip,width=\linewidth]{uni_weber_770_9}
\caption{Intersection location\\ED: 1.81\,m\\Fr\'{e}chet: 1.82\,m}
\label{subfig:uni_weber_ex_2}
\end{subfigure}
~
\begin{subfigure}{0.32\linewidth}
\includegraphics[trim=0 0cm 1.5cm 1.25cm,clip,width=\linewidth]{ring_road_602_45}
\caption{Single crosswalk location\\ED: 0.14\,m\\Fr\'{e}chet: 0.32\,m}
\label{subfig:ring_road_ex_1}
\end{subfigure}
\caption{Trajectory traces of example evaluation scenarios with varying paths from both data set locations. Empirical trajectories are displayed as blue dots and the simulated trajectories are shown as a solid red line.}
\label{fig:traj_trace_examples}
\end{figure*}
\subsection{Realism of Low-Level Trajectories} \label{subsec:trajectory_metrics}
It is crucial that our behavior model produces pedestrian movements that are as natural and human-like as possible in order to be relied upon as a realistic representation of pedestrians in test scenarios. To evaluate our model's effectiveness at generating realistic motion, we run the evaluation scenarios and record each evaluation pedestrian's generated trajectory. We compare this simulated trajectory generated by our model with the trajectory of the corresponding empirical pedestrian by two trajectory-matching metrics: Euclidean distance and discrete Fr\'{e}chet distance. Given the dynamic nature of humans, it is unreasonable to expect a single configuration of our model to completely cover the varying behaviors of all the pedestrians in the data set. To accommodate this, we manually search for a custom configuration of parameter values for each evaluation scenario that best matches the corresponding real-world pedestrian's actions and behaviors.
The Euclidean distance (ED) measures the average distance between each pair of corresponding points between the simulated and empirical trajectories. The ED metric we use is also known as the spatio-temporal Euclidean distance (STED)~\cite{Nanni2006}. The points of each trajectory are equi-timed and recorded at each simulation time step in the evaluation scenario. On the other hand, the Fr\'{e}chet distance provides a measure of geometric similarity between the trajectories or paths. It does not depend on the velocity profiles as the Euclidean distance does and instead judges the similarity in ``shape'' of the two compared trajectories.
The majority of test cases during development of our model were derived from the intersection data set. While this data set provides a substantial number of pedestrians exhibiting a wide range of behaviors, a goal of any useful pedestrian model should be extensibility to differing road structures and geometries. We test the generalization and extensibility of our model by extracting evaluation scenarios from the second data set (single crosswalk). We evaluate the model's ability to navigate this new road structure with the same trajectory-matching metrics. Table~\ref{tab:trajectory_results} displays the average ED, the maximum ED, and the average FD over the scenarios on each data set location.
To give context to our model's results, we introduce a method to generate a baseline trajectory-approximation for each empirical pedestrian. We produce a baseline trajectory for each evaluation scenario based on the empirical path. We first define a set of points on the intersection map that can be connected in various orders to approximate the empirical paths. The selected map points closely resemble the waypoints a model pedestrian may select to navigate through the intersection. A baseline trajectory is constructed by manually selecting an ordered set of points, beginning and ending with the start and end points, respectively, that best approximates the data set pedestrian's path. Equi-distanced and equi-timed points are then linearly interpolated between these points to form a trajectory with the same number of points as the corresponding empirical trajectory.
\begin{table}[ht]
\centering
\caption{Trajectory-matching metrics}
\label{tab:trajectory_results}
\begin{tabular}{r | r | c c c c}
\toprule
\multirow{2}{*}{Location} & \multirow{2}{*}{Length} & \multirow{2}{*}{\# Scenarios} & ED & Max.\ ED & Fr\'{e}chet \\
& & & (m) & (m) & (m) \\
\midrule
\multirow{3}{*}{Intersection} & Baseline & 198 & 5.45 & 12.48 & 2.90 \\
& Full & 198 & 2.23 & 5.21 & 3.04 \\
& Seg. & 527 & 1.55 & 2.65 & 1.81 \\
\midrule
Crosswalk & Full & 1017 & 1.36 & 2.01 & 1.71 \\
\bottomrule
\end{tabular}
\end{table}
It is interesting to note that the baseline method has a slightly improved Fr\'{e}chet distance over the model's full intersection scenarios. A reasonable explanation for this is that the baseline does not react to other pedestrians along the path, as it is simply a set of distances between waypoints. The model, on the other hand, interacts with other pedestrians and vehicles in their vicinity as do the empirical pedestrians. This introduces the risk of the model choosing a different course of action for their interaction than their empirical counterpart, for example, avoiding oncoming pedestrians on the right side instead of left, resulting in larger points of error. The baseline method, being non-reactive, averages out these deviations and may result in an improved geometric-based metric over a long duration scenario.
To visually confirm our model's trajectory-matching effectiveness, we trace both the simulated and empirical pedestrians' trajectories overlaid on a outline of the map file. \Cref{fig:traj_trace_examples} shows traces of evaluation scenarios at both the intersection location (\Cref{subfig:uni_weber_ex_1,subfig:uni_weber_ex_2}) and the single crosswalk location (\Cref{subfig:ring_road_ex_1}).
We note that the individual layers of the model are not evaluated independently. The Social Force model and its variations have been shown to effectively model both the individual movements of agents in sparse groups~\cite{Lakoba2005} and the crowd dynamics of dense groups~\cite{Helbing1995} \cite{Helbing2000} \cite{Mehran2009}. We focus on the conjunctive multi-layer use of high and low-level planners to produce realistic motion.
\subsection{Realism of High-Level Decisions}
For a pedestrian behavior model to properly represent the behaviors of real-world pedestrians, not only must it model the low-level trajectory movements, but it must also be able to replicate high-level decision-making processes. In order to measure this criterion, we need to define a metric by which we can conclusively declare that a decision made by a model pedestrian is the same decision made by its empirical counterpart. First, we must define a list of decisions to be observed from the naturalistic data. It was determined that there are two notable decisions pedestrians make while navigating an intersection.
\begin{enumerate}
\item Given a set of accessible crosswalks and the requirement that at least one crosswalk must be crossed to reach the destination, which crosswalk is selected to cross
\item Given a target crosswalk that the pedestrian has already decided to take which displays a red/yellow crossing light state, will the pedestrian begin to cross or wait until the next green state
\end{enumerate}
The above decisions were designed to ensure a binary response can be recorded for each instance of the decision across evaluation scenarios. The model pedestrian either makes the same decision as the data set pedestrian or they do not. In the rest of this section, we refer to these decisions as Decision 1 and 2 respectively. Note that this metric is only considered on the intersection data set due to the overly simplified road structure of the second data set location. For each full evaluation scenario, we noted the decision points where one of the two listed decisions were made. If the model pedestrian makes the same decision, a \textit{Same} data point is recorded, otherwise we record a \textit{Not Same} data point. \Cref{tab:decision_metric_results} displays the results of this process.
\begin{table}[ht]
\caption{Summary of decision-based metric results on full length evaluation scenarios using the intersection data set}
\label{tab:decision_metric_results}
\centering
\begin{tabular}{ r | c c c }
\toprule
\multirow{2}{*}{Decision} & Decision Points & \multicolumn{2}{c}{Same Decisions}\\
& \# & \# & \% \\
\midrule
1 & 253 & 253 & 100.0 \\
2 & 148 & 145 & 98.0 \\
\bottomrule
\end{tabular}
\end{table}
We see that our model pedestrians selected the same crosswalk when presented with multiple options as the real-world pedestrian 100\% of the time. However, there are three instances where the model pedestrian failed to enter the crosswalk at the same time as defined by Decision 2. After investigation, all three of these instances were due to the real-world pedestrian waiting at a red signal for most of its duration, then, when the vehicles' traffic lights show a two-way advanced green signal, they decide to enter the crosswalk as soon as there are no more conflicting left-turning vehicles. An adjustment to the High level of aggressiveness can account for this specific situation. A range of behaviors can be implemented, including a behavior where the probability of entering the crosswalk on a red signal increases with waiting time.
\subsection{Vehicle-Pedestrian Collision Scenario}
To showcase our model's practicality in creating critical scenarios, we revisit the scenario outlined in~\Cref{sec:intro}. The goal of this scenario is to demonstrate a plausible yet dangerous scenario that cannot be replicated with simple pedestrians that follow a constant speed profile. We created a scenario with one vehicle agent and one pedestrian agent in which the vehicle wants to pass through an unsignalized crosswalk that the pedestrian wants to cross. The pedestrian dynamically adjusts their walking or running speed to ensure a collision occurs at the crosswalk. At a technical level, this is achieved with our model by including a parameter in the \textbf{Keep in Lane} maneuver: \textit{collision\_vehicle = [vehicle\_id]}. Provided that the \textit{vehicle\_id} exists in the scenario and there is a crosswalk at which the agents can meet, the pedestrian dynamically determines a collision point based on the point of intersection between the crosswalk and the vehicle's heading vector. With assumed perfect perception of the vehicle's distance and speed, the pedestrian adjusts their own speed to ensure they reach the collision point at the same time as the vehicle.
A key benefit to using our model for this scenario is that the pedestrian will ensure a collision occurs regardless of the starting positions and velocities of the agents. With preset speed-profile pedestrians, the tester would need to manually reset the scenario's parameters with either trial and error or complex search-based computations to achieve the same result. Instead, with our approach, no changes need to be applied in order to force a collision scenario at every run.
\section{Discussion and Limitations} \label{sec:limitations}
In the current version of our model, we do not consider the implicit or explicit communication between human drivers and pedestrians, such as changes in speed or hand gestures. Such interactions are important considerations in modelling pedestrian movement and behavior. In our evaluation, we do not have access to this communication due to the data sets being recorded by overhead drones. Previous works, such as TrafficSim \cite{Suo2021}, have learned pedestrian behavior taking into account all forms of communication and external factors through data-driven approaches. Given the black-box nature of such approaches, we differentiate our work by providing finer control over individual pedestrian behaviors and interactions.
An extension of our model could incorporate human-driver interactions through behavior trees, specifically through more complex condition nodes. As long as the communication can be perceived by each agent, the pedestrian can evaluate the interaction and choose an appropriate action accordingly.
Adding to the set of available maneuvers and conditions can enhance the complexity and accuracy of the pedestrian's behavior. However, more maneuvers and conditions may also lead to a higher risk of incorrect or dangerous decisions. We must mediate the trade off between a manageable set of behaviors and their coverage and accuracy of real-world decisions, with evaluation on the available real-world data. Engineers must also be cautious of overfitting the behavior trees when designing critical scenarios not found in data. However, some scenario-based testing applications may require forcing a specific behavior to create a desired test scenario. In these cases, it is not so important to construct generalized behavior trees and it is sufficient to simply create the tree that generates the isolated behavior.
Since behavior trees allow for any number of parameters within their maneuver and condition nodes, it may be desirable to automate the process of tuning these parameters on real-world data. With separate sets of scenarios for tuning the trees and testing the model, the accuracy and robustness of the behavior trees can be improved. Using real-world data, the tuning process can also introduce the influence of implicit communication methods not previously incorporated into the model.
Another limitation of our model is the point-mass representation of pedestrians. The SP model abstracts characteristics from the agents, such as demographic information (age, gender, etc.) and body pose, which may be relevant to decisions for both drivers and pedestrians. For example, an elderly person will tend to move at different speeds and make different crossing decisions to an adult or a child in the same situation. We anticipate more sophisticated representations of pedestrians in future iterations of our model.
Finally, our model does not consider the uncertainty and noise of human motion. This is especially relevant in interactions between pedestrians and autonomous vehicles. Though not included in this iteration of the SP model, uncertainty can be injected into behavior trees. Noise can be used in condition nodes to express perception or judgement errors made by humans and in maneuver nodes to produce unexpected movements or decisions that may be difficult for an AV to predict.
\section{Conclusions} \label{sec:conclusions}
In this paper, we presented a novel hierarchical pedestrian behavior model that is capable of producing realistic trajectories through different traffic environments while following the rules of the road and making rational real-time decisions, but also allowing for misbehaviors. A multi-layer approach was applied to this problem that incorporates a high-level Behavior layer that determines an appropriate maneuver to be processed by the Maneuver layer, which informs the Motion Planner layer on how to adjust the low-level trajectory movements. The conjunctive use of behavior trees with an adapted Social Force Model ensures the model's agents are an accurate representation of real-world pedestrians. They were shown to make the same decisions when faced with multiple options and also display natural movements and interactions with other pedestrians and vehicles in the scene.
Our presented model offers benefit to the scenario-based testing of autonomous vehicles. Since pedestrian decisions and actions can be explicitly represented with behavior trees, engineers are able to inject desired behaviors into scenarios to test the AV's responses to critical situations. We provide an implementation of a set of basic maneuvers and conditions shown to sufficiently cover real-world behaviors. The flexibility and modularity of behavior trees allow for extensions of this list and configurations of trees that cover a wide range of conceivable behaviors.
We evaluated our model in terms of its ability to produce realistic low-level movements in two environments with different road structures and to replicate high-level decisions made by real-world pedestrians observed in a naturalistic data set. The results of our evaluation confirm that we present a viable pedestrian simulation model capable of producing realistic pedestrian decisions and movements.
| {'timestamp': '2022-06-06T02:15:24', 'yymm': '2206', 'arxiv_id': '2206.01601', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01601'} | arxiv |
\section{Introduction}
\noindent
Major Depressive Disorder (MDD) is among the world's most common mental health issues. According to an Organisation for Economic Co-operation and Development (OECD) report released in 2018, approximately 21 million people (4.5\%) were living with a depressive disorder across European Region (EU) countries in 2016~\cite{OECD_2018}. MDD also results in a high number of years lived with disability (YLD) in the European region, with the World Health Organisation estimating depression contributes 859 YLD per 100,000 population~\cite{WHO_2017}. With the ongoing Covid-19 pandemic, the global health situation has deteriorated, and people are even more susceptible to present symptoms related to MDD~\cite{santomauro2021global,han2020planning}. Since the beginning of the pandemic, the prevalence of MDD is estimated to have increased by 28\% ~\cite{santomauro2021global}.
Due to the prevalence and high associated socioeconomic costs associated with MDD, several initiatives have started to explore new ways to improve the management and treatment of MDD. \textit{Remote Assessment of Disease and Relapse in Major Depressive Disorder} (RADAR-MDD) is one such initiative~\cite{matcham2019remote}. It is a research project developed as part of Remote Assessment of Disease and Relapse – Central Nervous System (RADAR-CNS)\footnote{https://www.radar-cns.org/}, a major EU Innovative Medicines Initiative (IMI) research programme that investigates the use of remote measurement technologies (RMT) to monitor people with depression, epilepsy and multiple sclerosis in real-world settings. RADAR-MDD is a longitudinal cohort study examining the utility of multi-parametric RMT, including speech, physical activity, sleep, heart rate, location and social interaction signals, to measure changes in symptoms and predict relapse in people with MDD~\cite{matcham2019remote}. The main focus of the work presented in this paper is the 2-class automatic speech-based classification of MDD severity. RADAR-MDD is unique as an experimental speech corpus; it is the first speech-health dataset that contains speech in three languages that were collected with the same tool and protocol~\cite{cummins2015review, li2019speech, low2020automated}.
Speech is uniquely placed as a health signal, containing a complex combination of cognitive, neuromuscular and physiological information. It has a pyramidal structure of information levels; running from acoustic information at the lowest level, then onto prosodic, phonetic and finally conversational at the highest level~\cite{reynolds2003supersid,reynolds2003beyond}. The acoustic, phonetic and prosodic levels are of particular interest in speech-based depression detection. The acoustic and phonetic levels are directly influenced the physical actions of the respiratory and articulatory systems, and are affected by depression through related psychomotor effects. Clinically, prosodic abnormalities associated with depression are well documented \cite{cummins2015review}. Speech affected by depression is often subjectively characterised in clinical settings by decreased verbal activity, decreased utterance length, reduced speech rate and the presence of long pauses~\cite{jh2012verbal,hall1995nonverbal,sobin1997psychomotor}. There is a wide range of papers in the relevant literature that support these observations and strengthen the case for speech to be considered a valuable marker of depression. However, the complexity of speech and the natural variety of human voices make robust extraction of speech patterns associated with depression a highly non-trivial task.
A range of deep learning approaches have been explored in relation to speech-based depression detection, with Convolutional Neural Network (CNN) systems being highly prominent, e.\,g.\, \cite{10.1007/978-3-030-68790-8_1, rejaibi2019clinical, muzammel2020audvowelconsnet, zhao2019automatic}. While such approaches are popular, helping to overcome the lack of specificity associated with the use of generic multivariate speech representations, they can be highly complex, raising concerns of overfitting when training data is sparse. Moreover, without the addition of recurrent layers, which add further complexity, such systems do not explicitly model temporal changes in speech patterns, which have been shown to contain important information about depression~\cite{cummins2015review}. There has been less focus on Recurrent Neural Network (RNN) based approaches in speech-based depression detection despite their wider use in related tasks such as speech emotion recognition~\cite{yadav2021survey}. A small number of depression detection works have utilised RNNs within their speech models, e.\,g.\, \cite{rejaibi2022mfcc,zhao2020hybrid}. Of particular relevance for the work in this paper is the approach proposed in~\cite{rejaibi2022mfcc}. Key results from that work highlight the suitability of a Recurrent Neural Network (RNN) modelling approach using Mel Frequency Cepstral Coefficients (MFCCs) as input. Experiments on the Distress Analysis Interview Corpus (DIAC) corpus~\cite{ringeval2017avec,ringeval2019avec} showed a validation accuracy of 76.27\% when classifying low versus high levels of depression severity. It is not surprising that such an approach is well suited to depression detection: 1) MFCCs have shown to be suitable for capturing changes in speech motor control effects linked to depression~\cite{cummins2015analysis} and 2) recurrent layers would help model important temporal changes in the distribution of these features.
Inspired by the system presented in~\cite{rejaibi2022mfcc}, the MDD severity detection system proposed in this paper also uses MFCC's but in a \textit{sequence-to-sequence} classification model with local attention mechanisms. Given the widespread success of this paradigm in Natural Language Processing (NLP) tasks, it is not surprising that it has also been used in language-based depression models, e.\,g.\, \cite{harati2021speech,zogan2021depressionnet}. Despite strong results in related speech tasks [REFS], this approach is arguably under utilised in speech-based depression detection.
Adding to the novelty of the proposed approach is the proposed \textit{HARD-Training} paradigm. This is based on the concept of \textit{Curriculum Learning}, in which training instances are presented to a model in increasing levels of modelling difficulty~\cite{bengio2009curriculum}. Again, this approach has been used in related tasks such as emotion recognition; e.\,g.\, \cite{lotfian2019curriculum, ringeval2019avec}, but to the best of the authors' knowledge remains under explored within depression detection. During initial experimentation, we observed that when using a curriculum based training approach, only a sub-section of training samples, those \textit{nearest} the classification boundary was critical in boosting system performance. Presented results demonstrate that HARD-Training consistently improves system performance over training with all available samples. To the best of the authors' knowledge, this is the first time such as result has been presented in the speech-health literature. Summarising, the principal paper's contributions are as follows:
\begin{enumerate}
\item Introduce a new and extensive speech database (RADAR-MDD) for the analysis of MDD, containing three different languages (English, Spanish, Dutch), two speech elicitation tasks and an overall size of 59.12 effective hours. To the best of the authors' knowledge, this is one of the few speech corpus developed for the analysis of any kind of mental disorders of such a large size and with a multilingual perspective \cite{cummins2015review, li2019speech, low2020automated}.
\item Propose a novel approach (HARD-training) for the selection of training samples in the task of MDD binary classification. It is based on a curriculum learning paradigm, improving the generalisation capacity of the proposed classifier with an accuracy increment of 8.6\%.
\item Validate the efficacy of HARD-training for MDD severity classification across three languages, and separately for each gender.
\end{enumerate}
The paper structure is as follow: first, we describe the RADAR-MDD corpus, explaining the data collection procedure, study population and speech data. Then, the detection system is depicted, starting from the feature extraction process to a detailed description of the Sequence-to-Sequence classifier. Section \ref{curriculum} describes the basis of Curriculum learning methods, and what lead us to develop a new strategy referred in this paper as HARD-training. Section \ref{experiment and result} shows experimental settings and results, and Section \ref{conclusions} comprises our conclusions.
\section{RADAR-MDD Speech Corpus -- Study Population}
\noindent
RADAR-MDD was an observational cohort study with three recruitment sites: \textit{King’s College London} (KCL, London, United Kingdom); \textit{Amsterdam UMC, Vrije Universiteit} (VUmc; Amsterdam, The Netherlands). The full eligibility and exclusion criteria for RADAR-MDD are published in~\cite{matcham2019remote}. Briefly, the core eligibility criteria were having met the DSM-5 diagnostic criteria for non-psychotic MDD within the past two years prior to enrolment and having recurrent MDD (lifetime history of at least two episodes). Exclusion criteria included having a history of bipolar disorder, schizophrenia, MDD with psychotic features, or schizoaffective disorder; having dementia; and moderate or severe drug or alcohol use in the six months prior to enrolment. All participants were aged over 18, and were able to give informed consent.
Eligible participants were identified and recruited through several channels. This included existing research cohorts who had consented to be contacted for future research opportunities, primary and secondary mental health services, or advertisements placed on mental health charity websites, circulars or Twitter notices~\cite{matcham2019remote}. At the Amsterdam collection site, participants were also partially recruited through Hersenonderzoek.nl (\url{https://hersenonderzoek.nl}). All participants provided written consent and provided detailed baseline assessments as outlined in~\cite{matcham2019remote}.
\subsection{Service User Involvement}
\noindent
The RADAR-MDD protocol was co-developed with a patient advisory board (including service users) who shared their opinions on several user-facing aspects of the study including the choice and frequency of survey measures, the usability of the study app, participant facing documents, selection of optimal participation incentives, selection and deployment of wearable device as well as the data analysis plan. The speech task, and subsequent analysis has been discussed specifically with the patient advisory board.
\begin{table}[t] \centering
\caption{Extracts from The North Wind and the Sun used in the scripted task~\cite{international1999handbook}}
\label{tab:NWAS}
\begin{tabular}{|l|}
\hline
\begin{tabular}[c]{@{}l@{}} \textbf{Extract 1:} The North Wind and the Sun were disputing which was \\ the stronger, when a traveller came along wrapped in a warm cloak. \\ They agreed that the one who first succeeded in making the traveller \\ take his cloak off should be considered stronger than the other.\end{tabular} \\ \hline
\begin{tabular}[c]{@{}l@{}}\textbf{Extract 2:} Then the North Wind blew as hard as he could, but the \\ more he blew the more closely did the traveller fold his cloak around him; \\ and at last the North Wind gave up the attempt.\end{tabular} \\ \hline
\begin{tabular}[c]{@{}l@{}}\textbf{Extract 3:} Then the Sun shone out warmly, and immediately the \\ traveller took off his cloak. And so the North Wind was obliged to \\ confess that the Sun was the stronger of the two\end{tabular} \\ \hline
\end{tabular}
\end{table}
\subsection{Speech Collection in RADAR-MDD}
\noindent
Data were collected in RADAR-MDD using three main methods. First, all primary and secondary clincal outcome measures were collected every three months via \textit{Research Electronic Data Capture} (REDCap) software~\cite{harris2019redcap}. Participants also had to install two purpose-built apps to allow remote data collection. The first app enabled active RMT (aRMT) data collection, in which users provided questionnaire and speech data through active user actions with the app. The second app enabled passive RMT (pRMT) data collection in which background signals such as Bluetooth and location data as well as activity and cardiovascular parameters from the wrist-worn device were collected with minimal user interactions. Both apps are part of the the open-source, RADAR-base m-Health data collection system~\cite{ranjan2019radar}.
Speech data collection in RADAR-MDD started in London in August 2019, and in December 2019 at the other centres. Study participants were asked to complete two speech-recording tasks every two weeks. First, the app produced notifications each time speech recordings were scheduled. Before starting each recording task, participants were reminded, via on screen instructions, to find a quiet place to complete the recordings and to complete the recordings in their normal voice. The first recording was a \textit{scripted speech task} (ST) , in which the participants read aloud an extract from Aesop’s fable, The North Wind and the Sun~\cite{international1999handbook}. To help minimise potential confounding effects due to regular repetition of the text, the fable was split into three parts (Table \ref{tab:NWAS}). The three extracts were rotated in order such that participants recorded a different extract each time the task was scheduled. The second task was a \textit{free-response speech activity} (FR) in which participants were asked to speak about what they were looking forward to in the following seven days~\cite{mundt2007voice}. Participants were able to re-record their extracts should they wish, and were also given the choice to skip the tasks. In addition to recording their speech, participants also completed a \textit{8-item Patient Health Questionnaire} (PHQ-8;~\cite{kroenke2009phq}) to asses their level of depression. This was administered once every two weeks throughout the duration of follow-up.
\subsection{Speech Data Overview}
\noindent
Once recorded, the speech data were encrypted and sent to a secure server. When on the server the collected data were separated into the respective tasks and decrypted into 16 kHz \textit{Waveform Audio File Format} (WAV) files. All files that either were under five seconds in length were not considered in our analysis. The final number of participants and audio files considered in our analysis are presented in Table \ref{tab:corpus}. There was a higher proportion of female than male participants. Unsurprisingly, as KCL had the largest cohort and had been collecting speech for the longest, the largest amount of speech data was collected in the UK.
\begin{table}[t]
\caption{Description of sociodemographic data and audio file distribution in the scripted (Scrpt) and unscripted (Uns) RADAR-MDD speech files used in this paper}
\label{tab:corpus}
\begin{tabular}{|l|cc|cc|cc|}
\hline
\multirow{3}{*}{} & \multicolumn{2}{c|}{London-KCL} & \multicolumn{2}{c|}{Amsterdam-VUmc} & \multicolumn{2}{c|}{Barcelona-CIBER} \\
& \multicolumn{2}{c|}{(English)} & \multicolumn{2}{c|}{(Dutch)} & \multicolumn{2}{c|}{(Spanish)} \\
& Scrpt & Uns & Scrpt & Uns & Scrpt & Uns \\ \hline
Participants & 271 & 258 & 107 & 101 & 108 & 104 \\
Gender M/F & 59/212 & 56/202 & 25/82 & 22/79 & 33/75 & 22/71 \\
Mean Age & \multicolumn{2}{c|}{45($\pm$16)} & \multicolumn{2}{c|}{42($\pm$17)} & \multicolumn{2}{c|}{54($\pm$10)} \\
No. Files & 4,504 & 3,500 & 1,768 & 1,192 & 1,167 & 916 \\
Size (hours) & 17.62 & 18.92 & 6.89 & 5.86 & 5.52 & 4.42 \\ \hline
\end{tabular}
\end{table}
During the scripted task, all participants were invited to read the same fragments of a text in the language of the country they were enrolled in. As a result, the standard deviation of audio recordings length was much less in this task than in the unscripted one. Combining this observation with the expected acoustic uniformity in the scripted data, we can consider the scripted corpus as a controlled experimental framework~\cite{langley1988machine}. There are two main sources of variation: speech style and linguistic content~\cite{reynolds2003supersid,reynolds2003beyond}. Speech style varies in both tasks, and linguistic content only varies in the unscripted task. Given this, we expect that the effects of depression will be the more dominant source of variation in the scripted data when compared to the free response speech.
The distribution of the audio recording durations in the RADAR-MDD speech corpus is given in Figure \ref{fig:duration}.
The average recording length is 14.5s and 19.0s for the scripted and unscripted tasks respectively.
\begin{figure}[t]
\begin{center}
\includegraphics[width=0.7\linewidth]{figures/time.png}
\caption{Value distribution of audio recording duration of the RADAR-MDD corpus (KCL, VUmc, CIBER) on the scripted and unscripted tasks}
\label{fig:duration}
\end{center}
\end{figure}
We assigned a level of depression severity to each file using the concurrently collected PHQ-8 scores. We divided the speech files into two classes: (i) mild and moderate depression severity (PHQ-8 $<$ 10), herein referred to as the \textit{low} class; and (ii) moderately severe and severe depression (PHQ-8 $\geq$ 10), herein referred to as the \textit{high} class.
Visualizations of the PHQ-8 distribution are given in Figure \ref{fig:phq8-distribution}
Importantly when considering the interpretation of our results on a per-country basis, there are no notable differences related to the distribution of scores between the different tasks when comparing within each collection site.
In the next section, we move on to describing our Sequence-to-Sequence system
for the automatic speech-based two-class detection of MDD severity.
\begin{figure}[t]
\begin{center}
\includegraphics[width=0.35\linewidth]{figures/phq8/histogram_KCL_scripted.png}
\includegraphics[width=0.35\linewidth]{figures/phq8/histogram_KCL_unscripted.png}
\\[\smallskipamount]
\includegraphics[width=0.35\linewidth]{figures/phq8/histogram_VUmc_scripted.png}
\includegraphics[width=0.35\linewidth]{figures/phq8/histogram_VUmc_unscripted.png}
\\[\smallskipamount]
\includegraphics[width=0.35\linewidth]{figures/phq8/histogram_CIBER_scripted.png}
\includegraphics[width=0.35\linewidth]{figures/phq8/histogram_CIBER_unscripted.png}
\caption{Comparison across the 3 RADAR-MDD collection sites of the PHQ-8 scores distributions collected concurrently with the speech files}
\end{center}
\label{fig:phq8-distribution}
\end{figure}
\section{Sequence-to-Sequence system for speech-based MDD detection}
\noindent
Speech is a useful and informative remote measurement technologies (RMT) signal, which offers additional advantages over other RMT signals. Most notably, it is rich signal that can be collected cheaply and non-invasively using a smartphone. Moreover, we only require a relatively small amount of data (e.\,g.\, a few sentences or phrases) to capture depression information~\cite{6639130}. However, robustly classifying this information in a machine learning pipeline is non-trivial \cite{cummins2018speech}. This section explains the algorithm we propose for this task.
\subsection{Feature Extraction}
\noindent
Our severity detection system has two main stages: \textit{feature extraction} and \textit{classification}. Regarding feature extraction, we converted the speech data into log Mel-filterbank energy, referred to herein as Mel-Spectra, features. This is a popular, yet highly effectively speech feature based on the non-linear human ear perception of sound~\cite{tychtl1999speech,1172250}. The suitability of these features in combination with recurrent neural networks has been established over a range of different speech processing tasks [REFs, see if there is a depression one]. Mel Spectra features captures changes at the acoustic information level of speech; however, when viewed as a sequence, they are also informative of the prosodic and phonetic levels~\cite{ahmad2015unique}. They are a \textit{low-level} speech descriptor, extracted from very small windows (typically 25 ms in length) of speech to ensure the captured signal has a quasi-periodic structure. Given an audio segment to be processed via short-term sliding windows, the key steps in Mel-Spectra extraction are as follows (Figure \ref{fig:mfcc}):
\begin{enumerate}
\item Split the speech signal into overlapping short-time frames
\item Apply the Fast Fourier Transformation (FFT) on each frame
\item Filtering the FFT results using a Mel filterbank
\item Compute the log energy of filterbank output
\end{enumerate}
\begin{figure}[t]
\includegraphics[width=\linewidth]{figures/mfcc.png}
\caption{Mel features extraction process into blocks.}
\label{fig:mfcc}
\end{figure}
\subsection{Sequence to Sequence modelling}
\noindent
The classification step of our system is achieved by a sequence-to-sequence model (Figure \ref{fig:general_}) with a local attention mechanism~\cite{chiu2018state, niu2021review}. The selection of this model is to enable the longer-term sequential processing of the mel-spectrum features~\cite{hochreiter1997long,mozer1992induction}.
Our approach is built on Recurrent Neural Network (RNN) architectures which have been shown to be effective in the processing of sequential data \cite{10.1162/neco_a_01199}. RNNs ability to track and store dependencies throughout a sequence has been key in tasks such as Stock Price Pattern Recognition \cite{kamijo1990stock,samarawickrama2017recurrent} and health care \cite{luo2017recurrent}. The use of RNN's is further justified given that depression has been shown to alter temporal properties of speech; e.\,g.\, \cite{trevino2011phonologically, yamamoto2020using}.
\begin{figure}[t]
\includegraphics[width=\linewidth]{figures/general_system_dep.png}
\caption{Proposed MDD detection process from speech}
\label{fig:general_}
\end{figure}
Sequence-to-Sequence (Seq2Seq) models~\cite{chiu2018state} are a powerful extension of the RNN architecture. They have been successfully applied in a range of tasks,
including tasks related to depression prediction, such as speech-based emotion recognition~\cite{8470325, lin2021chunk, zhao2021combining}. Seq2Seq is a modelling paradigm that uses two sets of RNNs to convert one sequence of items in one domain into a sequence in another domain~\cite{sutskever2014sequence}. The first RNN network is known as the encoder and the second one as decoder. The encoder learns to processes each item of an input sequence and converts this information into a fixed (static) representation vector know as the context vector. The decoder then learns to converts this static representation into new sequence.
\begin{figure}[t]
\includegraphics[width=\linewidth]{figures/seq2seq.png}
\caption{Sequence to sequence model architecture with attention mechanism}
\label{fig:sys}
\end{figure}
The core component of the encoder and decoder set-up is the RNN blocks. In our work, they are realised by a Gated Recurrent Unit (GRU) layers (Fig. \ref{fig:sys}). In the input, a Batch Normalization layer is applied for decreasing the training time of the model. Linear transformations is also applied for guarantee matrix compatibility between some consecutive blocks. In the decoder, we added a local attention mechanism in order to consider information relevance when processing the output.
As we are actually performing a sequence-to-label task, we augment the output of the decoder with a feed-forward layer to performance binary classification.
During our initial system development phase (results not given), we observed that
the selection of training samples had a strong influence on the system performance.
Based on these observations and subsequent tests, we
developed a new approach, \textit{HARD-Training}. This paradigm is inspired by
curriculum learning~\cite{lotfian2019curriculum,bengio2009curriculum}, explained in the next subsection
\section{Curriculum learning}\label{curriculum}
\noindent
Curriculum learning is a method design to assist in maximising efficacy when training \textit{Deep Neural Networks} (DNNs)~\cite{bengio2009curriculum}. It is based on how we as humans efficiently learn.
We learn easy tasks that gradually became more complicated, incorporating new and more complex abstract concepts. By choosing what and when we learn, we can increase the speed at what learning can occur. The goal is to start small, learn easier aspects of the task or easier sub-tasks, and then gradually increase the difficulty level.
In
many machine learning application, the loss function follows a non-convex criterion, having several local minimums \cite{jain2017non}. Consequently, we have to find the global minimum of a non-convex training criterion. Curriculum learning has been found beneficial in those cases, being a version of a continuation method optimisation strategy that deals with minimising non-convex criteria~\cite{bengio2009curriculum, NIPS2014_c60d060b}. The key idea of continuation methods is to optimise a smooth objective and then gradually consider less smoothing, with the intuition that the smooth version of the problem reveals the global picture. This training approach has been found to increase the training speed and achieve a better generalisation capacity~\cite{bengio2009curriculum}. This generalisation benefit infers that the curriculum learning concept operates similar to a reguliser~\cite{li2021curriculum}.
Using a curriculum learning method for training, less complex samples feed the DNN with a high weight. In the case of the ambiguous samples, these feed the DNN with a low weight. This weight distribution helps to control the influence of the samples during training. However, applying such an \textit{a priori} assumes that non-ambiguous samples are more informative when updating the gradient, this is not always the case~\cite{NIPS2017_2f37d101}. Underexposure to ambiguous samples could even be detrimental when needing to minimise the variance of gradient updates~\cite{NIPS2017_2f37d101}. In this work, we introduce an alternate strategy to curriculum learning, \textbf{HARD-Training}, which is introduced in the next section.
\subsection{HARD-Training methodology for binary classification.}
\noindent
The method we proposed in this subsection is a variation of the Curriculum Learning approach explained previously. We keep the same key idea where \textit{ambiguous samples for humans are ambiguous for computers as well}. However, we take an opposite view of what samples are more relevant for the training of a binary classifier.
We assume that by focusing purely on ambiguous samples
will improve the generalization capacity of the network
over training with all available samples.
This improvement in generalization capacity of the model is translated into a better test performance.
We demonstrate the advantages of HARD-Training through a binary MDD severity detection task, i.\,e.\, the low and high classes.
During training, the goal our detection system is to find the optimal separation hyperplane that classifies the samples as high (moderately severe, and severe MDD) or low (mild and moderate MDD). The optimisation process is defined by a non-convex criterion as well. As a result, the decision boundary depicts a non-linear function. Referring ambiguous samples as hard, and non-ambiguous samples as easy, we hypothesise that hard samples are
those closest to the optimal separation hyperplane (Fig. \ref{fig:hard_training}); it is this proximity that makes them difficult to be classify correctly. On the other side, easy samples are those far from the separation hyperplane.
\begin{figure}[t]
\includegraphics[width=\linewidth]{figures/hard_training.png}
\caption{Illustration of hard and easy samples location in the binary classification task}
\label{fig:hard_training}
\end{figure}
Based on this assumption, we propose the following concept:
\begin{itemize}
\item During the training of a binary classifier, the use of hard (ambiguous) samples only is suitable for learning the optimal separation hyperplane, while easy samples would not lead to an effective approximation. The separation hyperplane defined by easy samples is more likely to follow a linear function due to the greater distance between them. This is not an appropriate function to guarantee the generalisation capacity of the classifier, making ineffective the classification of hard samples. Hard samples are closer to the optimal decision boundary because of their condition as ambiguous. Therefore, optimising the model using only hard samples help us to classify easy samples as well, and with a high accuracy. We conclude that, in training, easy samples can only make noisier the finding of the classifier's decision boundary.
\end{itemize}
The next step is to define what samples are ambiguous or not to the model. For our classification task, we use the PHQ-8 scores to define current symptom severity. A person meets the PHQ-8 criteria for having high depression symptom severity by obtaining a score greater or equal to 10. Moreover, a score less than 5 indicates low/no current depression symptoms, while a score greater than 15 indicates severe depression symptoms. Given this, we assume there is greater ambiguity in the presentation of depression symptoms closer to the cut of score of 10, as it is depicted in Figure \ref{fig:ambiguous}
\begin{figure}[h!]
\begin{center}
\includegraphics[width=8cm,height=8cm]{figures/depression_scale.jpg}
\caption{Depression severity levels according to PHQ-8 scale. Illustration of regions with ambiguous symptoms}
\label{fig:ambiguous}
\end{center}
\end{figure}
We undertook a simple experiment to validate our easy-hard partition assumption. In it, we trained a smaller version of our Seq2Seq model, using 32
as the hidden size of the GRU layers, from the decoder and encoder. Firstly, we trained the model, randomly picking 128 sequences from the group of easy samples (e.\,g.\, PHQ8 < 5 and PHQ8 > 15). Secondly, we initialized the model again and picked another 128 training sequences but from the group of hard samples. Then, we compared the training loss of the model for the easy and hard group respectively. On both cases, the total of training epochs was 500. If our assumption is valid, the training loss should be lower when easy samples are used; this experiment was repeated several times. The
Figure \ref{fig:easy-hard-epochs-comparison} shows a sample of what has been the behaviour of the training loss on those experiments.
\begin{figure}[h!]
\center
\includegraphics[width=0.48\linewidth]{figures/history_comparison_loss.png}
\caption{Comparison of the Seq2Seq training loss in front of easy and hard samples. The blue line represents the training loss of hard samples. The yellow line is from easy samples}
\label{fig:easy-hard-epochs-comparison}
\end{figure}
Initially, both the easy and hard training loss are similar, but after approximately 200 epochs the difference between them
becomes clear. It is easy to visualise how
difficult it was for the model to assimilate the patterns that came from the hard samples. This was the case most of the time we performed this experiment, which validates our assumption of the intervals defined for easy and hard samples. Nevertheless, there were a few cases were the model was able to learn from easy and hard samples to a similar speed. We attribute this seldom behavior to the high variability of speech features.
\section{Experimental settings and results} \label{experiment and result}
\noindent
Our system utilises Mel-spectrum features and a Seq2Seq model as classifier. We extracted 40 dimensional mel-spectrum features using a window of 0.25 ms with a hop of 10 ms via the Librosa Python package\cite{mcfee2015librosa}. These features were then split into sequence of 500 vectors, representing 5 secs long. The selection of this temporal length was based on our previous experience working on the DAIC-WOZ database, where a 5 seconds length appeared to be the optimal sequence length. The Seq2Seq model is augmented by a Batch Normalisation layer in the input, as well as unidirectional GRU layers in the encoder and decoder, each with a hidden layer size of 128. We use a local attention mechanism with a window size of 1.5 secs. The total of trainable parameters of the model was 204115. The batch size was set to 128, with 100 epochs of training. The Adam algorithm \cite{kingma2017adam} was taken as optimiser using Binary Cross Entropy as loss function. One cycle learning rate policy \cite{DBLP:journals/corr/abs-1708-07120} was done to fast up the convergence time of the model. To avoid exploding gradient, Gradient clipping method \cite{pascanu2013difficulty} was applied on the last layer of the model.
A 10-Fold speaker-stratified cross-validation strategy was used for the system test on the London and Amsterdam corpus respectively. In the case of Barcelona corpus, a 5-Folds were used because of the smaller total recording length of this corpus. When performing \textit{HARD-Training}, we removed the easy samples from the training group; however \emph{both} easy and hard samples were present in the test fold.
Figure \ref{fig:easy-hard-comparison} compares the results using the classic and HARD-Training approaches. We refer as classic approach to the training process where is not applied a curriculum learning strategy; therefore, every sample (hard and easy) feeds the model during training. The HARD-Training method consistently outperforms the classic approach for every collection place. The biggest difference of performance between them is around 10\% of accuracy and the smallest one is around 5\%. This means that despite of the training loss is higher for the HARD method in the same amount of epochs, it achieve a better generalisation capacity during test. This was the basis of our hypothesis to follow this training strategy. In addition, we can conclude that the benefits of HARD-Training are steady through different languages.
\begin{figure}[h!]
\includegraphics[width=0.48\linewidth]{figures/accuracy_scripted.png} \hfill
\includegraphics[width=0.48\linewidth]{figures/accuracy_unscripted.png}
\caption{Comparison of the Seq2Seq performance when using classic and HARD-Training methods on the scripted and unscripted tasks}
\label{fig:easy-hard-comparison}
\end{figure}
The Table \ref{tab:results} depicts the final results of the Seq2Seq model using the proposed \textit{HARD-Training} method. The results are quite stables with an accuracy from 75.12\% to 81.70 throughout the three collection places. Area Under Curve (AUC) values are in most of the cases over 80\%, which means a good class separation ability through different decision thresholds. The lowest performance was in the unscripted task of the Barcelona corpus, which is at the same time the smallest corpus. The standard deviation of the accuracy is higher for the unscripted task than for the scripted one in every collection place. We expected this behaviour because of the open setting condition of the unscripted task.
\begin{table}[t] \centering
\caption{Results of the Seq2Seq model using The HARD-Training method}
\begin{tabular}{ c|cccc }
\hline
\textbf{Collection place (Language)}& \textbf{Task} & \textbf{Accuracy} & \textbf{AUC} \\ \hline
\multirow{2}{*}{London-KCL (English)} & scripted & 76.76 +- 1.28 & 81.58 +- 2.34 \\
& unscripted & 78.63 +- 3.71 & 80.67 +- 4.22\\ \hline
\multirow{2}{*}{Amsterdam-VUmc (Dutch)} & scripted & 81.70 +- 4.68 & 83.91 +- 6.16\\
& unscripted & 77.33 +- 6.39 & 77.94 +- 9.15\\ \hline
\multirow{2}{*}{Barcelona-CIBER (Spanish)} & scripted & 79.15 +- 2.31 & 81.97 +- 3.84 \\
& unscripted & 75.12 +- 4.28 & 73.39 +- 4.61\\ \hline
\end{tabular}
\label{tab:results}
\end{table}
Finally, to contribute to wider discussion regarding bias and fairness in Artificial Intelligence and machine learning research, we conduct a gender independent analysis of our results. We split the results from Table \ref{tab:results} into male/female participants, as it is showed on Figure \ref{fig:male-female-accuracy}\footnote{The system was trained on both, female and male. Then, its performance per gender was separately evaluated}. As a general trend, the system performs stronger on male participants from KCL and VUmc, however there is not a noticeable drop-off in performance for the female participants when compared to the gender independent results for these sites. This stronger performance for males is surprising given the gender imbalance of the corpus and will investigate further in future research. For the CIBER site, the system performs stronger for females, which is more in line with expectation based purely on weighted gender distributions.
\begin{figure}[t]
\includegraphics[width=0.48\linewidth]{figures/gender_accuracy_scripted.jpg} \hfill
\includegraphics[width=0.48\linewidth]{figures/gender_accuracy_unscripted.jpg}
\caption{Comparison of the Seq2Seq accuracy for male/female participants}
\label{fig:male-female-accuracy}
\end{figure}
\
\section{Conclusions} \label{conclusions}
\noindent
The Remote Assessment of Disease and Relapse – Major Depressive Disorder (RADAR-MDD) speech corpus is a new longitudinal dataset containing approximately 60 hours of speech collected from almost 500 participants over an 18 month period. Matching the three collection sites, London, Amsterdam and Barcelona, the data collected is in English, Dutch and Spanish. To the best of the authors' knowledge, this dataset is unique in ts longitudinal duration and the number of languages recorded. The corpus is comprised of both a scripted, and a free-speech task.
Utilising this dataset, we designed and implemented a Sequence-to-Sequence model with local attention mechanism for a 2-class depression severity detection task. The novel aspect of this model was the proposed \textit{HARD-Training} paradigm. HARD-Training is based on a Curriculum Learning approach, however, it utilises a different selection criteria in relation to which samples are more relevant for the model training. Consistent results were demonstrated across the three language groups and two different speech tasks with the RADAR-MDD speech corpora. On average, hard training improved the model's accuracy by 8.6 \% and achieved an Area Under Curve over 80\% in almost every case tested. Finally, a gender-independent analysis was carried out to validate the Sequence-to-Sequence performance according to the gender of the participant. Results were strong for female and male participant's samples, but the best results were mostly achieved processing samples from male participants. Future work efforts will focus on verifying the benefits of HARD-Training in other scenarios, namely different speech-health tasks and different signals from remote measurement technologies.
\section{Acknowledgments}
\noindent
This work has received financial support from Axudas propias para a mobilidade de Persoal Investigador da Unvirsidade de Vigo 2021, the Xunta de Galicia (Centro singular de investigación de Galicia accreditation 2019-2022), Conseller\'{i}a de Cultura (Educaci\'{o}n e Ordenaci\'{o}n Universitaria; axudas para a consolidaci\'{o}n e estruturación de unidades de investigación competitivas do Sistema Universitario de Galicia -ED431B 2021/24), and the European Union (European Regional Development Fund - ERDF).
Funding The RADAR-CNS project has received funding from the Innovative Medicines Initiative 2 Joint Undertaking under grant agreement No 115902. This Joint Undertaking receives support from the European Union’s Horizon 2020 research and innovation programme and EFPIA (www.imi.europa.eu). This communication reflects the views of the RADAR-CNS consortium and neither IMI nor the European Union and EFPIA are liable for any use that may be made of the information contained herein. The funding body have not been involved in the design of the study, the collection or analysis of data, or the interpretation of data.
Participant recruitment in Amsterdam was partially accomplished through Hersenonderzoek.nl, a Dutch online registry that facilitates participant recruitment for neuroscience studies (https://hersenonderzoek.nl/). Hersenonderzoek.nl is funded by ZonMw-Memorabel (project no 73305095003), a project in the context of the Dutch Deltaplan Dementie, Gieskes-Strijbis Foundation, the Alzheimer's Society in the Netherlands and Brain Foundation Netherlands
Participants in Spain were recruited through the following institutions: Parc Sanitari Sant Joan de Déu network of mental health services (Barcelona); Institut Català de la Salut primary care services (Barcelona); Institut Pere Mata-Mental Health Care (Tarrassa); Hospital Clínico San Carlos (Madrid).
This paper represents independent research part funded by the National Institute for Health Research (NIHR) Maudsley Biomedical Research Centre at South London and Maudsley NHS Foundation Trust and King’s College London. The views expressed are those of the author(s) and not necessarily those of the NHS, the NIHR or the Department of Health and Social Care.
We thank all the members of the RADAR-CNS patient advisory board for their contribution to the device selection procedures, and their invaluable advice throughout the study protocol design. This research was reviewed by a team with experience of mental health problems and their carers who have been specially trained to advise on research proposals and documentation through the Feasibility and Acceptability Support Team for Researchers (FAST-R): a free, confidential service in England provided by the National Institute for Health Research Maudsley Biomedical Research Centre via King’s College London and South London and Maudsley NHS Foundation Trust.
We thank all GLAD Study volunteers for their participation, and gratefully acknowledge the NIHR BioResource, NIHR BioResource centres, NHS Trusts and staff for their contribution. We also acknowledge NIHR BRC, King's College London, South London and Maudsley NHS Trust and King's Health Partners. We thank the National Institute for Health Research, NHS Blood and Transplant, and Health Data Research UK as part of the Digital Innovation Hub Programme.
We thank our colleagues both within the RADAR-CNS consortium and across all involved institutions for their contribution to the development of this protocol. We thank all the members of the RADAR-CNS patient advisory board for their contribution to the device selection procedures, and their invaluable advice throughout the study protocol design. In particular we thank Grace Lavelle, Daniel Leightley, Maria Teresa Pe\~{n}arrubia-Mar\'{i}a, Gemma Riquelme Acid, Katie M. White, Alina Ivan, Carolin Oetzmann, Sara Simblett, Yatharth Ranjan, Zulqarnain Rashid, Amos A. Folarin, Josep Maria Haro, Srinivasan Vairavan, Til Wykes, Richard Dobson, Vaibhav A. Narayan and Matthew Hotopf.
| {'timestamp': '2022-06-06T02:13:13', 'yymm': '2206', 'arxiv_id': '2206.01542', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01542'} | arxiv |
\section{Introduction}
Ownership can be described, in very broad terms, as the set of exclusive rights over property, usually classified as tangible (e.g., real state, chattel) or intangible (e.g., intellectual property, digital objects).
Such rights are universally recognized as fundamental~\cite{akkermans2018comparative}, yet the very concept of ownership evolves over time, according to the mores of society and technological innovations of the place and moment. Ownership has in fact been intrinsically linked to information technology (in its broadest sense) from the very beginning of history, as attested by the small clay objects inscribed with proto-cuneiform dating back to 8000 BCE found in the Near East ---called \emph{tokens}--- used to keep track of the number of animals owned~\cite[p. 22]{daniels1996world}. Millennia later, the printing press, another technological writing milestone, greatly eased the massive copying of books and also gave way to a new form of piracy of intellectual property~\cite[\S1]{johns2010piracy}. More recently, digital technology, which allows perfect copies of digital objects at near-zero cost, brought into question aspects of goods once considered to be central~\cite{liu2000owning}, such as rivalry (impossible simultaneous use) and scarcity (limited availability). Incidentally, such «fundamental shift from tactile to digital, physical to code, and hard to soft media» in ownership is also reflected by hypertext within the history of information technology, as described by \citeauthor{landow2006hypertext}~\cite[pp. 29--41]{landow2006hypertext}.
Moreover, present-day digital ecosystems ---with most based on hypermedia--- have heavily influenced our ownership experience. For instance, whereas traditional market models are based on ownership, the \emph{sharing economy} is based on using and sharing products among each other, and is driven by consumer behavior (preference for convenience, low prices, sustainability), social networks and electronic markets, and mobile devices and electronic services~\cite{puschmann2016sharing}. Another example is the push towards a \emph{subscription model} of digital goods and services, such as news, music, video, videogames, and apps. Nonetheless, not all changes in digital ownership are welcome, and much debate is being made regarding the rights of buyers, creators, and distributors of digital objects, and the loss of expected privileges associated with ownership~\cite{liu2000owning}. Further, the increasing practice of license-only digital objects and the abuse of digital rights management (DRM) have given rise to harsh criticism against this “end of ownership” in the digital economy~\cite{perzanowski2016end}.
\section{A new kind of digital ownership}
Discontent with diminishing digital property rights led many tech enthusiasts to seek alternative approaches. Arguably, one of the most interesting is the use of a non-fungible token (NFT) to certify the authenticity and ownership of tangible or intangible assets. An NFT is a unique identifier recorded using distributed ledger technology (DLT), which is based on decentralized immutable lists of records spread over a peer-to-peer network without the need of a trusted authority, with the most famous example being blockchain~\cite{swartz2017blockchain}. NFTs are a specific form of \emph{smart contracts}, versatile transaction protocols that automatically execute, control, and document an agreement without the need of a trusted intermediator~\cite{antonopoulos2018mastering}. Amusingly enough, NFTs seem to carry on the ancient practice of using \emph{tokens} to keep track of property, only this time via digital cryptographic hashes instead of inscriptions on clay.
In the last couple of years, there has been a surge in public interest on NFTs due to the high-profile sale of certain digital assets~\cite{trujillo2022surge}, such as the sale for US\$5.4M of the initial implementation source code of the World Wide Web by Tim-Berners Lee.\footnote{\url{https://www.bbc.com/news/technology-57666335}} Users and buyers of NFTs are allured by the promise of ownership, traceability, and financial gain~\cite{mackenzie2021nfts}. And the high figures involved in much publicized sales have sparked a frenzy in the development of NFTs applications and ecosystems in different sectors, such as collectibles, sports, visual arts, and video games~\cite{nadini2021mapping}. Even “traditional” social media have begun integrating NFTs. Twitter now can display special NFT profile pictures with a hexagonal shape present in the Ethereum blockchain (the most common DLT for NFTs), and Reddit has established a collaboration with OpenSea (the largest NFT marketplace) to sell unique animated avatars, called CryptoSnoos. Many more ideas are emerging around NFTs and DLT beyond finance, such as decentralized autonomous organizations (DAOs), a novel manner to codify and automatically manage governance via smart contracts without a central leadership~\cite{hassan2021decentralized}. Hence, due to the aforementioned commonalities with respect to information technology, I believe that using an hypertext approach to augment our capabilities on digital ownership based on DLT is a logical yet untapped opportunity.
\section{Envisioning hyperownership}
Bitcoin, the first successful decentralized virtual currency, gave way to the idea of using DLT as a means to register property ownership.
In particular, \citeauthor{fairfield2014bitproperty}~\cite{fairfield2014bitproperty} posited that property could be seen as a set of information describing who may do what, when, and with which resource: «property is the law of lists and ledgers». In this perspective, property does not consist in the \emph{thing} itself, but in the packaging, tracking and transmission of data regarding ownership via information systems; thus, a property system has two key actions: \emph{store} and \emph{communicate} ownership information.
However, DLT has mainly focused on improving the latter action from the point of view of machines, neglecting the human element. For example, in a survey of DLT applications from the perspective of human-computer interaction (HCI), \citeauthor{elsden2018making} state that these «are currently overwhelmingly driven by a mix of engineering, investment and crypto-anarchist visions», and they express the need for more research on the human challenges of DLT, such as design for trust, algorithmic governance, influence on societal and individual values, ease of use for end users, and implications of publicly sharing one's property data~\cite{elsden2018making}. \citeauthor{glomann2019improving} further confirm the need of a human-centered approach given crucial DLT issues: high onboarding learnability; lack of design considerations for usability, efficiency, and accessibility; and design challenges in decentralized applications~\cite{glomann2019improving}.
In this respect, I believe there is an unexploited opportunity in using a hypertext approach to tackle these issues, for as hypertext has been historically touted as a means to augment human intellect~\cite{van2019reflections}, by allowing a person to approach complex problems, to fulfill their comprehension needs, and to derive solutions to problems~\cite{engelbart1962augmenting}. To seize such an opportunity, I think the view posited by \citeauthor{atzenbeck2019hypertext}~\cite{atzenbeck2019hypertext} of a «hypertext method of inquiry, as way of viewing arbitrary systems», is particularly apt. In this view, hypertext shifts its focus from a particular set of technologies and techniques, to the more general explicit association of information. \emph{Hyperownership} is thus a concept to augment human capabilities on digital ownership, by synthesizing these two ideas: property is the law of lists and ledgers, and hypertext is a method of inquiry of arbitrary systems.
Based on their form of structure from a hypertext perspective~\cite{atzenbeck2019hypertext}, NFTs are a first class structure, as by definition DLT records explicit relationships between resources and allows the association of metadata with a link for a given transaction. On top of these records, we could use a new representation to exploit the explicit ownership associations in new ways. For instance, we could use \emph{temporal bipartite graphs} to represent the evolving relationships between the two main kinds of DLT entities: tokens (property) and their respective account (owner). Compared to their static and unipartite counterparts, temporal bipartite graphs model better the complexity and dynamism of real-world problems~\cite{chen2021efficiently}. In this \emph{owner--property} temporal bipartite graph, the state of ownership in a given moment could be computed from a derived static graph, i.e., a \emph{snapshot}, in which each token is associated with at most one owner and each owner is associated with zero or more tokens. A second ownership-based useful representation could be a \emph{property--usage} temporal bipartite graph, in which we model distinct usages of property tokens in a given context (e.g., profile picture in social media, an audio or video reproduction). In the snapshots of this graph, each property could be associated to zero or more usages. Finally, a third temporal bipartite graph, \emph{owner--usage} could be derived from the first two. Further styling could be done through automatic context-aware hypermedia sculpting to remove irrelevant links based on context or manual calligraphic linking by users~\cite{hargood2016patterns}.
\begin{figure*}
\includegraphics{diagram.pdf}
\caption{Conceptual diagram of applying a hypermedia approach to blockchain so as to inquiry on the ownership of digital objects, in which there is an increasing shift in focus from the machine to the human aspects of the system.}
\label{fig:diagram}
\Description{The figure is divided into four sections. In the first there is a blockchain containing a series of smart contracts. In the second, these are converted to temporal bipartite graphs. In the third, further customization is illustrated via calligraphic and sculpture hypermedia styles to respectively increase or reduce existing links. In the final section, an example of ownership inquiry is shown, in which the associative trail between a usage of a given asset and its monetary cost, passing through the related seller, owner, and cryptocurrency exchange.}
\end{figure*}
With such an approach, illustrated in Fig.~\ref{fig:diagram}, we could augment human capabilities to inquiry on ownership by: using novel HCI techniques to visualize and interact with digital property; leveraging recent advances in big graph mining~\cite{aridhi2016big} to discover interesting phenomena and gain insight into the dynamics of ownership; integrating existing knowledge graphs~\cite{ji2021survey} to enrich the semantics of the ownership network and viceversa; creating novel non-linear narratives regarding the history of digital objects and the preferences of owner accounts; easing the exploration and recommendation of potentially interesting digital objects to buy, use, or admire; and much more.
\section{Risks and challenges}
Due to the uncertainties surrounding NFTs, there are significant risks in undertaking the realization of hyperownership. For instance, despite the promise and eagerness of improved usage and financial control and financial by digital content creators, many are divided on the merits of NFTs~\cite{kugler2021non}.
Above all, crucial issues remain unanswered regarding the ownership of NFTs and the objects that they represent~\cite{lydiate2021crypto}, such as a likely economic bubble, legal recognition, and the currently rising fraud and stealing in the community; as simply put by \citeauthor{joselit2021nfts}~\cite{joselit2021nfts}: «The NFT is a social contract that values property over material experience. That contract can be broken.» Nevertheless, I think we should look beyond these hectic times and focus on the innovative technology and techniques of NFTs and DLT in general. After all, the hypertext community has already gone trough a similar tumultuous technological period caused by hype and unwise investments, during the rise of the World Wide Web and subsequent \emph{dot-com bubble burst}~\cite{wheale2003bursting}.
Many technical and ethical challenges must also be resolved to realize hyperownership. For instance, at the moment we have competing DLT and NFT community-driven standards, resulting in low cross-platform compatibility, albeit many initiatives are in course to remedy this~\cite{williams2020cross}. In addition, DLT and related technologies present significant challenges in software engineering~\cite{wessling2018engineering}. For instance, many DLT applications store assets on the InterPlanetary File System (IPFS), a distributed peer-to-peer hypermedia protocol aimed to be resilient and persistent~\cite{huang2020blockchain}, which entails a different development approach. In fact, given this shift in paradigm, many people call Web3 a potential decentralized and token-based iteration of the Web~\cite{voshmgir2020token}, albeit this has been decried as a mere buzzword~\cite{newitz2022web3}.
Still, Web3 tenets might represent the next step in hypermedia infrastructure, which began as monolithic systems, then client-server systems, later as open hypermedia systems (OHS), and currently as component-based OHS~\cite{atzenbeck2017revisiting}. Hence, distributed and decentralized component-based OHS (using for instance IPFS for media storage) should be further explored.
Another significant technical challenge concerns scalability, especially of a graph representation of DLT records which might manifest rapid exponential growth~\cite{alabi2017digital}. In this regard, the community on big graph processing systems is working towards adapting new distributed workloads, standard models, and suitable performance metrics to model complex real-world phenomena, with a keen eye towards the possibility of creating a Big Graph Memex~\cite{sakr2021future}, inspired by Bush's original Memex concept. Hyperownership as described herein thus fits and builds upon such an ambitious vision.
Last but not least, ethical issues are also significant for hyperownership. Privacy, a main driver of DLT~\cite{hassan2019privacy}, is far from perfect, and as some of us can imagine, not everyone is keen in facilitating access to the information regarding what we own. Such issues are also present in hypertext, given that despite its potential to empower users and democratize access to information, it is susceptible to surveillance and manipulation~\cite[Ch. 8]{landow2006hypertext}. Indeed, both sculptural and calligraphic hypertext styles could be used to restrict access or to manipulate the narrative regarding the ownership of certain assets by certain individuals or groups. In fact, it could argued that both hypertext and DLT influence and are influenced by political motives, as respectively demonstrated by the OHS and DAOs. Hence, particularly attention should be paid to these sensitive issues in order to avoid abuse, intentional or not.
\section{Conclusion}
Once again, novel technology is changing the perception and experience of ownership, more so in an environment as \emph{interwingled} as the digital economy. This change represents an opportunity for the development of novel hypertext ideas, such as hyperownership, to unravel and augment our relationship with digital property. Hence, I invite the hypertext community to look and take inspiration by the novel (yet ancient) \emph{token economy}.
\bibliographystyle{ACM-Reference-Format}
| {'timestamp': '2022-06-06T02:14:29', 'yymm': '2206', 'arxiv_id': '2206.01566', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01566'} | arxiv |
\subsection{Rethinking DGI}
\label{rethink_gcl}
DGI~\cite{velivckovic2018deep} is the first work introducing Contrastive Learning into GRL. However, due to a technical defect observed in their official open-source code, we found it is essentially not working as the authors thought (i.e., learning via MI interaction). The backbone that truly makes it work is a new paradigm, Group Discrimination.
\vspace{1mm}\noindent\textbf{Constant Summary Vector.} As shown in Figure \ref{fig:DGI}, the original idea of DGI is to maximise the MI (i.e., the red line) between a node $a$ and the summary vector $ s$, which is obtained by averaging all node embeddings in a graph $\mathcal{G}$. Also, to regularise the model training, DGI corrupts $\mathcal{G}$ by shuffling the node order of the input feature matrix to get $\tilde{\mathcal{G}}$. Then, generated embeddings of $\tilde{\mathcal{G}}$ are served as negative samples, which are pulled apart from the summary vector $ s$ via MI minimisation.
\begin{table}
\footnotesize
\centering
\caption{Summary vector statistics on three datasets with different activation functions including ReLU, LeakyReLU (i.e., LReLU shown below), PReLU, and Sigmoid.}
\label{tab:summary vector}
\resizebox{0.9\columnwidth}{!}{
\begin{tabularx}{0.9\linewidth}{l|p{2.0cm}p{2.0cm}<{\centering}p{2.0cm}<{\centering} p{2.0cm}<{\centering}p{2.0cm}<{\centering}p{2.0cm}<{\centering}}
\toprule
\textbf{Activation} & \textbf{Statistics} &\textbf{Cora} & \textbf{CiteSeer} & \textbf{PubMed}\\
\midrule
& Mean & 0.50 & 0.50 & 0.50\\
ReLU/LReLU/PReLU &Std & 1.3e-03 & 1.0e-04 & 4.0e-04\\
& Range & 1.4e-03 & 8.0e-04 & 1.5e-03 \\
\midrule
& Mean & 0.62 & 0.62 & 0.62 \\
Sigmoid & Std & 5.4e-05 & 2.9e-05 & 6.6e-05\\
& Range & 3.6e-03 & 3.0e-03 & 3.2e-03 \\
\bottomrule
\end{tabularx}}
\end{table}
Nonetheless, in the implementation of DGI, a Sigmoid function is inappropriately applied on the summary vector generated from a GNN whose weight is initialised with Xavier initialisation.
As a result, elements in the summary vector are very close to the same value. We have validated this finding on three datasets (i.e., Cora, CiteSeer and PubMed) with different activation functions used in the GNN encoder including ReLU, Leaky ReLU, PReLU, and Sigmoid. The experiment result is shown in Table \ref{tab:summary vector}, which shows that summary vectors in all datasets are approximately a \textbf{constant vector} $\epsilon I$, where $\epsilon$ is a scalar and $ I \in \mathcal R^{{D}}$ is an all-ones vector (e.g., $\epsilon$=0.5 in these datasets with ReLu, Leaky ReLu or PReLu as activation)
To theoretically explain this phenomenon, we present the theorem below:
\begin{theorem}
Given $\mathcal{G} = (\textbf{X} \in \mathcal{R}^{N\times D}, \textbf{A} \in \mathcal{R}^{N\times N})$, and a GCN encoder $g()$ whose weight matrix is initialised with Xavier initialisation, we can obtain its embedding $\textbf{H} = g(\mathcal{G})$. Then, when $D$ increases, the data range of Sigmoid function $\sigma$ taking $\textbf{H}$ as input (i.e., $max(\sigma(\textbf{H})) - min(\sigma(\textbf{H}))$) converges to 0.
\end{theorem}
Based on this theorem, we can see if the dimension of input feature matrix $\textbf{X}$ is large, then these summary vectors can lose variance and become constant vector. The proof for the theorem is presented in Appendix \ref{proof 1}.
To evaluate the effect of $\epsilon$ to constant summary vector, we vary the scalar $\epsilon$ (from 0 to 1 increment by 0.2) to change the constant summary vector
and report the model performance (i.e., averaged accuracy on five runs) in Table \ref{tab:fix vector}.
\begin{wraptable}{r}{0.7\textwidth}
\vspace{-5mm}
\footnotesize
\caption{The experiment result on three datasets with changing value from 0 to 1.0 for the summary vector.}
\label{tab:fix vector}
\resizebox{0.7\columnwidth}{!}{
\begin{tabularx}{1.0\linewidth}{lp{0.917cm}<{\centering} p{0.917cm}<{\centering} p{0.917cm}<{\centering} p{0.917cm}<{\centering} p{0.917cm}<{\centering} p{0.917cm}<{\centering}}
\toprule
\textbf{Dataset} &\textbf{0} & \textbf{0.2} & \textbf{0.4} & \textbf{0.6} & \textbf{0.8} & \textbf{1.0}\\
\midrule
Cora & 70.3$\pm{0.7}$ & 82.4$\pm{0.2}$ & 82.3$\pm{0.3}$ & 82.5$\pm{0.4}$ & 82.3$\pm{0.3}$ & 82.5$\pm{0.1}$ \\
CiteSeer & 61.8$\pm{0.8}$ & 71.7$\pm{0.6}$ & 71.9$\pm{0.7}$ & 71.6$\pm{0.9}$ & 71.7$\pm{1.0}$ & 71.6$\pm{0.8}$\\
PubMed & 68.3$\pm{1.5}$ & 77.8$\pm{0.5}$ & 77.9$\pm{0.8}$ & 77.7$\pm{0.9}$ & 77.4$\pm{1.1}$ & 77.2$\pm{0.9}$ \\
\bottomrule
\end{tabularx}}
\end{wraptable}
From this table, we can see, except for 0, the model performance is trivially affected by $\epsilon$ for constant summary vector. When the summary vector is set to 0, the model performance plummets because node embeddings become all 0 when multiplying with such vector and the model converges to the trivial solution. As the summary vector only has a trivial effect on model training, the hypothesis of DGI~\cite{velivckovic2018deep} on learning via contrastiveness between anchor nodes and the summary instance does not hold, which raises a question to be investigated: \textit{What truly leads to the success of DGI?}
\noindent\noindent\textbf{Simplifying DGI.} To answer the question, we predigest the loss proposed in DGI by using an all-ones vector as the summary vector $ s$ (i.e., setting $ s=\epsilon I=I$) and simplifying the discriminator $\mathcal{D}$ (i.e., removing the learnable weight vector). Then, we rewrite the loss to the following form:
\begin{equation}
\begin{aligned}
\mathcal{L}_{DGI} &= \frac{1}{2N}({\sum_{i = 1}^{N}}\log\mathcal{D}(z_i, s) +\log(1 - \mathcal{D}(\tilde{z}_i, s))), \\
& = \frac{1}{2N}(\sum_{i = 1}^{N}\log(z_i \cdot s) + \log(1 - \tilde{z}_i\cdot s))), \\
& = \frac{1}{2N}({\sum_{i = 1}^{N}}\log(sum(z_i)) + \log(1 - sum(\tilde{z}_i))),
\end{aligned}
\label{eq:DGI loss}
\end{equation}
where $\cdot$ is the vector multiplication operation, $ N$ is the number of nodes in a graph, $ z_i \in \mathcal{R}^{1 \times D}$ and $ \tilde{z}_i \in \mathcal{R}^{1 \times D}$ are the original and corrupted embedding for node $i$,
$ sum()$ is the summation function, and $\mathcal{D}$ is a discriminator for bilinear transformation, which can be formulated as follows:
\begin{equation}
\mathcal{D}(z_i, s) = z_i\cdot w\cdot s,
\label{eq:discriminator}
\end{equation}
\begin{table}[t]
\vspace{2mm}
\centering
\footnotesize
\caption{Comparison of the original $ DGI$ and $ DGI_{BCE}$ in terms of accuracy (averaged on five runs), memory efficiency (in MB) and training time (in seconds). Number after | shows how many times have $ DGI_{BCE}$ improved on top of $ DGI$.}
\label{tab:bce_compare}
\resizebox{0.7\columnwidth}{!}{
\begin{tabularx}{0.72\linewidth}{ll p{1.6cm}<{\centering} p{1.6cm}<{\centering}p{1.6cm}<{\centering}}
\toprule
\textbf{Experiment} & \textbf{Method} &\textbf{Cora} & \textbf{CiteSeer} & \textbf{PubMed}\\
\midrule
Accuracy & DGI & 81.7$\pm{0.6}$ & 71.5$\pm{0.7}$ & 77.3$\pm{0.6}$ \\
& $ DGI_{BCE}$ & 82.5$\pm{0.3}$ & 71.7$\pm{0.6}$ & 77.7$\pm{0.5}$\\
\midrule
Memory & DGI & 4189MB & 8199MB & 11471MB \\
& $ DGI_{BCE}$ & 1475MB|64.8\% & 1587MB|80.6\% & 1629MB|85.8\% \\
\midrule
Time & DGI & 0.085s & 0.134s & 0.158s \\
& $ DGI_{BCE}$ & 0.010s|8.5$\times$ & 0.021s|6.4$\times$ & 0.015s|10.5$\times$\\
\bottomrule
\end{tabularx}}
\vspace{-2mm}
\end{table}
where $ w$ is a learnable weight vector. Specifically, as shown in Equation \ref{eq:discriminator}, by removing the weight vector $ w$, $ z_i$ is directly multiplied with $ s$. As $ s$ is a vector containing only one, the multiplication of $ z_i$ and $ s$ is equivalent to summing $ z_i$ itself directly. From this form, we can see that the multiplication of $ z_i$ and the summary vector only serves as an aggregation function (i.e., summation aggregation) to summarise information in $ z_i$. To explore the effect of other aggregation functions, we replace the summation function in Equation \ref{eq:DGI loss} with other aggregation methods including mean-, minimum-, maximum- pooling and linear aggregation. We report the experiment results (i.e., averaged accuracy on five runs) in Table \ref{tab:aggregation}. The table shows that replacing the summation function with other aggregation methods still works, while summation and linear aggregation achieve comparatively better performance.
Based on Equation \ref{eq:DGI loss}, we can rewrite it to a very simple binary cross entropy loss if we also include corrupted nodes as data samples and setting $ h_i =sum(z_i)$:
\begin{equation}
\mathcal{L}_{BCE} = \frac{1}{2N}(\sum_{i = 1}^{2N}y_i\log h_i + (1 - y_i)\log(1 - h_i)),
\label{eq:binary DGI}
\end{equation}
\begin{wraptable}{r}{0.6\textwidth}
\vspace{-6mm}
\footnotesize
\caption{The experiment result on three datasets with different aggregation function on node embeddings.}
\label{tab:aggregation}
\resizebox{0.6\columnwidth}{!}{
\begin{tabularx}{1.06\linewidth}{lp{2.2cm}<{\centering} p{2.2cm}<{\centering} p{2.2cm}<{\centering}}
\toprule
\textbf{Method} &\textbf{Cora} & \textbf{CiteSeer} & \textbf{PubMed}\\
\midrule
Sum & 82.5 $\pm{0.2}$ & 71.7 $\pm{0.6}$ & 77.7 $\pm{0.5}$ \\
Mean & 81.8 $\pm{0.5}$ & 71.8 $\pm{1.1}$ & 76.5 $\pm{1.2}$\\
Min & 80.4 $\pm{1.3}$ & 61.7 $\pm{1.8}$& 70.1 $\pm{1.9}$\\
Max & 71.4 $\pm{1.2}$& 65.3 $\pm{1.4}$ & 70.2 $\pm{2.8}$ \\
linear & 82.2 $\pm{0.4}$ & 72.1 $\pm{0.7}$& 77.9 $\pm{0.5}$ \\
\bottomrule
\end{tabularx}}
\end{wraptable}
where $ y_i \in \mathcal{R}^{1 \times 1}$ means the indicator for node $i$ (i.e., if node $i$ is corrupted, $ y_i$ is 0, otherwise it is 1), and $ h_i \in \mathcal{R}^{1 \times 1}$ represents the summarisation of node $i$'s embedding. As we include corrupted nodes as data samples, the size of nodes to be processed is doubled to $ 2N$ (i.e., the number of corrupted nodes is equal to the number of original nodes). From the equation above, we can easily observe that what DGI truly does is discriminate a group of summarised original node embeddings from the other group of summarised corrupted node embeddings, as shown in Figure \ref{fig:node_comparison}. We name this self-supervised learning paradigm "\textbf{Group Discrimination}". To validate the effectiveness of this paradigm, we replace the original DGI loss with Equation \ref{eq:binary DGI}, namely, $ DGI_{BCE}$ and compare it with DGI on three datasets in terms of training time, memory efficiency and model performance as shown in Table \ref{tab:bce_compare}. Here, $ DGI_{BCE}$ adopts the same parameter setting as DGI. From this table, we can observe $ DGI_{BCE}$ dramatically improves DGI in both memory- and time-efficiency while it slightly enhances the model performance of DGI. This is contributed to the removal of multiplication operations between node pairs, which eases the burden of computation and memory consumption in both forward and backward propagation. In section \ref{ap:why}, we further explore GD and compare it with existing contrastive losses.
\subsection{Rethinking MVGRL}
\begin{figure}[htbp]
\centering
\includegraphics[scale = 0.8]{Figures/MVGRL.pdf}
\caption{The architecture of MVGRL. Here augment means augmentation. $S$ is the summary vector based on $\mathcal{G}$, and $S_{aug}$ is the summary vector based on the augmented graph $\mathcal{G}_{aug}$.}
\label{fig:mvgrl}
\end{figure}
Extending the architecture of DGI, MVGRL resorts to multi-view contrastiveness via additional augmentation.
Specifically, as shown in Figure \ref{fig:mvgrl}, it first uses the diffusion augmentation to create $\mathcal{G}_{aug}$. Then, it corrupts $\mathcal{G}$ and $\mathcal{G}_{aug}$ to generate negative samples $\tilde{\mathcal{G}}$ and $\tilde{\mathcal{G}}_{aug}$. To build contrastiveness, MVGRL also generates two summary vectors $S_{aug}$ and $S$ by averaging all embeddings in $\mathcal{G}_{aug}$ and $\mathcal{G}$, respectively. Based on the design of MVGRL, the model training is driven by mutual information maximisation between an anchor node embedding and its corresponding augmented summary vector. However, MVGRL has the same technical error in their official JSD-based implementation as DGI, which makes it also becomes an group-discrimination-based approach.
Similar to Equation \ref{eq:binary DGI} of DGI, the proposed loss in MVGRL can also be rewritten as a binary cross entropy loss:
\begin{equation}
\mathcal{L}_{MVGRL} = \frac{1}{4N}(\sum_{i = 1}^{4N}y_i\log h_i + (1 - y_i)\log(1 - h_i)),
\label{eq:mvgrl_loss}
\end{equation}
here the number of nodes is increased to $ 4N$ as we include nodes in $\mathcal{G}_{aug}$ and $\tilde{\mathcal{G}}_{aug}$ as data samples. The indicator $y_i$ for $\mathcal{G}$ and $\mathcal{G}_{aug}$ are 1, while $\tilde{\mathcal{G}}$ and $\tilde{\mathcal{G}}_{aug}$ are considered as negative samples (i.e., the indicator $y_i$ for them are 0). To explore why MVGRL can achieve a better performance than DGI, we replace the original MVGRL loss with Equation \ref{eq:mvgrl_loss} and conduct ablation study of $ MVGRL_{bce}$ by removing different set of data samples in Equation \ref{eq:mvgrl_loss}, and report the experiment result in Table \ref{tab:mvgrl ablation}. From the table, the performance of $ MVGRL_{bce}$ is on par with $ MVGRL$, which reconfirms the effectiveness of using the bce loss. Also, we can observe that including $\mathcal{G}_{aug}$ and $\tilde{\mathcal{G}}_{aug}$ is the key of MVGRL surpassing DGI. With $\mathcal{G}_{aug}$ and $\tilde{\mathcal{G}}_{aug}$, the model performance of $ MVGRL_{bce} w/o \mathcal{G}_{aug}$ and $\tilde{\mathcal{G}}_{aug}$ is improved from 82.2 to 83.1. We conjecture this is because with the diffusion augmentation, MVGRL is trained with the additional global information provided by the diffused view $\mathcal{G}_{aug}$. However, the diffusion augmentation involves expensive matrix inversion computation and significantly densifies the given graph, which requires much more memory and time to store and process than the original view. This can hinder the model from extending to large-scale datasets \cite{zheng2021towards}.
\begin{table}
\footnotesize
\centering
\caption{The ablation study of MVGRL from the perspective of Group Discrimination.}
\label{tab:mvgrl ablation}
\begin{tabularx}{0.72\linewidth}{lp{1.4cm}<{\centering} p{1.4cm}<{\centering} p{1.4cm}<{\centering}}
\toprule
\textbf{Method} &\textbf{Cora} & \textbf{CiteSeer} & \textbf{PubMed}\\
\midrule
$ MVGRL$ & 82.9 $\pm{0.9}$ & 72.6 $\pm{0.8}$ & 78.8 $\pm{0.6}$ \\
$ MVGRL_{bce}$ & 83.1 $\pm{0.6}$ & 72.8 $\pm{0.5}$ & 79.1 $\pm{1.1}$ \\
$ MVGRL_{bce}$ w/o $\mathcal{G}_{aug}$ & 81.2 $\pm{0.8}$ & 52.8 $\pm{3.1}$ & 76.6 $\pm{1.3}$ \\
$ MVGRL_{bce}$ w/o $\mathcal{G}$ & 82.1 $\pm{0.6}$ & 71.8 $\pm{1.1}$ & 77.1 $\pm{1.2}$\\
$ MVGRL_{bce}$ w/o $\tilde{\mathcal{G}}_{aug}$ & 81.1 $\pm{0.8}$ & 56.7 $\pm{2.1}$& 74.9 $\pm{1.3}$\\
$ MVGRL_{bce}$ w/o $\tilde{\mathcal{G}}$ & 82.7 $\pm{0.9}$ & 72.0 $\pm{0.9}$ & 78.6 $\pm{0.9}$\\
$ MVGRL_{bce}$ w/o $\mathcal{G}_{aug}$ and $\tilde{\mathcal{G}}_{aug}$ & 82.2 $\pm{0.6}$ & 71.8 $\pm{1.0}$ & 77.0 $\pm{0.8}$ \\
$ MVGRL_{bce}$ w/o $\mathcal{G}$ and $\tilde{\mathcal{G}}$ & 83.1 $\pm{0.6}$ & 72.6 $\pm{0.6}$& 78.5 $\pm{1.4}$ \\
\bottomrule
\end{tabularx}
\end{table}
\subsection{Definition of Group Discrimination}
As mentioned above, Group Discrimination is a self-supervised GRL paradigm, which learns by discriminating different groups of node embeddings. Specifically, the paradigm assigns different indicators to different groups of node embeddings. For example, for binary group discrimination, one group is considered as the positive group with class 1 as its indicator, whereas the other group is the negative group, having its indicator assigned as 0. Given a graph $\mathcal{G}$, the positive group usually includes node embeddings generated with the original graph $\mathcal{G}$ or its augmented views (i.e., similar graph instances of $\mathcal{G}$ created by augmentation). In contrast, the opposing group contains negative samples obtained by corrupting $\mathcal{G}$, e.g., changing its topology structure.
\subsection{Problem Definition}
We first define unsupervised node representation learning and then present the architecture of \texttt{GGD}, which extends $DGI_{BCE}$ with additional augmentation and embedding reinforcement to reach better model performance. Given a graph $\mathcal{G}$ with attributes $ \textbf{X} \in \mathcal{R}^{N \times D}$, where $ N$ is the number of nodes in $\mathcal{G}$, and $ D$ is the number of dimensions of $\textbf{X}$, our aim is to train a GNN encoder without the reliance on labelling information. With the trained encoder, taking $\mathcal{G}$ and $\textbf{X}$ as input, it can output learned representations $ \textbf{H} \in \mathcal{R}^{N \times \hat{D}}$, where $ \hat{D}$ is the predefined output dimension. $ \textbf{H}$ can then be used in many downstream tasks such as node classification.
\subsection{Graph Group Discrimination}
Based on the proposed self-supervised GRL paradigm, Group Discrimination, we have designed a novel method, namely \texttt{GGD}, to learn node representations using a Siamese network structure and a binary cross-entropy loss. The architecture of the proposed framework is presented in Figure \ref{fig:ggd}. The framework mainly consists of four components: augmentation, corruption, a Siamese GNN network, and Group Discrimination.
\noindent \textbf{Augmentation.} With a given graph $\mathcal{G}$ and feature matrix $ \textbf{X}$, optionally, we can augment it with augmentation techniques such as edge and feature dropout to create $\hat{\mathcal{G}}$ and $ \hat{\textbf{X}}$. In practice, we follow the augmentation proposed in GraphCL~\cite{you2020graph}. Specifically, edge dropout removes a predefined fraction of edges, while we use node dropout to mask a predefined proportion of feature dimension, i.e., assigning 0 to replace values in randomly selected dimensions. This step is optional in implementation.
Notably, the motivation of using augmentation in our framework is distinct from contrastive learning methods. In our study, augmentation is used to increase the difficulty of the self-supervised training tasks. With augmentation, $\hat{\mathcal{G}}$ and $ \hat{\textbf{X}}$ is changing in every training iteration, which forces the model to lessen the dependence on the fixed pattern (i.e., unchanged edge and feature distribution) in a monotonous graph. However, in Contrastive Learning, augmentation creates augmented views sharing similar semantic information for building contrastiveness.
\noindent \textbf{Corruption.} $\hat{\mathcal{G}}$ and $ \hat{\textbf{X}}$ are then corrupted to build $\tilde{\mathcal{G}}$ and $ \tilde{\textbf{X}}$ for the generation of node embeddings in the negative group. We adopt the same corruption technique used in DGI~\cite{velivckovic2018deep} and MVGRL~\cite{hassani2020contrastive} as shown in Figure \ref{fig:corruption}.
The corruption technique devastates the topology structure of $\hat{\mathcal{G}}$ by randomly changing the order of nodes in $ \hat{\textbf{X}}$. The corrupted $ \tilde{\textbf{X}}$ and $\tilde{\mathcal{G}}$ can be used for producing node representations with incorrect network connections.
\noindent \textbf{The Siamese GNN.} We have designed a Siamese GNN network to output node representations given a graph and its attribute. The Siamese GNN network is made up of two components, which are a GNN encoder and a projector. The backbone GNN encoder is replaceable with a variety of choices of GNNs, e.g., GCN~\cite{kipf2016semi} and GAT~\cite{velivckovic2017graph}. In our work, we adopt GCN as the backbone. The projector is a flexible network with a user-defined number of linear layers. When generating node embeddings of the positive group, the Siamese network takes $\hat{\mathcal{G}}$ and $ \hat{\textbf{X}}$ as input. Using the same encoder and projector, the Siamese network output the negative group with $\tilde{\mathcal{G}}$ and $ \tilde{\textbf{X}}$. These two groups of node embeddings are considered as a collection of data samples with a size of $ 2N$ for discrimination. Before conducting group discrimination, all data samples are summarised with the same aggregation technique, e.g., sum-, mean-, and linear aggregation.
\noindent \textbf{Group Discrimination.} In the group discrimination process, we adopts a very simple binary cross entropy (BCE) loss to discriminate two groups of node embeddings as shown in Equation \ref{eq:binary DGI}.
In our implementation, $ y_i$ is 0 and 1 for node embeddings in negative and positive groups. During model training, the model is optimised by categorising node embeddings in the collection of data samples into their corresponding class correctly. The loss is computed by comparing the summarisation of a node $i$, i.e., a scalar, with its indicator $ y_i$. With the ease of BCE loss computation, the training process of \texttt{GGD}\ is very fast and memory efficient.
\vspace{-2mm}
\subsection{Model Inference}
During training, the model is optimised via loss minimisation with Equation \ref{eq:binary DGI}. The time complexity analysis of \texttt{GGD}\ is provided in Appendix \ref{sec:complexity analysis}. With the trained GNN encoder $g_{\theta}$, we can obtain the node embeddings $ \textbf{H}_{\theta}$ with the input $\mathcal{G}$.
Inspired by MVGRL~\cite{hassani2020contrastive}, which strengthens the output embeddings by including additional global information, we adopt a conceptually similar embedding reinforcement approach. Specifically, they obtain the final embeddings by summing up embeddings from two views: the original view comprising local information and the diffused view with global information. This operation reinforces the final embeddings and leads to model performance improvement. Nonetheless,
graph diffusion impairs the scalability of a model \cite{zheng2021towards} and hence cannot be directly applied in our embedding generation. To avoid the diffusion computation, we have come up with a workaround in the virtue of graph power to extract global information. Graph power can extend the message passing scope of $ \textbf{H}_{\theta}$ to n-hop neighbourhood, which encodes global information from distant neighbours. It can be formulated as follows:
\vspace{-1mm}
\begin{equation}
\textbf{H}_{\theta}^{global} = \textbf{A}^n \cdot \textbf{H}_{\theta},
\label{graph power}
\end{equation}
where $ \textbf{H}_{\theta}^{global}$ is the global embedding, and $ \textbf{A}$ is the adjacency matrix of the graph $\mathcal{G}$.
It is notable that this operation can be easily decomposed with the associative property of matrix multiplication and is easy to compute.
To show the easiness of such computation, we conduct an experiment showing its time consumption on various datasets in Appendix \ref{sec:graph power}. Finally, the final embedding can be achieved by $ \textbf{H} = \textbf{H}_{\theta}^{global} + \textbf{H}_{\theta}$,
which can be used for downstream tasks.
\subsection{Corruption}
\label{ap:why}
Firstly, we explore the corruption technique used in DGI~\cite{velivckovic2018deep} and MVGRL~\cite{hassani2020contrastive}, which is shown in Figure \ref{fig:corruption}. These two studies corrupt the topology of a given graph $\mathcal{G}$ by shuffling the feature matrix $ \textbf{X}$. This is because by changing the node order of $ \textbf{X}$, the neighbouring structure of $\mathcal{G}$ is completely changed, e.g., neighbours of node $a$ become node $b$ neighbours.
With the corruption technique, negative samples in the negative group are generated with incorrect edges. Thus, by discriminating the positive group (i.e., nodes generated with ground truth edges) and the negative group, we conjecture the model can distill valuable signals from learning how to identify nodes generated with correct topology and output effective node embeddings.
\subsubsection{Benefits of Group Discrimination}
Compared with contrastive learning, Group Discrimination enjoys advantages in computation efficiency, memory efficiency and convergence speed. To compare Group Discrimination with GCL, we first analyse the complexity of two commonly-adopted contrastive loss functions, InfoNCE and JSD estimator. These two contrastive losses of an anchor node $i$ can be formulated as follows:
\begin{minipage}{0.4\textwidth}
\begin{equation}
\mathcal{L}_{NCE}(i) = -\log\frac{e^{z_i\cdot c_i/\tau}}{\sum^{N}_{k=1}e^{z_i \cdot z_k/\tau}}
\label{infonce}
\end{equation}
\end{minipage}
\begin{minipage}{0.6\textwidth}
\begin{equation}
\mathcal{L}_{JSD}(i) = -\log\mathcal{D}(z_i, c_i) + \log(1-\mathcal{D}(\tilde{z}_i,c_i))
\end{equation}
\end{minipage}
\noindent where $ z_i \in \mathcal{R}^{1 \times D}$ represents node embedding of node $i$, $\tau$ is the temperature coefficient, $\mathcal{D}$ is the discriminator, $ \tilde{z}_i$ is the corrupted negative counterpart, and $ c_i \in \mathcal{R}^{1 \times D}$ is the positive counterpart sharing similar semantic information with node $i$. In InfoNCE, the loss computation conducts similarity computation for positive (i.e, the numerator of Equation \ref{infonce}) and negative counterparts (i.e., the denominator) once and $ N$ times, respectively. As the time complexity of node similarity computation is $ O(D)$ (e.g., vector multiplication between $ z_i$ and $ c_i$), the overall complexity for InfoNCE is $ O(ND)$. Though the JSD estimator does not require a size of $ N$ negative samples for each node, it still needs $ O(D)$ for the loss computation of an anchor node because the discriminator requires vector multiplication between embeddings of node $i$ and $ c_i$.
To alleviate the computation burden of InfoNCE loss, BGRL~\cite{thakoor2021bootstrapped} and GBT~\cite{zbontar2021barlow} attempt to get rid of the reliance on negative samples with customised losses. BGRL~\cite{thakoor2021bootstrapped} utilises a simple loss to minimise the cosine similarity between the online node embedding $ z_{(\mathcal{G}_1,i)}$ and the target node embedding $ h_{(\mathcal{G}_2,i)}$ for node $i$:
\begin{equation}
\mathcal{L}_{BGRL}(i) = -\frac{z_{(\mathcal{G}_1,i)} \cdot h_{(\mathcal{G}_2,i)}}{\parallel z_{(\mathcal{G}_1,i)} \parallel \cdot \parallel h_{(\mathcal{G}_2,i)} \parallel},
\end{equation}
where $z_{(\mathcal{G}_1,i)}$ and $ h_{(\mathcal{G}_2,i)}$ are generated from two augmented views $\mathcal{G}_1$ and $\mathcal{G}_2$. Different from BGRL~\cite{thakoor2021bootstrapped}, GBT~\cite{zbontar2021barlow} adopts a correlation-based loss as follows:
\begin{equation}
\mathcal{L}_{GBT}(i) = \sum_{i}(1 - C_{ii})^2 + \lambda \sum_{j \neq i} C_{ij}^2; C_{ij} = \frac{z_{(\mathcal{G}_1,i)} \cdot z_{(\mathcal{G}_2,j)}}{\sqrt{{z_{(\mathcal{G}_1,i)}}^2} \cdot \sqrt{{z_{(\mathcal{G}_2,j)}}^2}},
\end{equation}
where $i$ and $j$ are two indices for the embedding dimension.
From the losses shown above, we can see these two losses still involve vector multiplication between two node embeddings. Thus, even though these two methods reduce the time complexity of InfoNCE (i.e., $ O(ND)$) to $ O(D)$, they are still on par with the JSD estimator. Different from the aforementioned contrastive learning loss, to actuate a Group Discrimination learning paradigm, our method uses an effortless binary cross-entropy loss as shown in Equation \ref{eq:binary DGI}. In Group Discrimination, the loss computation of a node $i$ requires only $ O(1)$ as it conducts multiplication between scalars (i.e., $ h_i$ and $ y_i$) in lieu of vectors. Thus, Group Discrimination has great advantages in computation and memory efficiency. Another merit of the proposed paradigm is fast convergence as shown in section \ref{sec:large}. We conjecture this is contributed to the concentration of Group Discrimination on the general edge distribution of graphs instead of node-specific information as GCL methods do. Thus, it would not be distracted from too-detailed information.
\subsection{Evaluating on Small- and Medium-scale Datasets}
\label{sec:evalsmall}
We compare \texttt{GGD}\ with ten baselines including four supervised GNNs (i.e., GCN~\cite{kipf2016semi}, GAT~\cite{velivckovic2017graph}, SGC~\cite{wu2019simplifying}, and CG3~\cite{wan2020contrastive}) and six GCL methods (i.e., DGI~\cite{velivckovic2018deep}, GMI~\cite{peng2020graph}, MVGRL~\cite{hassani2020contrastive}, GRACE~\cite{zhu2020deep}, BGRL~\cite{thakoor2021bootstrapped} and GBT~\cite{zbontar2021barlow}) on five small- and medium scale benchmark datasets. In the experiment, we follow the same data splits as ~\cite{yang2016revisiting} for Cora, CiteSeer and PubMed. For Amazon Computers and
Photos, we adopt the semi-supervised experiment setting, which includes 30 randomly-selected nodes per class in the training and validation set. The remaining nodes are used as the test set. The model performance is measured using the averaged classification accuracy with five results along with standard deviations and reported in Table \ref{tab: classification results}.
\begin{table}[t]
\footnotesize
\centering
\caption{Comparison of memory consumption in \underline{MBs} of six GCL baselines and \texttt{GGD}\ on five datasets.}
\label{tab:memory}
\resizebox{0.8\columnwidth}{!}{
\begin{tabularx}{0.79\linewidth}{lp{1.5cm}<{\centering} p{1.5cm}<{\centering}p{1.5cm}<{\centering}p{1.5cm}<{\centering}p{1.5cm}<{\centering}}
\toprule
\textbf{Method} &\textbf{Cora} & \textbf{CiteSeer} &\textbf{PubMed} &\textbf{Comp} &\textbf{Photo}\\
\midrule
DGI & 4,189 & 8,199 & 11,471 & 7,991 & 4,946 \\
GMI & 4,527 & 5,467 & 14,697 & 10,655 & 5,219 \\
MVGRL & 5,381 & 5,429 & 6,619 & 6,645 & 6,645\\
GRACE & 1,913 & 2,043 & 12,597 & 8,129 & 4,881\\
BGRL & 1,627 & 1,749 & 2,299 & 5,069 & 3,303 \\
GBT & 1,651 & 1,799 & 2,461 & 5,037 & 2,641\\
\midrule
\texttt{GGD} & 1,475 & 1,587 & 1,629 & 1,787 & 1,637\\
\midrule
Improve & 10.7-72.6\% & 11.8-80.6\% & 27.2-85.8\% & 64.5-83.2\% & 38.0-75.4\%\\
\bottomrule
\end{tabularx}
}
\end{table}
\noindent \textbf{Accuracy.} From Table \ref{tab: classification results}, we can observe that GGD generally outperforms all baselines
in all datasets. The only exception is on CiteSeer dataset, where the semi-supervised method, CG3\cite{wan2020contrastive}, slightly outperforms \texttt{GGD}, which still provides the 2nd best performance. In this experiment, we reproduce BGRL~\cite{thakoor2021bootstrapped}, GBT~\cite{zbontar2021barlow} and \texttt{GGD}, while the other results are sourced from previous studies~\cite{wan2020contrastive, jin2021multi}.
\noindent \textbf{Efficiency and Memory Consumption.} \texttt{GGD}\ is substantially more efficient than other self-supervised baselines in time and memory consumption as shown in Table \ref{tab:time} and Table \ref{tab:memory}. Remarkably, \texttt{GGD}\ is \textbf{19.2 times faster} in Amazon Photos for training time per epoch, and consumes \textbf{64.5\% less memory} in Amazon Computers for memory consumption than the most efficient baselines (i.e., GBT~\cite{zbontar2021barlow}). The dramatic boost of time and memory efficiency of \texttt{GGD}\ is contributed to the exclusion of similarity computation in self-supervised signal extraction, which enables model training without multiplication of node embeddings.
\subsection{Evaluating on Large-scale datasets}
\label{sec:large}
To evaluate the scalability of \texttt{GGD}, we choose three large-scale datasets from Open Graph Benchmark~\cite{hu2020open}, which are ogbn-arxiv, ogbn-products, and ogbn-papers100M. ogbn-papers100M is the most challenging large-scale graph available in Open Graph Benchmark for node property prediction with over 1 billion edges and 110 million nodes. Extending to extremely large graphs (i.e., ogbn-products and ogbn-papers100M), we adopt a Neighbourhood Sampling strategy, which is described in Appendix \ref{sec:exp setting}.
\noindent \textbf{ogbn-arxiv \& ogbn-products.}
For ogbn-arxiv, we compare \texttt{GGD}\ against four self-supervised baselines (i.e., DGI~\cite{velivckovic2018deep}, GRACE~\cite{zhu2020deep}, BGRL~\cite{thakoor2021bootstrapped}and GBT~\cite{zbontar2021barlow}), whereas BGRL~\cite{thakoor2021bootstrapped} and GBT~\cite{zbontar2021barlow} are selected to be compared for ogbn-products.
\begin{table}[t]
\centering
\footnotesize
\caption{Node classification result and efficiency comparison on ogbn-arxiv.
`epo' means epoch. `Time' means training time per epoch (in seconds). `Total' is total training time (Number of epochs $\times$ `Time'). OOM indicates out-of-memory on Nvidia A40 (48GB).}
\label{tab:ogbn-arxiv}
\resizebox{0.85\columnwidth}{!}{
\begin{tabularx}{0.82\linewidth}{lp{0.9cm}<{\centering} p{1.2cm}<{\centering} |p{2.5cm}<{\centering} p{0.3cm}<{\centering}p{1.2cm}<{\centering}}
\toprule
\textbf{Method} &\textbf{Valid} & \textbf{Test} & \textbf{Memory} & \textbf{Time} & \textbf{Total}\\
\midrule
Supervised GCN & 73.0$\pm{0.2}$ & 71.7$\pm{0.3}$ & - & - & - \\
\midrule
MLP & 57.7$\pm{0.4}$ & 55.5$\pm{0.2}$ & - & - & - \\
Node2vec & 71.3$\pm{0.1}$ & 70.1$\pm{0.1}$ & - & - & - \\
\midrule
DGI & 71.3$\pm{0.1}$ & 70.3$\pm{0.2}$ & - & - & -\\
GRACE(10k epos) & 72.6$\pm{0.2}$ & 71.5$\pm{0.1}$ & - & - & -\\
BGRL(10k epos) & 72.5$\pm{0.1}$ & 71.6$\pm{0.1}$ & OOM (Full-graph) & / &/ \\
GBT(300 epos) & 71.0$\pm{0.1}$ & 70.1$\pm{0.2}$ & 14,959MB & 6.47 & 1,941.00 \\
\midrule
\texttt{GGD} (1 epo) & 72.7$\pm{0.3}$ & 71.6$\pm{0.5}$ & 4,513MB|69.8\% & 0.18 & 0.18|10,783$\times$\\
\bottomrule
\end{tabularx}
}
\end{table}
In addition, we include the performance of MLP, Node2vec~\cite{grover2016node2vec}, and supervised GCN~\cite{kipf2016semi} sourced from~\cite{hu2020open} in Table \ref{tab:ogbn-arxiv} and Table \ref{tab:ogbn-products}. For memory and training time comparison, we only compare \texttt{GGD}\ with the two most efficient baselines (i.e., BGRL and GBT according to Tables \ref{tab:time} and \ref{tab:memory}). In ogbn-arxiv, we reproduce BGRL~\cite{thakoor2021bootstrapped} and found it fails to process ogbn-arxiv in full batch. Thus, we only compare \texttt{GGD}\ and GBT in this dataset, which can successfully train in full-graph processing mode.
\begin{table}[t]
\footnotesize
\caption{Node classification result and efficiency comparison on ogbn-products. }
\centering
\label{tab:ogbn-products}
\resizebox{0.85\columnwidth}{!}{
\begin{tabularx}{0.82\linewidth}{lp{1.1cm}<{\centering} p{1.2cm}<{\centering} |p{1.9cm}<{\centering} p{0.8cm}<{\centering}p{1.1cm}<{\centering}}
\toprule
\textbf{Method} &\textbf{Valid} & \textbf{Test} & \textbf{Memory} & \textbf{Time} & \textbf{Total}\\
\midrule
Supervised GCN & 92.0$\pm{0.0}$ & 75.6$\pm{0.2}$ & - & - \\
\midrule
MLP & 75.5$\pm{0.0}$ & 61.1$\pm{0.0}$ & - & - \\
Node2vec & 70.0$\pm{0.0}$ & 68.8$\pm{0.0}$ & - & - \\
\midrule
BGRL (100 epos) & 78.1$\pm{2.1}$ & 64.0$\pm{1.6}$ & 29,303MB & 53m16s & 5,326m40s \\
GBT (100 epos) & 85.0$\pm{0.1}$ & 70.5$\pm{0.4}$ & 20,419MB & 48m38s & 4,863m20s\\
\midrule
\texttt{GGD} (1 epo) & 90.9$\pm{0.5}$ & \textbf{75.7}$\pm{0.4}$ & 4,391MB|78.5\% & 12m46s & 12m46s|381$\times$\\
\bottomrule
\end{tabularx}
}
\end{table}
From Table \ref{tab:ogbn-arxiv} and Table \ref{tab:ogbn-products}, we can see \texttt{GGD}\ remarkably achieves the state-of-the-art performance using only one epoch to train. As a result, \texttt{GGD}\ is 10,783 times faster than the most efficient baseline, i.e., GBT~\cite{zbontar2021barlow}, on total training time to reach the desirable performance in ogbn-arxiv. Please be noted that the number of epochs in our experiment is consistent with the optimal choice of this hyperparameter specified in GBT~\cite{zbontar2021barlow}. For ogbn-products, we are 381 $\times$ faster than GBT~\cite{zbontar2021barlow} on total training time.
Notably, our performance is significantly higher than GCL baselines using 100 epochs (i.e., 6\% and 5.2\% improvement on GBT~\cite{zbontar2021barlow} in validation and test set) with only one epoch training in this dataset. In addition, we compare the convergence speed among \texttt{GGD} , BGRL~\cite{thakoor2021bootstrapped} and GBT~\cite{zbontar2021barlow} on ogbn-arxiv and ogbn-products, which are shown in Figure \ref{convergence}. For ogbn-arxiv, BGRL~\cite{zbontar2021barlow} is running using batched processing with neighbour sampling. This figure shows the preeminence of \texttt{GGD}\ in convergence speed as \texttt{GGD}\ can be well-trained with only one epoch (i.e., reaching the peak model performance in the first epoch and staying stable with increased epochs). In contrast, the other two baselines require comparatively much more epochs to gradually improve their performance. Compared with GCL baselines, \texttt{GGD}\ achieves much faster convergence via Group Discrimination. We conjecture this is because GD-based method focuses on the general edge distribution of graphs instead of node-specific information. Inversely, GCL methods can suffer from convergence inefficiency as they may be easily distracted from too-detailed node-specific information during training.
\begin{figure}[t]
\centering
\begin{subfigure}
\centering
\includegraphics[scale = 0.3]{Figures/ogbn-arxiv.pdf}
\label{fig:tsne-cora_1}
\end{subfigure}
\hspace{10mm}
\begin{subfigure}
\centering
\includegraphics[scale = 0.3]{Figures/ogbn-products.pdf}
\label{fig:tsne-dgi_1}
\end{subfigure}
\vspace{-4mm}
\caption{Convergence speed comparison among \texttt{GGD}, BGRL\cite{thakoor2021bootstrapped} and GBT~\cite{zbontar2021barlow}. X-axis means number of epochs, while Y-axis represents the accuracy on test set.}
\label{convergence}
\end{figure}
\begin{table}[t]
\centering
\footnotesize
\caption{Node classification result and efficiency comparison on ogbn-papers100M. }
\label{tab:ogbn-paper}
\resizebox{0.75\columnwidth}{!}{
\begin{tabularx}{0.7\linewidth}{lp{1.1cm}<{\centering} p{1.1cm}<{\centering}| p{1.77cm}<{\centering} p{1.0cm}<{\centering}}
\toprule
\textbf{Method} &\textbf{Validation} & \textbf{Test} &\textbf{Memory} &\textbf{Time}\\
\midrule
Supervised SGC & 63.3$\pm{0.2}$ & 66.5$\pm{0.2}$ & - & -\\
\midrule
MLP & 47.2$\pm{0.3}$ & 49.6$\pm{0.3}$ & - & -\\
Node2vec & 55.6$\pm{0.0}$ & 58.1$\pm{0.0}$ & - & -\\
\midrule
BGRL (1 epoch)& 59.3$\pm{0.5}$ & 62.1$\pm{0.3}$ & 14,057MB & 26h28m\\
GBT (1 epoch)& 58.9$\pm{0.4}$ & 61.5$\pm{0.5}$ & 13,185MB & 24h38m \\
\midrule
\texttt{GGD} (1 epoch) & 60.2$\pm{0.3}$ & 63.5$\pm{0.5}$ & 4,105MB|68.9\% & 9h15m|2.7$\times$ \\
\bottomrule
\label{ogbn-papers100m}
\end{tabularx}}
\end{table}
\noindent \textbf{ogbn-papers100M.}
We further compare \texttt{GGD}\ with BGRL~\cite{thakoor2021bootstrapped} and GBT~\cite{zbontar2021barlow} on ogbn-papers100M, the largest OGB dataset with billion scale edges. Other self-supervised learning algorithms such as DGI~\cite{velivckovic2018deep} and GMI~\cite{peng2020graph} fail to scale to such a large graph with a reasonable batch size (i.e., 256). We only report the performance of each algorithm after a single epoch of training in Table \ref{ogbn-papers100m} due to the extreme scale of the dataset and the limitation of our available resources. From the table, we can observe that \texttt{GGD}\ outperforms the two GCL counterparts, BGRL~\cite{thakoor2021bootstrapped} and GBT~\cite{zbontar2021barlow} in both accuracy and efficiency. Specifically, \texttt{GGD}\ achieves 60.2 in accuracy while BGRL and GBT reach 59.3 and 58.9 in test set, respectively. With only one epoch, these two algorithms may not be well trained. However, training each epoch of these two requires over 1 day and if we would like to train them for 100 epochs, then we will need 100+ GPU days, which is prohibitively impractical for general practitioners. In contrast, \texttt{GGD}\ can be trained in about 9 hours to achieve a good result for this dataset, which is more appealing in practice.
\section{Appendix A}
\subsection{Proof of Theorem 1}
\label{proof 1}
\noindent\textit{Proof.} To prove Theorem 1, given a graph $\mathcal{G} = (\textbf{X},\textbf{A})$, where $\textbf{X} \in \mathcal{R}^{N \times D}$ and a GNN encoder $g()$, for simplicity, we consider $g()$ as a one-layer GCN and conduct the following normalisation to $\textbf{X}$ to make its value to be within the range $[0,1]$:
\begin{equation}
z_{ij} = \frac{x_{ij}- min(x_j)}{max(x_j)-min(x_j)}
\end{equation}
where $z_{ij} \in \textbf{Z}$ is the normalised $x_{ij} \in \textbf{X}$, $i$ denotes the row-entry of the matrix, $j$ indicates the column-entry of the matrix, $min()$ is the function to get the minimum value, and $max()$ is the function for getting the maximum value.
Then, we input $\textbf{Z}$ to $g$ whose weight matrix $\textbf{W}$ is initialised with Xavier initialisation:
\begin{equation}
\begin{aligned}
\textbf{H} &= \sigma(\hat{\textbf{D}}^{\frac{1}{2}}\hat{\textbf{A}}\hat{\textbf{D}}^{\frac{1}{2}}\textbf{ZW}),
\end{aligned}
\end{equation}
where $\textbf{H}$ is the output embedding, $\sigma$ is non-linear activation function, $\hat{\textbf{A}} = \textbf{A} + \textbf{I}$, $\hat{\textbf{D}}$ is the degree matrix for $\hat{\textbf{A}}$, $\textbf{W}$ is the learnable weight matrix. As multiplying the normalised adjacency matrix will not change the output data range, the output of $\hat{\textbf{D}}^{\frac{1}{2}}\hat{\textbf{A}}\hat{\textbf{D}}^{\frac{1}{2}}\textbf{Z}$ is still within the range $[0,1]$. Then, as the element in Xavier initialised $\textbf{W}$ is in between $\frac{-1}{\sqrt{D}}$ and $\frac{1}{\sqrt{D}}$, we can easily derive that the output data range of the matrix multiplication of $\hat{\textbf{D}}^{\frac{1}{2}}\hat{\textbf{A}}\hat{\textbf{D}}^{\frac{1}{2}}\textbf{Z}$ and $\textbf{W}$ still stay in the same range $[\frac{-1}{\sqrt{D}},\frac{1}{\sqrt{D}}]$ as $\textbf{W}$.
After that, we need to apply $\sigma$ to the multiplication output. Here, we analyse four commonly adopted non-linear activation functions: Sigmoid, ReLu, LeakyReLu and PReLu.
We first consider the Sigmoid function $\sigma(\textbf{x}) = \frac{1}{1+e^{-\textbf{x}}}$ , as it is a monotonic increasing function, we can derive that the data range of $\textbf{H} \in [\frac{1}{1 + e^{\frac{1}{\sqrt{D}}}}, \frac{1}{1 + e^{-\frac{1}{\sqrt{D}}}}]$. Then, we apply the Sigmoid function $S()$ again as DGI\cite{velivckovic2018deep} did to $\textbf{H}$ and obtain:
\begin{equation}
S(\textbf{H}) = \frac{1}{1 + e^{-\textbf{H}}}.
\end{equation}
Similarily, as the Sigmoid function is a monotonic increasing function, we can easily derive that the data range for $S(\textbf{H})$ is in $[\frac{1}{e^{-\frac{1}{e^{\frac{1}{\sqrt{D}}}+1}}+1}, \frac{1}{e^{-\frac{1}{e^{-\frac{1}{\sqrt{D}}}+1}}+1}]$.
Then, when $D\rightarrow \infty$, for the lower bound $\frac{1}{e^{-\frac{1}{e^{-\frac{1}{\sqrt{D}}}+1}}+1}$, we can obtain:
\begin{equation}
\begin{aligned}
\lim_{D \rightarrow \infty}(\frac{1}{e^{-\frac{1}{e^{-\frac{1}{\sqrt{D}}}+1}}+1}) &= \frac{1}{\underset{D\to \infty }{\text{lim}}\left(e^{-\frac{1}{e^{-D^{-\frac{1}{2}}}+1}}+1\right)} \\ &= \frac{1}{\exp \left(\underset{D\to \infty }{\text{lim}}-\frac{1}{e^{-D^{-\frac{1}{2}}}+1}\right)+1} \\ &= \frac{1}{\exp \left(-\frac{1}{\exp \left(-\underset{D\to \infty }{\text{lim}}D^{-\frac{1}{2}}\right)+1}\right)+1} \\ &= \frac{1}{\exp \left(-\frac{1}{\exp \left(-\frac{1}{\sqrt{\underset{D\to \infty }{\text{lim}}D}}\right)+1}\right)+1} \\ &= \frac{1}{e^{-\frac{1}{e^{-\frac{1}{\sqrt{\infty }}}+1}}+1} \\ &= \frac{1}{\sqrt{e}^{-1}+1} \\ &\approx 0.62
\end{aligned}
\end{equation}
Also, for the upper bound $\frac{1}{e^{-\frac{1}{e^{\frac{1}{\sqrt{D}}}+1}}+1}$, when $D \rightarrow \infty$, we can obtain:
\begin{equation}
\begin{aligned}
\lim_{D \rightarrow \infty}(\frac{1}{e^{-\frac{1}{e^{\frac{1}{\sqrt{D}}}+1}}+1}) &= \frac{1}{\underset{D\to \infty }{\text{lim}}\left(e^{-\frac{1}{e^{D^{-\frac{1}{2}}}+1}}+1\right)} \\ &= \frac{1}{\underset{D\to \infty }{\text{lim}}e^{-\frac{1}{e^{D^{-\frac{1}{2}}}+1}}+ 1} \\&= \frac{1}{\exp \left(\underset{D\to \infty }{\text{lim}}-\frac{1}{e^{D^{-\frac{1}{2}}}+1}\right)+1} \\&= \frac{1}{\exp \left(-\frac{1}{\exp \left(\underset{D\to \infty }{\text{lim}}D^{-\frac{1}{2}}\right)+1}\right)+1} \\ &= \frac{1}{\exp \left(-\frac{1}{\exp \left(\frac{1}{\sqrt{\underset{D\to \infty }{\text{lim}}D}}\right)+1}\right)+1} \\&= \frac{1}{e^{\frac{1}{e^{-\frac{1}{\sqrt{\infty }}}+1}}+1} \\ &= \frac{1}{\sqrt{e}^{-1}+1} \\ &\approx 0.62
\end{aligned}
\end{equation}
Finally, we can easily observe that $\lim_{D \rightarrow \infty}(\frac{1}{e^{-\frac{1}{e^{\frac{1}{\sqrt{D}}}+1}}+1}) = \lim_{D \rightarrow \infty}(\frac{1}{e^{-\frac{1}{e^{-\frac{1}{\sqrt{D}}}+1}}+1})$ and thus prove Theorem 1 when $\sigma$ is Sigmoid function.
For the other three non-linear activation functions ReLu $\sigma(x) = max(0, x)$, Leaky ReLu $\sigma(x) = max(0.01*x, x)$ and PReLu $\sigma(x) = max(0, x) + a*min(0, x)$, where $a \leq 1$ is a learnable parameter, we can also derive the data range of these functions for $\textbf{H}$ are $[0, \frac{1}{\sqrt{D}}]$, $[\frac{-0.01}{\sqrt{D}}, \frac{1}{\sqrt{D}}]$ and $[\frac{-a}{\sqrt{D}}, \frac{1}{\sqrt{D}}]$, respectively. Here, we can see these functions share the same upper bound $\frac{1}{\sqrt{D}}$. The only difference for their lower bound is the coefficient $c \in [0, 1]$ for $\frac{-1}{\sqrt{D}}$, i.e., 0 for ReLu, 0.01 for Leaky ReLu and $a$ for PReLu.
By inputting $\textbf{H}$ with these activation functions to the Sigmoid function, we can derive the output data range of the function is $S(\textbf{H})\in [\frac{1}{1 + e^{\frac{c}{\sqrt{D}}}}, \frac{1}{1 + e^{-\frac{1}{\sqrt{D}}}}]$. For the lower bound $\frac{1}{1 + e^{\frac{c}{\sqrt{D}}}}$, we can obtain:
\begin{equation}
\begin{aligned}
\underset{D\to \infty }{\text{lim}}\frac{1}{e^{\frac{c}{\sqrt{D}}}+1} &= \frac{1}{\underset{D\to \infty }{\text{lim}}\left(e^{c D^{-\frac{1}{2}}}+1\right)} \\ &= \frac{1}{\underset{D\to \infty }{\text{lim}}e^{c D^{-\frac{1}{2}}}+1} \\ &= \frac{1}{\exp \left(\underset{D\to \infty }{\text{lim}}c D^{-\frac{1}{2}}\right)+1} \\&= \frac{1}{\exp \left(\frac{c}{\underset{D\to \infty }{\text{lim}}\sqrt{D}}\right)+1} \\&= \frac{1}{\exp \left(\frac{c}{\sqrt{\underset{D\to \infty }{\text{lim}}D}}\right)+1} \\ &= \frac{1}{e^{\frac{c}{\sqrt{\infty }}}+1} = 0.5
\end{aligned}
\end{equation}
For the upper bound $\frac{1}{1 + e^{-\frac{1}{\sqrt{D}}}}$, we can obtain:
\begin{equation}
\begin{aligned}
\underset{D\to \infty }{\text{lim}}\frac{1}{e^{-\frac{1}{\sqrt{D}}}+1} &= \frac{1}{\underset{D\to \infty }{\text{lim}}\left(e^{-D^{-\frac{1}{2}}}+1\right)} \\ &= \frac{1}{\underset{D\to \infty }{\text{lim}}e^{-D^{-\frac{1}{2}}}+1} \\ &= \frac{1}{\exp \left(\underset{D\to \infty }{\text{lim}}-D^{-\frac{1}{2}}\right)+1} \\ &= \frac{1}{\exp \left(-\underset{D\to \infty }{\text{lim}}D^{-\frac{1}{2}}\right)+1} \\ &= \frac{1}{\exp \left(-\frac{1}{\underset{D\to \infty }{\text{lim}}\sqrt{D}}\right)+1} \\&= \frac{1}{\exp \left(-\frac{1}{\sqrt{\underset{D\to \infty }{\text{lim}}D}}\right)+1} \\ &= \frac{1}{e^{-\frac{1}{\sqrt{\infty }}}+1} = 0.5
\end{aligned}
\end{equation}
Finally, we can easily observe that $\underset{D\to \infty }{\text{lim}}\frac{1}{e^{\frac{c}{\sqrt{D}}}+1} = \underset{D\to \infty }{\text{lim}}\frac{1}{e^{-\frac{1}{\sqrt{D}}}+1}$ and thus prove Theorem 1 when $\sigma$ is ReLu, LeakyReLu or PReLu.
\subsection{Complexity Analysis}
\label{sec:complexity analysis}
The time complexity of our method consists of two components: the \textit{siamese GNN} and the \textit{loss computation}.
Existing self-supervised baselines share similar time complexity for the first component. In \texttt{GGD}, Given a graph $\mathcal{G}$ with $ N$ nodes and $ M$ edges in the sparse format, taking a GCN~\cite{kipf2016semi} encoder as an example, the time complexity of it is $ O(N + M)$. As we need to process both the augmented graph $\hat{\mathcal{G}}$ and the corrupted graph $\tilde{\mathcal{G}}$, \texttt{GGD}\ requires the encoder computation twice. Then, the projector network (i.e., MLP) with $ L$ linear layers will be applied to the encoder output, which takes $ O(ND)$ for each layer in computation. Here $ D$ is a parameter defining the hidden size. Before group discrimination, we aggregate the generated embedding with simple summation consuming $ O(ND)$.
For the loss computation, we use the BCE loss, i.e., Equation \ref{eq:binary DGI}, to category summarised node embeddings, i.e., scalars. The time complexity of this final step is $ O(2N)$ (i.e., processing all data samples from the positive and negative group). Ignoring the computation cost of the augmentation, the overall time complexity of \texttt{GGD}\ for computing a graph $\mathcal{G}$ is $ O(2(N+M+LND+ ND + N)) \rightarrow O(N+M+LND+ ND) \rightarrow O(LND)$, where we can see the time complexity is mainly contributed by the siamese GNN. More importantly, we compress the self-supervised learning loss computation to $ O(N)$ for a whole graph.
\subsection{Graph Power}
\label{sec:graph power}
To show the easiness of graph power computation, we conduct an experiment to evaluate the time consumption for graph power computation on eight datasets, whose statistics are shown in Appendix \ref{sec:dataset stat}. Specifically, we set the hidden size of $ \textbf{H}_{\theta}$ to 256, and $ n$ is fixed to 10 for all datasets. The experiment results are shown as below:
\begin{table}[htp]
\footnotesize
\centering
\caption{Graph power computation time in \underline{seconds} on eight benchmark datasets. The experiment is conducted using CPU: Intel Xeon Gold 5320. `Cite' , `Comp', `Photo', `Arxiv', `Products', `Papers' means Citeseer, Amazon Computer, Amazon Photo, ogbn-arxiv, ogbn-products and ogbn-papers100M.}
\begin{tabularx}{0.97\linewidth}{lp{1.4cm}<{\centering} p{1.4cm}<{\centering}p{1.4cm}<{\centering}p{1.4cm}<{\centering}p{1.4cm}<{\centering}p{1.4cm}<{\centering}p{1.4cm}<{\centering}}
\toprule
\textbf{Cora} & \textbf{Cite} &\textbf{PubMed} &\textbf{Comp} &\textbf{Photo} &\textbf{Arxiv} &\textbf{Products} & \textbf{Papers}\\
\midrule
5.4e-3& 7.3e-3 & 9.8e-3 & 1.2e-2 & 8.5e-3 & 2.2e-2 & 24.5 & 208.8 \\
\bottomrule
\end{tabularx}
\vspace{-2mm}
\end{table}
This table shows that the computation of graph power is very trivial on small and medium size graphs, e.g., ogbn-arxiv, which has million of edges, consuming only 0.22 seconds. Extending to an extremely large graph, ogbn-papers100M, which have over 1 billion edges and 11 million nodes, the computation only requires 209 seconds (i.e., around three minutes), which is acceptable considering the sheer size of the dataset.
\subsection{Dataset Statistics}
\label{sec:dataset stat}
The following table presents the statistics of eight benchmark datasets including five small to medium -scale datasets and three large-scale datasets from OGB Graph Benchmark\cite{hu2020open}.
\begin{table}[H]
\caption{The statistics of eight benchmark datasets.}
\footnotesize
\centering
\begin{tabularx}{0.67\linewidth}{lp{1.3cm}<{\centering} p{1.0cm}<{\centering} p{1.3cm}<{\centering}p{1.3cm}<{\centering}}
\toprule
\textbf{Dataset} & \textbf{Nodes} & \textbf{Edges} & \textbf{Features} & \textbf{Classes} \\ \midrule
\textbf{Cora} & 2,708 & 5,429 & 1,433 & 7 \\
\textbf{CiteSeer} & 3,327 & 4,732 & 3,703 & 6 \\
\textbf{PubMed} & 19,717 & 44,338 & 500 & 3 \\
\textbf{Amazon Computers} & 13,752 & 245,861 & 767 & 10 \\
\textbf{Amazon Photo} & 7,650 & 119,081 & 745 & 8 \\
\textbf{ogbn-arxiv} & 169,343 & 1,166,243 & 128 & 40 \\
\textbf{ogbn-products} & 2,449,029 & 61,859,140 & 100 & 47 \\
\textbf{ogbn-papers-100M} & 111,059,956 & 1,615,685,872 & 100 & 172 \\
\bottomrule
\end{tabularx}
\label{tab:dataset}
\end{table}
\subsection{Experiment Settings \& Computing Infrastructure}
\label{sec:exp setting}
\textbf{Extending to Extremely Large Datasets.} Extending to extremely large graphs (i.e., ogbn-products and ogbn-papers100M), we adopt a simple Neighbourhood Sampling strategy introduced in GraphSage~\cite{hamilton2017inductive} to decouple model training from the sheer size of graphs. Specifically, we create a fixed size subgraph for each node, which is created by sampling a predefined number of neighbours in each convolution layer for sampled nodes. The same approach is employed in the testing phase to obtain final embeddings.
\noindent\textbf{General Parameter Settings.}
In our experiment, we mainly tunes four parameters for \texttt{GGD}\ ,which are learning rate, hidden size, number of convolution layers in the GNN encoder, and number of linear layers in the projector. For simplicity, we set the n-th graph power for final embedding generation fixed to 10 for all datasets. The parameter setting for each dataset is shown below:
\begin{table}[H]
\caption{Parameter settings on eight datasets. `num-conv' and `num-proj' represent number of convolution layers in GNNs and number of linear layers in projector, respectively.}
\footnotesize
\centering
\begin{tabularx}{0.7\linewidth}{lp{1.1cm}<{\centering} p{1.0cm}<{\centering} p{1.5cm}<{\centering}p{1.5cm}<{\centering}}
\toprule
\textbf{Dataset} & \textbf{lr} & \textbf{hidden} & \textbf{num-conv} & \textbf{num-proj} \\ \midrule
\textbf{Cora} & 1e-3 & 256 & 1 & 1 \\
\textbf{CiteSeer} & 1e-5 & 512 & 1 & 1 \\
\textbf{PubMed} & 1e-3 & 512 & 1 & 1 \\
\textbf{Amazon Computers} & 1e-3 & 256 & 1 & 1 \\
\textbf{Amazon Photo} & 1e-3 & 1024 & 1 & 1 \\
\textbf{ogbn-arxiv} & 5e-5 & 1500 & 3 & 1 \\
\textbf{ogbn-products} & 1e-4 & 1024 & 4 & 4 \\
\textbf{ogbn-papers-100M} & 1e-3 & 256 & 3 & 1 \\
\bottomrule
\end{tabularx}
\label{tab:parameter setting}
\end{table}
\noindent \textbf{Large-scale Datasets Parameter Settings.}
To decouple model training from the scale of graphs, we adopt the neighbouring sampling technique, which has three parameters: batch size, sample size, number of hops to be sampled. Batch size refers to the number of nodes to be processed in one parameter optimisation step. Sample size means the number of nodes to be sampled in each convolution layer, and number of hops determines the scope of the neighbourhood for sampling. In \texttt{GGD}\ implementation, the batch size, sample size, and number of hops are fixed to 2048, 12 and 3, respectively.
\noindent \textbf{Memory and Training Time Comparison.} As memory and training time are very sensitive to hyper-parameters related to the structure of GNNs, including hidden size, number of convolution layers, and batch processing for large-scale datasets, e.g., batch size and number of neighbours sampled in each layer. Thus, in memory and training comparison, to be fair, we set all these parameters to be the same for all baselines and \texttt{GGD}. The specific parameter setting for each dataset is shown below:
\begin{table}[H]
\caption{Parameter settings on eight datasets for memory and training time comparison.}
\footnotesize
\centering
\begin{tabularx}{0.67\linewidth}{lp{1.0cm}<{\centering} p{1.2cm}<{\centering} p{1.0cm}<{\centering}p{1.5cm}<{\centering}}
\toprule
\textbf{Dataset} & \textbf{hidden} & \textbf{num-conv} & \textbf{batch} & \textbf{num-neigh} \\ \midrule
\textbf{Cora} & 512 & 1 & - & - \\
\textbf{CiteSeer} & 512 & 1 & - & - \\
\textbf{PubMed} & 256 & 1 & - & - \\
\textbf{Amazon Computers} & 256 & 1 & - & - \\
\textbf{Amazon Photo} & 256 & 1 & - & - \\
\textbf{ogbn-arxiv} & 256 & 3 & - & - \\
\textbf{ogbn-products} & 256 & 3 & 512 & 10 \\
\textbf{ogbn-papers-100M} & 128 & 3 & 512 & 10 \\
\bottomrule
\end{tabularx}
\label{tab:parameter time&memory}
\end{table}
\noindent \textbf{Computing Infrastructure.}
For experiments in section 3, 5 and 6.1, they are conducted using Nvidia GRID T4 (16GB memory) and Intel Xeon Platinum 8260 with 8 core. For experiments on large-scale datasets (i.e.,ogbn-arxiv, ogbn-products and ogbn-papers100M), we use NVIDIA A40 (48GB memory) and Intel Xeon Gold 5320 with 13 cores.
\section{Introduction}
\label{sec:intro}
\input{2Introduction}
\section{Rethinking Representative GCL Methods}
\label{sec:rethink}
\input{3Rethinking_GCL}
\section{Methodology}
\input{4Method}
\section{Exploring Group Discrimination}
\label{sec:explore gd}
\input{5Exploring_GD}
\section{Experiments}
\label{sec:experiment}
\input{7Experiment}
\section{Related Work}
\input{6Related_Work}
\section{Future Work}
\label{sec: future work}
\input{8Future_work}
{\small
\bibliographystyle{unsrt}
| {'timestamp': '2022-06-06T02:12:53', 'yymm': '2206', 'arxiv_id': '2206.01535', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01535'} | arxiv |
\section{Introduction}
Modern text generative models (TGMs) have demonstrated impressive results in generating texts close to the human level in terms of fluency, coherence, and grammar~\cite{keskar2019ctrl,zellers2019defending,brown2020language,rae2021scaling}. However, the misuse potential of TGMs increases with their capabilities to generate more human-like texts. Malicious users can deploy TGMs for spreading propaganda and fake news~\cite{zellers2019defending,uchendu-etal-2020-authorship,mcguffie2020radicalization}, augmenting fake product reviews~\cite{adelani2020generating}, and facilitating fraud, scams, and other targeted manipulation~\cite{DBLP:journals/corr/abs-2112-04359}. The increasing difficulty for laypeople and users to discriminate machine-generated texts from human-written ones facilitates the spread of such misuse~\cite{karpinska-etal-2021-perils,uchendu-etal-2021-turingbench-benchmark}. This motivates the \textit{artificial text detection} task~\cite{jawahar-etal-2020-automatic}, a fast-growing niche field aimed at mitigating the misuse of TGMs.
The Russian Artificial Text Detection (RuATD) shared task explores the problem of artificial text detection in Russian. Unlike existing datasets for English, our approach includes a range of task-specific TGMs, that is, models fine-tuned for common text generation tasks at the sentence- and document-level. On the one hand, such a setting challenges the participants and crowd-sourced annotators. On the other hand, it also enables many research and development purposes, such as training and benchmarking artificial text detectors, warning users about potentially fake content on social media and news platforms, filtering corpora augmented with TGMs, exploring detectors' robustness w.r.t. TGMs' architecture, size, downstream task, or domain. The shared task dataset consists of publicly available texts across multiple domains and texts generated by various monolingual and cross-lingual TGMs. The setup includes two sub-tasks: (i) to determine if a given text is automatically generated or written by a human (binary classification), and (ii) to identify the author of a given text (multi-class classification).
The main contributions of this paper are the following:
\begin{enumerate}
\item We propose a diverse automatic text detection corpus in Russian, the first of its kind (\S \ref{subsection:data});
\item We model two competition sub-tasks (\S \ref{subsection:tasks}) after the traditional concepts of ``Turing test'' and authorship attribution for neural text generation models~\cite{uchendu-etal-2021-turingbench-benchmark}. We establish two count-based and neural-based baseline solutions (\S \ref{subsection: baseline}) and the human evaluation on the binary classification problem (\S \ref{subsection:human benchmark});
\item We conduct an extensive analysis of the received submissions for both sub-tasks (\S \ref{section:results}) and discuss potential research directions (\S \ref{section:disc});
\item We set up the shared task environment, which remains open for the community submissions to facilitate future research in the area (\S \ref{subsection:kaggle}).
\end{enumerate}
\section{Dataset}
\begin{figure*}[ht!]
\includegraphics[width=\linewidth]{images/scheme.pdf}
\caption{Data collection, text generation, and post-processing procedure.}
\label{fig:scheme}
\end{figure*}
\subsection{Text Generation}
The corpus includes texts from 14 text generators, i.e., one human writer and 13 monolingual/multilingual TGMs varying in their number of parameters, architecture choices, and pre-training objectives. Each model is fine-tuned for one or more of the following text generation tasks: MT, paraphrase generation, text simplification, and text summarization. We also consider back-translation and zero-shot generation approaches. Figure~\ref{fig:scheme} outlines the dataset creation pipeline. Text generation hyperparameters for each model are presented in \ref{tab:gen-params}. Note that we mostly use the default hyperparameters under the considered libraries.
\input{tables/hyperparameters}
\noindent{\bf Human} We collect human-written texts from publicly available resources among six domains (see Section~\ref{subsection:data} for more details). Gold standard references from task-specific datasets are also used as human texts, since they are generally written and/or validated by crowd-source annotators~\cite{artetxe-schwenk-2019-massively,schwenk-etal-2021-wikimatrix,scialom-etal-2020-mlsum,hasan-etal-2021-xl}. The human texts serve as the input to the TGMs.
\noindent{\bf MT \& Back-translation} We use three MT models via the \texttt{EasyNMT} framework\footnote{\href{https://github.com/UKPLab/EasyNMT}{\texttt{github.com/UKPLab/EasyNMT}}}: OPUS-MT~\cite{tiedemann-thottingal-2020-opus}, M-BART50~\cite{tang2020multilingual}, and M2M-100~\cite{fan2020englishcentric}. We use subsets of the Tatoeba~\cite{artetxe-schwenk-2019-massively} and WikiMatrix~\cite{schwenk-etal-2021-wikimatrix} datasets to obtain translations among three language pairs: English-Russian, French-Russian, and Spanish-Russian. In the back-translation setting, the input sentence is translated into one of the target languages, and then back into Russian.
\noindent{\bf Paraphrase Generation} Paraphrases are generated with models available under the \texttt{russian-paraphrasers} library~\cite{fenogenova-2021-russian}: ruGPT2-Large\footnote{\href{https://huggingface.co/sberbank-ai/rugpt2large}{\texttt{hf.co/sberbank-ai/rugpt2large}}}, ruT5-Base-Multitask\footnote{\href{http://huggingface.co/cointegrated/rut5-base-paraphraser}{\texttt{hf.co/cointegrated/rut5-base-multitask}}}, and mT5~\cite{xue-etal-2021-mt5} of Small and Large versions.
\noindent{\bf Text Simplification} We fine-tune ruGPT3-Small\footnote{\href{https://huggingface.co/sberbank-ai/rugpt3small_based_on_gpt2}{\texttt{hf.co/sberbank-ai/rugpt3small}}}, ruGPT3-Medium\footnote{\href{https://huggingface.co/sberbank-ai/rugpt3medium_based_on_gpt2}{\texttt{hf.co/sberbank-ai/rugpt3medium}}}, ruGPT3-Large\footnote{\href{https://huggingface.co/sberbank-ai/rugpt3large_based_on_gpt2}{\texttt{hf.co/sberbank-ai/rugpt3large}}}, mT5-Large, and ruT5-Large\footnote{\href{https://huggingface.co/sberbank-ai/ruT5-large}{\texttt{hf.co/sberbank-ai/rugt5-large}}} for text simplification on a filtered version of the RuSimpleSentEval-2022 dataset~\cite{sakhovskiy2021rusimplesenteval,fenogenovatext}. Fine-tuning of each model is run for $4$ epochs with the batch size of $4$, learning rate of $10^{-5}$, and weight decay of $10^{-2}$.
\noindent{\bf Text Summarization} We use two abstractive summarization models fine-tuned on the Gazeta dataset~\cite{Gusev2020gazeta}: ruT5-base\footnote{\href{https://huggingface.co/IlyaGusev/rut5_base_sum_gazeta}{\texttt{hf.co/IlyaGusev/rut5-base-sum-gazeta}}} and M-BART\footnote{\href{https://huggingface.co/IlyaGusev/mbart_ru_sum_gazeta}{\texttt{hf.co/IlyaGusev/mbart-ru-sum-gazeta}}}.
\noindent{\bf Zero-shot Generation} We generate texts in a zero-shot manner by prompting the model and specifying the maximum number of generated tokens. The models include ruGPT3-Small, ruGPT3-Medium, ruGPT3-Large.
\subsection{Data}
\label{subsection:data}
Pre-training corpora of TGMs can cover multiple versatile domains~\cite{liu2020survey}, which prompt their abilities to generate texts with specific lexical, syntactic, discourse and stylistic properties. Despite this, the ATD task is generally explored w.r.t. only one particular domain, e.g., product reviews ~\cite{adelani2020generating}, social media posts~\cite{fagni2021tweepfake}, or news~\cite{uchendu-etal-2021-turingbench-benchmark}. Such setting limits the scope of evaluation of artificial text detectors. A few studies show that performance of modern detectors can vary drastically across domains~\cite{bakhtin2019real,kushnareva-etal-2021-artificial}, which stimulates the development of more generalizable and robust methods~\cite{jawahar-etal-2020-automatic}.
This paper aims at providing a diverse shared task data, taking into account the current limitations in the niche ATD field, and the diversity of TGMs widely used in the industry and NLP research for Russian. To this end, we consider domains which represent normative Russian, as well as general domain texts, social media posts, texts of different historical periods, bureaucratic texts with complex discourse structure and embedded named entities, and other domains included in the task-specific datasets, such as subtitles and web-texts. Recall that aside from linguistic and stylometric properties, texts differ in their length (e.g., sentence-level vs. document-level), and specifics attributable to the downstream tasks. We now list domains of texts that are fed into the previously described TGMs.
\noindent{\bf Russian National Corpus} We use the diachronic sub-corpora of the Russian National Corpus\footnote{\href{https://ruscorpora.ru/old/en/index.html}{\texttt{ruscorpora.ru}}} (RNC), which covers three historical periods of the society and the Modern Russian language (``pre-Soviet'', ``Soviet'', and ``post-Soviet'').
\noindent{\bf Social Media} We parse texts from multiple social media platforms that are marked with certain hashtags, such as dates, months, seasons, holidays, the names of large cities in Russia, etc. These texts are typically short, written in informal style and may contain emojis and obscene lexis.
\noindent{\bf Wikipedia} We select the top-100 most viewed Russian Wikipedia pages spanning the period of 2016-2021 according to the PageViews\footnote{\url{https://pageviews.wmcloud.org/}} statistics.
\noindent{\bf News Articles} The news segment covers different news sources in the Taiga corpus~\cite{shavrina2017methodology} and the \texttt{corus} library\footnote{\href{https://github.com/natasha/corus}{\texttt{github.com/natasha/corus}}}, including but not limited to Lenta, KP, Interfax, Izvestia, Gazeta. We additionally parse more recent news articles to prevent potential data leakage and cheating.
\noindent{\bf Prozhito Diaries} Prozhito is a corpus of digitilized personal diaries, written during the 20th century~\cite{melnichenko2017prozhito}.
\noindent{\bf Strategic Documents} are produced by the Ministry of Economic Development of the Russian Federation. The documents are written in bureaucratic style, rich in embedded entities, and have complex syntactic and discourse structure. This dataset has been previously used in the RuREBus shared task \cite{rurebus}.
\subsection{Post-processing} Each generated text undergoes a post-processing procedure based on a combination of language processing tools and heuristics. First, we discard duplicates, copied inputs, empty outputs, and remove special tokens from the generated texts (e.g., \texttt{<s>}, \texttt{</s>}, \texttt{<pad>}, etc.). Next, we empirically define length intervals for each generation task based on a manual analysis of length distributions in \texttt{razdel}\footnote{\href{https://github.com/natasha/razdel}{\texttt{github.com/natasha/razdel}}} tokens. The texts are filtered by the following token ranges: 5-to-25 (\textbf{MT, Back-translation, Paraphrase Generation}), 10-to-30 (\textbf{Text Simplification}), 15-to-60 (\textbf{Text Summarization}), and 85-to-400 (\textbf{Zero-shot Generation}). We additionally discard the social media texts containing obscene lexis according to the corpus of Russian obscene words\footnote{\href{https://github.com/odaykhovskaya/obscene_words_ru}{\texttt{github.com/odaykhovskaya/obscene-words}}}, and keep the MT/Back-translation texts classified as Russian with the confidence of more than $0.9$ (\texttt{langdetect}\footnote{\href{https://github.com/fedelopez77/langdetect}{\texttt{github.com/fedelopez77/langdetect}}}).
\section{Dataset Statistics}
This section describes various count-based statistics of our dataset for human-written and machine-generated texts.
\noindent{\bf General Statistics} \autoref{tab:tgms} shows general dataset statistics w.r.t. text generation task, text generator, and domain. On average, there are $37.9$ tokens in each text, with variations depending on the task. We estimate the frequency of each text according to the Russian National Corpus (RNC)\footnote{\href{http://ruscorpora.ru/new/en/}{\texttt{ruscorpora.ru/new/en}}}. It is computed as the number of frequently used tokens (i.e., the number of instances per million, that is, IPM in RNC is higher than $1$) divided by the number of tokens in a sentence. The average IPM is $0.86$ for the human-written texts and $0.87$ for the machine-generated ones.
\input{tables/corpus_table/corpus_table_longtable.tex}
\noindent{\bf Diversity Metrics} We estimate the diversity of the texts in terms of their k-gram statistics and lexical richness. We calculate two diversity metrics upon $k$-gram statistics: Dist-$k$~\cite{li-etal-2016-diversity} and Ent-$k$~\cite{zhang2018generating}. Dist-$k$ is the total number of k-grams divided by the number of tokens in the text set. Ent-$k$ is an entropy metric that weights each k-gram so infrequent k-grams are penalized and contribute less to diversity. We compute the diversity scores for texts grouped by label and report them for $k \in \{1, 2, 4\}$ in \autoref{tab:dist-ent}.
\input{tables/dist-ent}
\noindent{To} measure the lexical diversity\footnote{\href{https://github.com/LSYS/LexicalRichness}{\texttt{Lexical richness}}} of the texts in our dataset, we calculate four types of metrics: word count, terms count, type-token ratio (TTR), and corrected type-token ratio (CTTR). Type-token ratio is computed as $t/w$ and corrected type-token ratio is computed as $t/\sqrt{2 * w}$, where $t$ is the number of unique terms/vocabulary, and $w$ is the total number of words.
\input{tables/lex_rich}
We can see that the ratio of the diversity measures between the natural and artificial texts depends on the task, which is explained by the very task formulation. At the same time, artificial texts may include non-existent words, degenerated textual segments, or rare words, which can be attributed to more significant lexical richness metrics overall.
\section{Setup}
\subsection{Tasks} \label{subsection:tasks}
The RuATD Shared task features two sub-tasks:
\begin{enumerate}
\item[I.] Determine if a given text is automatically generated or written by a human. This sub-task is framed as a binary classification problem with two labels: \textbf{H} (human) and \textbf{M} (machine).
\item[II.] Identify the author of a given text. This sub-task is modeled after the traditional problem of authorship attribution~\cite{coyotl2006authorship}, particularly in the context of neural models~\cite{uchendu-etal-2020-authorship}. It is a multi-class classification problem with 14 target classes -- a human writer and 13 TGMs.
\end{enumerate}
\noindent{\bf Evaluation} Each sub-task uses the accuracy score, a standard metric for classification with balanced classes, as the official evaluation metric.
\subsection{Dataset Splits}
We split the dataset into four sets in the 60/10/15/15 proportion ratio: train (130k), development (21k), public test (32k), and private test (32k). Each set is balanced by the number of target classes, text generator, text generation task, and domain\footnote{The number of human-written texts is equal to the number of machine-generated texts for each domain and text generation task.}. These sets are used for both sub-tasks, with only the target classes changed, i.e., the \textbf{M} label is broken into 13 TGMs' names in the multi-class sub-task.
\subsection{Kaggle Setup} \label{subsection:kaggle}
We use the Kaggle competition platform to run the shared task. The sub-tasks are set as separate competitions and leaderboards:
\begin{enumerate}
\item[I.] The binary sub-task \href{https://www.kaggle.com/competitions/ruatd-2022-bi/host/settings}{is hosted under this link};
\item[II.] The multi-class sub-task \href{https://www.kaggle.com/competitions/ruatd-2022-multi-task}{is hosted under this link}.
\end{enumerate}
The participants are allowed to take part solely or in teams in both sub-tasks. The shared task comprises two stages: \textbf{public} and \textbf{private} testing. The first stage provides access to the public test set and leaderboard, allowing the participants to develop and improve their submissions during the competition. The second stage defines the final leaderboard ranking on the private test set, scoring up to three submissions selected by the participants. Otherwise, the Kaggle platform automatically selects the three best submissions based on the participants' public test scores.
Participants are allowed to use any additional materials and pre-trained models, except for direct markup of the test set and search on the Internet.
\subsection{Baseline}
\label{subsection: baseline}
We provide the participants with two open-source baseline solutions: count-based (TF-IDF baseline) and BERT-based (BERT baseline)~\cite{devlin-etal-2019-bert}. TF-IDF baseline is based on TF-IDF features coupled with the SVD dimensionality reduction and a Logistic Regression classifier. The TF-IDF has 50k features, further reduced to 5000 by SVD. The BERT baseline follows the default fine-tuning and evaluation procedure for the classification task under the HuggingFace transformers framework~\cite{wolf-etal-2020-transformers}.
\subsection{Peer Review}
Each participant is asked to publicly release their solutions and peer review other participants' submissions. This step allows for a fair evaluation, eliminating the risks of potential cheating, such as solving the sub-tasks via a web search or other heuristics. After analyzing the assigned submission, the peer-reviewer should answer two questions in the Google form and provide comments, if any:
\begin{itemize}
\item Does the submission use a web search?
\item Does the submission violate any other rules\footnote{The shared task rules are provided \href{https://github.com/dialogue-evaluation/RuATD/blob/main/en_README.md}{in the GitHub repository}.} of the shared task?
\end{itemize}
\subsection{Human Baseline}
\label{subsection:human benchmark}
\begin{figure*}[t!]
\includegraphics[width=\linewidth]{images/toloka_one_sample.png}
\caption{An example of the Toloka interface for the human evaluation setup.}
\label{fig:tolokasetup}
\end{figure*}
We conduct a human evaluation on the binary classification problem using stratified sub-samples from the public and private test sets. Each subset of 2.5k samples is balanced by the number of target classes, text generator, text generation task, and domain. We report the human baseline results during both public and private testing stages. The evaluation is run via the Toloka platform. The annotation setup follows the conventional crowd-sourcing guidelines for the ATD task and accounts for methodological limitations discussed in ~\cite{ippolito2020automatic,clark-etal-2021-thats,karpinska-etal-2021-perils}. We provide a full annotation instruction in Figure~\ref{fig:toloka_instruction} (see Appendix~\ref{section:appendix}), and an example of the Toloka interface in Figure~\ref{fig:tolokasetup}.
We grant access to the human evaluation project to only top-$70$\% annotators according to the in-house Toloka rating system. Each annotator must first finish the training task by completing at least $80$\% of samples correct to get onto the main annotation task. We use the dynamic overlap of $3$-to-$5$ annotators per sample. We discard votes from those annotators whose quality rate on the control tasks is less than $50$\%. We also filter out votes with the response time of less than $15$ seconds per annotation task page (5 samples). The resulting vote is aggregated as the majority vote label.
\section{Results and Analysis}
\label{section:results}
We report the official shared task results of the private testing stage in \autoref{tab:leaderboards}. Only peer-reviewed submissions (marked with \checkmark in the Table) are considered official.
\input{tables/leaderboards/leaderboards_longtable.tex}
As one can notice from Table, top-4 systems in the binary classification task have been peer-reviewed. In the multi-class setting, all four top-4 systems have been also peer-reviewed.
The results demonstrate that state-of-the-art classification models can be relatively successful in distinguishing human-written texts from machine-generated ones for the Russian language and determining the exact model used for generation for the latter class. However, one can quickly notice a rather stark contrast between the best scores obtained on the RuATD test set in binary setup (0.830 accuracy for \textit{MSU}, the top-system in binary classification task) and scores obtained for a similar setup in English (0.970 accuracy; see ~\cite{uchendu-etal-2020-authorship} for reference). We attribute this contrast not to the difference in the languages but mainly to the nature of texts: in the English setup, an average text length is 432 words (compared to 31 in RuATD). This claim can be validated by splitting evaluation scores of the best binary RuATD models by length: on the texts longer than 23 words (about a quarter of all RuATD texts), top models can score over 0.95 accuracy.
Unsurprisingly all models that can outperform our BERT baseline used fine-tuned language models (LMs) from the BERT family. Specific models that can achieve the best scores on the test set are mDeBERTa~\cite{he2021debertav3}, and Russian-language implementations of RoBERTa~\cite{liu2019roberta}. Top models experiment with learning-rate scheduling as well as other training techniques (e.g., adversarial training with fast-gradient method ~\cite{dong2018boosting}, or child-tuning training ~\cite{xu2021raise}).
Using additional features (e.g., lexical richness, perplexity, number of characters, number of sentences, TF-IDF of POS tags, punctuation, tonality, reading ease) provided only limited benefit. While there are competitive solutions with such features (e.g., \textit{mariananieva}, 4th-placed solution in the binary setup), none of the three best models in either task used any additional features.
Ensembling models proved to be beneficial, although competitive results could be achieved using single models. For example, \textit{Posokhov Pavel}, the best model in the multi-class setup task, does not use the ensembling of any kind, nor does \textit{orzhan}, the third-placed model in both tasks.
\noindent{\textbf{Human Baseline}} The overall accuracy of the human evaluation is $0.66$, which scores below the BERT baseline. The low results are consistent with recent studies~\cite{karpinska-etal-2021-perils,uchendu-etal-2021-turingbench-benchmark}, which underpin the difficulty of the task for crowd-sourcing annotators. These works advise hiring experts trained to evaluate written texts or conduct multiple crowd-sourcing evaluation setups with extensive training phases. We leave the human evaluation experiments for future work.
\section{Discussion}
\label{section:disc}
\noindent{\textbf{On indistinguishable examples}} The reasons for the errors of various systems on the RuATD corpus are of separate research interest. A short meaningful sentence of frequency n-grams may often occur in a web-corpus and be easily reproduced by a simple statistical LM. Thus, the very definition of a specific automatic text can be a challenging task for an attentive annotator and even for an engineer directly involved in developing TGMs. This can be illustrated, for example, by the case of Ilya Sutskever from the GPT-3 project, who tweeted spring of 2022, that \textit{large neural networks may be ``slightly conscious.''}\footnote{\href{https://towardsdatascience.com/openais-chief-scientist-claimed-ai-may-be-conscious-and-kicked-off-a-furious-debate-7338b95194e}{https://towardsdatascience.com}}. The methodological problem of obtaining some significant phrases or texts randomly using LMs, however, is raised much earlier than the onset of ``indistinguishability by the engineers themselves'': critical works on the Turing test~\cite{turing1950computing} offer various variations of tests that level this problem. For example, \cite{bringsjord1996inverted} explicitly note that a state machine that generates random sentences could be randomly considered meaningful by a judge in a good mood.
In general, various methodological variations offer 1) interactive work with models/people, checking the maintenance of the context~\cite{kugel1990time} and even the consistency of the author's ``cognitive profile''~\cite{watt1996naive}. These areas can be considered topics for future work for the following shared tasks.
\noindent{\textbf{Ethical considerations}} Setting the task of detecting non-human texts is timely due to the rapid development of LMs. The very issue of detecting non-human texts affects the fundamental right of the user to understand when they interact with a subjectless technological solution and when - with a person. Problems of this kind are actively discussed in reviews of recent years. In particular, \cite{https://doi.org/10.48550/arxiv.2108.07258} define the scope of problems as: \begin{enumerate}
\item foundation model misuse, including both purposeful generated text misuse and the unconditional reliance on automatic text classification results that can be false negative;
\item development of legal grounds to mitigate generative model misuse and detection model misuse;
\item widespread deployment of automatic text detection systems: the presented models can lead to an "arms race" between malicious content generators and detectors.
\end{enumerate}
Although the improvement of language modeling is undoubtedly a fundamental task of machine learning, we are of the position that a thorough study of models that classify automatic texts is necessary. As practice shows, the percentage of their errors in the Russian language is non-zero.
\section{Related Work}
Many research efforts are related to natural language generation (NLG) models. These works can be characterized into two broad categories - (i) training LMs on large-scale data and (ii) learning to distinguish between machine-authored and human-written content. \cite{jawahar-etal-2020-automatic} provides a good survey on the automatic detection of machine-generated text for English.
Prior work has focused on training classifiers on samples from a model \cite{brown2020language} and directly using a model distribution \cite{gehrmann2019gltr}. \cite{gehrmann2019gltr} propose a visual and statistical tool named GLTR for the detection of generation artifacts across different sampling schemes. \cite{ippolito2020automatic} compare human raters and automatic classifiers depending on the decoding strategy. They observe that classifiers can detect statistical artifacts of generated sequences while humans quickly notice semantic errors. Classifier accuracy ranges between 70\% and 90\% depending on the decoding strategy for short texts (64 tokens). \cite{dugan2020roft} propose a RoFT (Real or Fake Text) tool to detect the boundary between a human-written text passage and machine-generated sentences showing NLG models are capable of fooling humans by one or two sentences. A recent study of \cite{galle2021unsupervised} focuses on the unsupervised detection of machine-generated documents leveraging repeated higher-order n-grams. They show that specific well-formed phrases over-appear in machine-generated texts as compared to human ones. \cite{mccoy2021much} propose a suite of analyses called RAVEN for assessing the novelty of generated text, focusing on sequential structure (n-grams) and syntactic structure. Experiments show that random sampling result in generated text with a more significant number of novel n-grams.
Recent studies \cite{carlini2022quantifying,lee2022language} have raised a concern about model memorization due to data privacy leakage. \cite{carlini2022quantifying} confirm that memorization scales with model size and current LMs do accurately model the distribution of their training data. \cite{lee2022language} investigate memorization and plagiarism when generating artificial texts. They observe that fine-tuned LMs demonstrate different patterns of plagiarism based on characteristics of auxiliary data. \cite{schuster2020limitations} propose two benchmarks demonstrating the stylistic similarity between malicious and legitimate uses of LMs.
\cite{liyanage2022benchmark} propose a benchmark for detecting
automatically generated research content that consists of a synthetic dataset and a partial text substitution dataset. The latter is created by replacing several sentences of abstracts with sentences generated by an NLG model. \cite{stiff2021detecting} adopt a wide variety of datasets of news articles, product reviews, forum posts, and tweets and investigated several classifiers to predict whether a text has been automatically generated. Their experiments show that classifiers perform reasonably accurately in the news domain, while the same task is more challenging for shorter social media posts.
\section{Conclusion}
\label{section:conclusion}
We presented RuATD shared task, the first shared task on artificial text detection for the Russian language. As a result of the competition, 38 solutions have been obtained, solving the problem in two tasks modeled after the traditional concepts of the Turing test and authorship attribution for NLG methods.
The best solution of the shared task has achieved
\begin{itemize}
\item 83.0\% accuracy in a binary task setup;
\item 65.0\% accuracy in a multi-class task setup.
\end{itemize}
The shared task dataset, codebase, human evaluation results, participant solutions, and other materials are now available online under Apache 2.0 license\footnote{\href{https://github.com/dialogue-evaluation/RuATD}{https://github.com/dialogue-evaluation/RuATD}}.
The competition problem can be further treated as a Turing test in a non-interactive setting.
First of all, its direct methodological extensions are possible in such applied areas as:
\begin{itemize}
\item dialogue systems, and
\item applications for editors and writers.
\end{itemize}
Another direction for future work is to conduct a critical study on the human evaluation guidelines on artificial text detection, which is still an open methodological question in the field~\cite{karpinska-etal-2021-perils}. We welcome the communities of NLP developers, linguists, and engineers to contribute to further research in the area and next criteria formulations.
\section*{Acknowledgments}
The experiments were partially carried out on computational resources of HPC facilities at HSE University \cite{kostenetskiy2021hpc}. Ekaterina Artemova and Marat Saidov were supported by the framework of the HSE University Basic Research Program.
| {'timestamp': '2022-06-06T02:14:53', 'yymm': '2206', 'arxiv_id': '2206.01583', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01583'} | arxiv |
\section{Introduction}
Given examples and background knowledge (BK), the goal of inductive logic programming (ILP) \cite{mugg:ilp} is to find a set of rules (a logic program
) which with the BK correctly generalises the examples.
The fundamental challenge is to efficiently search a large hypothesis space (the set of all programs) for a \emph{solution} (a program that correctly generalises the examples).
The two main approaches are \emph{divide-and-conquer} (D\&C{}) and \emph{separate-and-conquer} (S\&C{}).
D\&C{} approaches \cite{tilde} divide the examples into disjoint sets and search for a program for each set.
S\&C{} approaches \cite{progol} search for a program that generalises a subset of the examples, separate these examples, and then search for more rules to add to the program to generalise the remaining examples.
These two approaches support noise and learning programs with many rules and literals.
However, as they only learn from a subset of the examples, they struggle to learn recursive programs.
Moreover, these approaches offer no guarantees about the optimality of their solutions and can learn overly specific programs.
Finally, these systems cannot perform predicate invention \cite{stahl:pi}.
Many modern approaches \cite{aspal,mugg:metagold,dilp,hexmil,popper,meta_abduce} overcome these limitations through meta-level search \cite{ilp30} and can learn optimal and recursive programs.
However, most modern approaches struggle to learn programs with many literals in a rule, many rules in a program, or both.
For instance, \textsc{ASPAL}{} \cite{aspal} precomputes every possible rule in a program and uses an answer set solver to find a subset of rules that generalises the examples.
However, this precomputation rule selection approach does not scale to rules with more than a few literals \cite{ilasp,hexmil,prosynth}.
Likewise, many modern systems struggle to learn programs with many rules \cite{mugg:metagold,dilp,popper,hopper}.
In this paper, our goal is to overcome the limitations of modern systems yet maintain the ability to learn recursive and optimal programs and support predicate invention.
The three key ideas are to (i) decompose programs into \emph{non-separable} fragments, (ii) learn fragments separately, and (iii) \emph{combine} fragments to learn programs with many rules and literals.
A non-separable program cannot be decomposed into smaller parts.
For instance, consider this program:
\[
\begin{array}{l}
p_1 : \left\{
\begin{array}{l}
\emph{happy(A) $\leftarrow$ rich(A)}\\
\emph{happy(A) $\leftarrow$ friend(A,B), famous(B).}\\
\emph{happy(A) $\leftarrow$ married(A,B), beautiful(B)}\\
\end{array}
\right\}
\end{array}
\]
This program has three rules that can be evaluated independently.
In other words, if we learn the three rules separately and union their individual logical consequences, we have a program that is logically equivalent to $p_1$.
This program is, therefore, a \emph{separable} program.
By contrast, consider this program:
\[
\begin{array}{l}
p_2 : \left\{
\begin{array}{l}
\emph{happy(A) $\leftarrow$ rich(A)}\\
\emph{happy(A) $\leftarrow$ married(A,B), happy(B)}\\
\end{array}
\right\}
\end{array}
\]
This program has two rules that cannot be evaluated independently as it has a recursive rule.
In other words, if we learn the two rules separately and union their individual logical consequences, we have a program that is logically different to $p_2$.
It is, therefore, a \emph{non-separable} program.
By decomposing programs into smaller non-separable fragments, we want to make them easier to learn and thus reduce learning times.
To explore these ideas, we build on the \emph{learning from failures} (LFF) \cite{popper} approach.
LFF frames the ILP problem as a constraint satisfaction problem.
The goal of an LFF learner, such as \textsc{Popper}{}, is to accumulate constraints in a generate, test, and constrain loop.
In other words, \textsc{Popper}{} continually generates programs, tests them on examples, and, if they are not solutions, builds constraints to explain why they are not solutions to guide future program generation.
To improve learning performance, we add the three new previously mentioned ideas to LFF.
We describe our approach with an example.
\subsubsection*{Motivating example}
Suppose we have positive and negative examples of lists of numbers of arbitrary length.
We want to learn a program to say whether an unseen list is good or bad.
We might want to learn a program such as:
\[
\begin{array}{l}
h_0 : \left\{
\begin{array}{l}
\emph{f(A) $\leftarrow$ head(A,7)}\\
\emph{f(A) $\leftarrow$ head(A,4), tail(A,B), head(B,4)}\\
\emph{f(A) $\leftarrow$ head(A,23), tail(A,B), head(B,24)}\\
\emph{f(A) $\leftarrow$ tail(A,B), f(B)}
\end{array}
\right\}
\end{array}
\]
\noindent
This program says that a list is good if it contains the sequence [7] or [4,4] or [23,24].
The last rule is important.
It is a recursive rule that allows the program to generalise to lists of arbitrary length.
To find a program that generalises the examples, we use a \emph{generate}, \emph{test}, \emph{combine}, and \emph{constrain} loop.
In the generate stage, we generate progressively larger programs, i.e. programs with one literal, two literals, etc.
Importantly, in this step, we only generate non-separable programs.
For this example, we would start by generating programs such as $h_1$ and $h_2$:
\[
\begin{array}{l}
h_1 : \left\{
\begin{array}{l}
\emph{f(A) $\leftarrow$ head(A,1)}\\
\end{array}
\right\}\\
h_2 : \left\{
\begin{array}{l}
\emph{f(A) $\leftarrow$ head(A,5)}\\
\end{array}
\right\}
\end{array}
\]
\noindent
In the test stage, we test each program on the examples.
If a program entails a negative example, we build a \emph{generalisation} constraint to eliminate more general programs from the hypothesis space as they will also entail the negative example.
For instance, if we have the negative example \emph{f([5,5,5])} we would eliminate $h_2$ from the hypothesis space and anything more general than it, such as:
\[
\begin{array}{l}
h_3 : \left\{
\begin{array}{l}
\emph{f(A) $\leftarrow$ head(A,5)}\\
\emph{f(A) $\leftarrow$ head(A,7)}\\
\end{array}
\right\}
\end{array}
\]
If a program entails no negative examples, we build a \emph{specialisation} constraint to eliminate more specific programs from the hypothesis space, as they will also not cover any positive example.
For instance, if we do not have a positive example where the first element is 5, we prune all specialisations of $h_2$, such as
\[
\begin{array}{l}
h_4 : \left\{
\begin{array}{l}
\emph{f(A) $\leftarrow$ head(A,5), tail(A,B), head(B,9)}
\end{array}
\right\}
\end{array}
\]
\noindent
A key novelty of our approach is the combine stage.
If a program entails \emph{at least one} positive and none of the negative examples, we add the program to a set of \emph{candidate} programs.
Candidate programs are non-separable programs that we want to combine.
For instance, when considering programs of size 5, we might generate the recursive program:
\[
\begin{array}{l}
h_5 : \left\{
\begin{array}{l}
\emph{f(A) $\leftarrow$ head(A,7)}\\
\emph{f(A) $\leftarrow$ tail(A,B),f(B)}\\
\end{array}
\right\}
\end{array}
\]
As $h_5$ covers at least one positive example and no negative examples we deem it a candidate program.
In the combine stage, we search for a combination of candidate programs that covers all the positive examples and that is minimal in size.
If we do not find a combination, we go to the constrain stage, where we use the discovered generalisation and specialisation constraints to generate a new program.
If we find a combination, we deem it the best solution so far.
For instance, suppose that after considering programs of size 7 we see the programs:
\[
\begin{array}{l}
h_6 : \left\{
\begin{array}{l}
\emph{f(A) $\leftarrow$ head(A,4), tail(A,B), head(B,4)}\\
\emph{f(A) $\leftarrow$ tail(A,B),f(B)}\\
\end{array}
\right\}\\
h_7 : \left\{
\begin{array}{l}
\emph{f(A) $\leftarrow$ head(A,23), tail(A,B), head(B,24)}\\
\emph{f(A) $\leftarrow$ tail(A,B),f(B)}\\
\end{array}
\right\}
\end{array}
\]
\noindent
Then the combination of $h_5 \cup h_6 \cup h_7$ is $h_0$ (the solution we want to learn).
We have, therefore, learned a program with 4 rules and 13 literals by only considering programs with 2 rules and 7 literals.
As we show in our experiments, this decomposition and recombination of programs allows us to learn programs much faster than existing approaches.
As this point, we have has not yet proven that the combination is optimal in terms of program size.
In other words, we have not yet proven that there is no smaller solution.
Therefore, to avoid over-fitting, we continue to the constrain stage and add a constraint on the maximum program size in the generate stae (12 literals) for future iterations.
We repeat this loop until we prove the optimality of a solution.
\paragraph{Contributions.}
\begin{itemize}
\item We introduce a generate, test, combine, and constrain ILP approach.
\item We implement our ideas in \textsc{Popper+}{}, a new ILP system.
\textsc{Popper+}{} uses an answer set programming (ASP) solver \cite{clingo} to generate programs that do not violate constraints.
\textsc{Popper+}{} uses a separate ASP solver to search for combinations of non-separable programs.
To learn programs with complex data structures and continuous values, \textsc{Popper+}{} uses Prolog to test programs\footnote{\textsc{Popper+}{} can also ASP to test programs if the programs only need Datalog programs.}
\textsc{Popper+}{} learns optimal, recursive, and large programs and supports predicate invention.
\item We experimentally show on three domains (classification, inductive general game playing, and program synthesis) that our approach can substantially outperform other ILP systems, especially in terms of learning times.
\end{itemize}
\section{Related work}
\textbf{D\&C{}.}
\textsc{TILDE}{} \cite{tilde} is a D\&C{} approach.
\textsc{TILDE}{} extends decision tree learning algorithms to learn first-order, rather than propositional, rules.
Although \textsc{TILDE}{} can learn large programs and scale to large datasets, it cannot learn recursive programs and struggles to learn from small numbers of examples.
\textbf{S\&C{}.}
Progol is a S\&C{} approach that has inspired many other approaches \cite{xhail,atom,inspire}, notably \textsc{Aleph}{} \cite{aleph}.
Progol employs a set covering algorithm to incrementally find programs that covers an uncovered example, removes the example from the set, and repeats on the remaining uncovered examples.
Progol struggles to learn recursive and optimal programs and does not support predicate invention.
Progol variants, such as \textsc{Aleph}{}, inherit the same limitations.
\textbf{Rule selection.}
Many systems systems formulate the ILP problem as a rule selection problem \cite{ilasp,hexmil,dilp,prosynth,difflog,apperception}.
ASPAL \cite{aspal} is one of the first rule selection approaches.
ASPAL precomputes every possible rule in the hypothesis space.
ASPAL uses an ASP solver to find a subset of the rules that covers all the positive but none of the negative examples.
A major issue with this approach is scalability in terms of the size of rules.
As it involves pre-computing every possible rule in the hypothesis space, the approach does not scale to rules with many body literals, or, more generally, to problems with many rules.
For instance, the \emph{coins-goal} task in our experiments would require precomputing at least $10^{12}$ rules, which is clearly intractable.
In contrast to these approaches, we do not precompute every possible rule.
In addition, we do not search for combinations of individual rules.
We instead search for combinations of \emph{programs}, potentially formed of multiple rules, including recursive rules and invented predicates.
\textbf{\textsc{Popper}{}.}
Rather than precompute every possible rule, \textsc{Popper}{} \cite{popper} lazily generates \emph{programs}, potentially with multiple rules.
The key idea of \textsc{Popper}{} is to discover constraints from smaller programs to rule out larger programs.
\textsc{Popper}{} searches for a single solution for all the examples.
\textsc{Popper}{} struggles to learn solutions with many rules and many literals.
We go beyond \textsc{Popper}{} by (i) only generating non-separable programs in the generate step, and (ii) adding a combine step.
As we experimentally demonstrate, our \textsc{Popper+}{} approach can drastically outperform \textsc{Popper}{} and other systems.
\textbf{\textsc{DCC}{}.}
The most similar work to our approach is the \emph{divide, constrain, and conquer} (\textsc{DCC}{}) approach \cite{dcc}.
\textsc{DCC}{} combines classical D\&C{} search with modern constraint-driven ILP.
Similar to D\&C{} approaches, \textsc{DCC}{} learns a program for each example separately.
To do so, \textsc{DCC}{} calls \textsc{Popper}{} with a subset of the examples.
As these programs are likely to be overly specific, \textsc{DCC}{} iteratively tries to learn more general programs.
The key idea behind \textsc{DCC}{} is to reuse knowledge (constraints) between iterations to improve learning performance.
Our approach is completely different to \textsc{DCC}{}.
\textsc{DCC}{} tries to generate a single program that covers all the examples, including separable programs and \textsc{DCC}{} has no combine stage, i.e. does not search for combinations of programs.
By contrast, \textsc{Popper+}{} never generates a separable program.
Moreover, it searches for combinations of programs in the combine stage.
As we experimentally show, \textsc{Popper+}{} can drastically outperform \textsc{DCC}{}, especially in terms of learning times.
\section{Problem Setting}
\label{sec:setting}
We use the \emph{learning from failures} (LFF) \cite{popper} setting.
LFF uses \emph{hypothesis constraints} to restrict the hypothesis space.
Let $\mathcal{L}$ be a language that defines hypotheses, i.e.~a meta-language.
For instance, consider a meta-language formed of two literals \emph{h\_lit/3} and \emph{b\_lit/3} which represent \emph{head} and \emph{body} literals respectively.
With this language, we can denote the rule \emph{last(A,B) $\leftarrow$ tail(A,C), head(C,B)} as the set of literals \emph{\{h\_lit(0,last,(0,1)), b\_lit(0,tail,(0,2)), b\_lit(0,head,(2,1))\}}.
The first argument of each literal is the rule index, the second is the predicate symbol, and the third is the literal variables, where \emph{0} represents \emph{A}, \emph{1} represents \emph{B}, etc.
A \emph{hypothesis constraint} is a constraint (a headless rule) expressed in $\mathcal{L}$.
Let $C$ be a set of hypothesis constraints written in a language $\mathcal{L}$.
A set of definite clauses $H$ is \emph{consistent} with $C$ if, when written in $\mathcal{L}$, $H$ does not violate any constraint in $C$.
For instance, the rule \emph{last(A,B) $\leftarrow$ last(B,A)} violates the constraint \emph{$\leftarrow$ h\_lit(0,last,(0,1)), b\_lit(0,last,(1,0))}.
We denote as $\mathcal{H}_{C}$ the subset of the hypothesis space $\mathcal{H}$ which does not violate any constraint in $C$.
We define the LFF problem:
\begin{definition}[\textbf{LFF input}]
\label{def:probin}
The \emph{LFF} input is a tuple $(E^+, E^-, B, \mathcal{H}, C)$ where $E^+$ and $E^-$ are sets of ground atoms denoting positive and negative examples respectively; $B$ is a definite program denoting background knowledge;
$\mathcal{H}$ is a hypothesis space, and $C$ is a set of hypothesis constraints.
\end{definition}
\noindent
We define a LFF solution:
\begin{definition}[\textbf{LFF solution}]
\label{def:solution}
Given an input tuple $(E^+, E^-, B, \mathcal{H}, C)$, a hypothesis $H \in \mathcal{H}_{C}$ is a \emph{solution} when $H$ is \emph{complete} ($\forall e \in E^+, \; B \cup H \models e$) and \emph{consistent} ($\forall e \in E^-, \; B \cup H \not\models e$).
\end{definition}
\noindent
If a hypothesis is not a solution then it is a \emph{failure}.
A hypothesis is \emph{incomplete} when $\exists e \in E^+, \; H \cup B \not \models e$.
A hypothesis is \emph{inconsistent} when $\exists e \in E^-, \; H \cup B \models e$.
A hypothesis is \emph{partially complete} when $\exists e \in E^+, \; H \cup B \models e$.
A hypothesis is \emph{totally incomplete} when $\forall e \in E^+, \; H \cup B \not \models e$.
Let $cost : \mathcal{H} \mapsto R$ be an arbitrary cost function that measures the cost of a hypothesis.
We define an \emph{optimal} solution:
\begin{definition}[\textbf{Optimal solution}]
\label{def:opthyp}
Given an input tuple $(E^+, E^-, B, \mathcal{H}, C)$, a hypothesis $H \in \mathcal{H}_{C}$ is \emph{optimal} when (i) $H$ is a solution, and (ii) $\forall H' \in \mathcal{H}_{C}$, where $H'$ is a solution, $cost(H) \leq cost(H')$.
\end{definition}
\noindent
In this paper, our cost function is the number of literals in the hypothesis $H$.
\paragraph{Constraints.}
The goal of an LFF learner is to learn hypothesis constraints from failed hypotheses.
\citet{popper} introduce hypothesis constraints based on subsumption \cite{plotkin:thesis}.
A clause $C_1$ \emph{subsumes} a clause $C_2$ ($C_1 \preceq C_2$) if and only if there exists a substitution $\theta$ such that $C_1\theta \subseteq C_2$.
A clausal theory $T_1$ subsumes a clausal theory $T_2$ ($T_1 \preceq T_2$) if and only if $\forall C_2 \in T_2, \exists C_1 \in T_1$ such that $C_1$ subsumes $C_2$.
A clausal theory $T_1$ is a \emph{specialisation} of a clausal theory $T_2$ if and only if $T_2 \preceq T_1$.
A clausal theory $T_1$ is a \emph{generalisation} of a clausal theory $T_2$ if and only if $T_1 \preceq T_2$.
If a hypothesis $H$ is incomplete, a \emph{specialisation} constraint prunes specialisations of $H$, as they are guaranteed to also be incomplete.
If a hypothesis $H$ is inconsistent, a \emph{generalisation} constraint prunes generalisations of $H$, as they are guaranteed to be inconsistent as well.
\section{\textsc{Popper+}{}}
\label{sec:impl}
We now describe our \textsc{Popper+}{} algorithm.
We first briefly describe \textsc{Popper}{}.
\subsection{\textsc{Popper}{}}
\noindent
Algorithm \ref{alg:popper} shows the \textsc{Popper}{} algorithm, which solves the LFF problem (Definition \ref{def:probin}).
\textsc{Popper}{} takes as input background knowledge (\tw{bk}), positive (\tw{pos}) and negative (\tw{neg}) examples, and an upper (\tw{max\_size}) bound on hypothesis sizes.
\textsc{Popper}{} uses a \emph{generate}, \emph{test}, and \emph{constrain} loop to find an optimal solution.
\textsc{Popper}{} starts with a ASP program $\mathcal{P}$ (hidden in the generate function).
The models of $\mathcal{P}$ correspond to hypotheses (definite programs).
In the generate stage (line 5), \textsc{Popper}{} uses Clingo \cite{clingo}, an ASP system, to search for a model of $\mathcal{P}$.
If there is no model, \textsc{Popper}{} increments the hypothesis size (line 7) and loops again.
If there is a model, \textsc{Popper}{} converts it to a hypothesis (\tw{h}).
In the test stage (line 9), \textsc{Popper}{} tests the hypothesis on the training examples.
If the hypothesis is a solution (is complete and consistent), \textsc{Popper}{} returns it.
If the hypothesis fails (is incomplete or inconsistent), then, in the constrain stage (line 12), \textsc{Popper}{} builds hypothesis constraints (represented as ASP constraints) from the failure.
\textsc{Popper}{} adds these constraints to $\mathcal{P}$ to prune models and thus reduce the hypothesis space.
For instance, if a hypothesis is incomplete (does not entail all the positive examples), \textsc{Popper}{} builds a specialisation constraint to prune hypotheses that are logically more specific.
If a hypothesis is inconsistent, \textsc{Popper}{} builds a generalisation constraint to prune hypotheses that are logically more general.
\textsc{Popper}{} repeats this loop until it (i) finds an optimal solution, or (ii) there are no more hypotheses to test.
\begin{algorithm}[t]
{
\begin{myalgorithm}[]
def $\text{popper}$(bk, pos, neg, max_size):
cons = {}
m = size
while m $\leq$ max_size:
h = generate(cons, size)
if h == UNSAT:
size += 1
continue
outcome = test(pos, neg, bk, h)
if outcome == (COMPLETE, CONSISTENT)
return h
cons += constrain(h, outcome)
return {}
\end{myalgorithm}
\caption{
\textsc{Popper}{}
}
\label{alg:popper}
}
\end{algorithm}
\subsection{\textsc{Popper+}{}}
Algorithm \ref{alg:popp+} shows the \textsc{Popper+}{} algorithm.
There are two key differences to \textsc{Popper}{}.
First, \textsc{Popper+}{} only allows generates \emph{non-separable} programs in the generate stage.
Second, \textsc{Popper+}{} has an additional \emph{combine} stage that tries to combine promising programs.
We now describe these differences and the high-level \textsc{Popper+}{} loop.
\begin{algorithm}[t]
{
\begin{myalgorithm}[]
def $\text{popper+}$(bk, pos, neg, max_size):
cons = {}
candidates = {}
size = 1
while size $\leq$ max_size:
h = generate(cons, size)
if h == UNSAT:
size += 1
continue
test_outcome = test(pos, neg, bk, h)
if test_outcome == (PARTIAL_COMPLETE, CONSISTENT):
candidates += h
combine_outcome = combine(candidates, bk, pos, neg)
if combine_outcome != NO_SOLUTION:
solution, solution_size = outcome
max_size = solution_size-1
cons += constrain(h, outcome)
return {}
\end{myalgorithm}
\caption{
\textsc{Popper}{}
}
\label{alg:popp+}
}
\end{algorithm}
The generate stage of \textsc{Popper+}{} is identical to \textsc{Popper}{} but only generates non-separable programs.
The test stage is also the same.
A key difference is how \textsc{Popper+}{} handles the outcome of testing.
If a program is inconsistent, \textsc{Popper+}{} builds a generalisation constraint to prune programs that are more general, the same as \textsc{Popper}{}.
Specialisation constraints are different.
If a program is incomplete, \textsc{Popper}{} builds a specialisation constraint to prune anything more specific.
However, \textsc{Popper+}{} cannot do that because the partially complete program might still need to be specialised to form a solution.
For instance, consider learning programs to determine whether someone is happy.
Suppose \textsc{Popper+}{} generates the program:
\begin{center}
\begin{tabular}{l}
\emph{happy(A) $\leftarrow$ rich(A)}
\end{tabular}
\end{center}
This program is incomplete and inconsistent.
However, we do not want to prune specialisations of it as doing so would eliminate the following program from the hypothesis space:
\begin{center}
\begin{tabular}{l}
\emph{happy(A) $\leftarrow$ rich(A), tall(A)}
\end{tabular}
\end{center}
\noindent
Therefore, \textsc{Popper+}{} only builds a specialisation constraint when a program is either (i) totally incomplete, or (ii) consistent.
If a program is partially complete and consistent, \textsc{Popper+}{} adds the program to a set of candidate programs (line 12).
In the combine stage, \textsc{Popper+}{} searches for combinations of programs that cover the positive examples.
If there is such a combination, \textsc{Popper+}{} updates its maximum program size and continues to search to prove optimality.
For instance, suppose that the combination of two programs each with 3 literals is a solution.
Then there is no point considering programs with more than 5 literals, as we already have a solution with 6 literals.
\textsc{Popper+}{} repeats this loop until either it (i) finds an optimal solution, or (ii) there are no more hypotheses to test.
\paragraph{Combiner.}
To find combinations of programs, we follow ASPAL and use an ASP encoding.
We give each positive example a unique example id.
Unlike ASPAL, which only assigns ids to individual rules, we assign each candidate program (potentially formed of multiple rules) a unique program id.
We create an ASP choice rule (a decision variable in standard constraint terminology) that determines whether a program should be in a solution.
We add facts about the coverage and size of each candidate program.
We then ask the ASP solver to find a combination of programs that covers as many positive examples as possible.
We also ask the ASP solver to find the smallest combination, as to learn the optimal program.
\section{Experiments}
\label{sec:exp}
The evaluate the performance of \textsc{Popper+}{}, our experiments aim to answer the question:
\begin{description}
\item[Q1] How does \textsc{Popper+}{} compare against other approaches?
\end{description}
\noindent
To answer \textbf{Q1} we compare \textsc{Popper+}{} against \textsc{Popper}{}, \textsc{DCC}{}, and \textsc{Aleph}{}.
A key motivation for introducing \textsc{Popper+}{} is to reduce learning times, especially the time required to provably learn optimal programs.
Our experiments, therefore, aim to answer the question:
\begin{description}
\item[Q2] How well does \textsc{Popper+}{} perform given more learning time?
\end{description}
\noindent
To answer \textbf{Q2}, we measure the learning performance of \textsc{Popper+}{} and other systems when given progressively longer timeouts (maximum learning times).
In other words, we ask each system to return the best solution found in the time given.
\paragraph{Methods.}
We measure predictive accuracy and learning time given a maximum learning time.
We use two maximum learning times: \textbf{60 seconds} and \textbf{10 minutes}.
We repeat all the experiments 10 times and measure the mean and standard deviation.
We use a 3.8 GHz 8-Core Intel Core i7 with 32GB of ram.
All the systems use a single CPU.
\paragraph{Systems.}
\label{sec:systems}
We compare \textsc{Popper+}{} against \textsc{Popper}{}, \textsc{DCC}{}, and \textsc{Aleph}{}\footnote{
We also tried to compare \textsc{Popper+}{} against \textsc{ILASP3}{}.
However, \textsc{ILASP3}{} follows ASPAL and pre-computes every possible rule in a hypothesis space.
This approach is infeasible for our datasets.
For instance, on the trains tasks, \textsc{ILASP3}{} took 2 seconds to pre-compute rules with three body literals; 20 seconds for rules with four body literals; and 12 minutes for rules with five body literals.
Since the simplest train task requires rules with six body literals, \textsc{ILASP3}{} is unusable.
}.
We use these systems because they can learn recursive definite programs.
\textsc{DCC}{}, \textsc{Popper}{}, and \textsc{Popper+}{} use identical biases so the comparison between them is fair.
\textsc{Aleph}{} uses a similar bias to \textsc{Popper+}{} but requires additional settings, such as an upper bound on the nodes to be explored when searching for a rule.
We have tried to make a fair comparison but there will likely be different parameters that would improve the performance of \textsc{Aleph}{}.
\subsection{Experimental Domains}
We use the following domains.
More details are in the appendix.
\textbf{Michalski Trains.}
The Michalski trains \cite{michalski:trains} problem is to find a hypothesis that distinguishes eastbound trains from westbound trains.
We use this domain because we can easily generate progressively more difficult tasks to test the scalability of the approaches as the solution size grows.
We consider four tasks of increasing complexity, where the subscript denotes the number of rules in the solution.
There are 1000 examples but the distribution of positive and negative examples is different for each task.
We randomly sample the examples and split them into 80/20 train/test partitions
\textbf{IGGP.}
In \emph{inductive general game playing} (IGGP) \cite{iggp} agents are given game traces from the general game playing competition \cite{ggp}.
The task is to induce a set of rules that could have produced these traces.
We use four IGGP games: \emph{minimal decay} (md), \emph{rock, paper, scissors} (rps), \emph{buttons}, and \emph{coins}.
We learn the \emph{next} relation for each game.
We also learn the \emph{goal} relation for \emph{buttons} and \emph{coins}.
These tasks are non-trivial for ILP systems as the search spaces can be large.
We exclude the goal relations for \emph{md} and \emph{rps} and they require trivial two literal solutions.
These tasks are non-trivial for ILP systems as the search spaces can be large.
For instance, the \emph{coins-goal} problem has 130 background relations and requires a solution with multiple rules and many literals.
\textbf{Program synthesis.}
Inducing complex recursive programs has long been considered a difficult problem \cite{ilp20} and most ILP systems cannot learn recursive programs.
We use the program synthesis dataset introduced by \citet{popper} augmented with two new tasks \emph{contains} and \emph{reverse}.
\subsection{Experimental Results}
Table \ref{tab:q1-60} shows the predictive accuracies of the solutions returned by the systems when given a maximum learning time of \textbf{60 seconds}.
The results show that \textsc{Popper+}{} generally outperforms the other systems in terms of predictive accuracy.
\textsc{Popper+}{} comfortably outperforms \textsc{Popper}{} and \textsc{DCC}{}, especially on the trains and IGGP tasks.
For instance, for the \emph{buttons} task, \textsc{Popper+}{} achieves 100\% accuracy on the test set, whereas \textsc{Popper}{} and \textsc{DCC}{} only achieve 19\%.
\textsc{Aleph}{} performs reasonably well on the trains and IGGP tasks but struggles on the program synthesis tasks.
This performance is expected as \textsc{Aleph}{}, as with all bottom clause approaches, struggle to learn recursive programs.
\textsc{Popper+}{}, \textsc{Popper}{}, and \textsc{DCC}{} are all guaranteed to learn optimal programs given sufficient time, assuming one exists.
Therefore, when these systems have low predictive accuracy, it is because they struggled to find a solution in the given time limit and thus return an empty or partial program -- this explanation does not hold for \textsc{Aleph}{}, which always terminates in the given learning time, but tends to learn overly specific programs.
For instance, the \emph{buttons} tasks requires learning a solution with 10 rules and 61 literals, which is beyond \textsc{DCC}{} and \textsc{Popper}{}.
This explanation is clearer when looking at the predictive accuracies of the solutions returned by the systems when given a maximum learning time of \textbf{10 minutes}, which are shown in Table \ref{tab:q1-600}.
With this larger timeout, all three systems have higher predictive accuracy, as does \textsc{Aleph}{}.
However, even with this larger timeout, \textsc{Popper+}{} is still the best performing system.
The systems have large differences in learning times, which are shown in Table \ref{tab:q1times}.
The main difference is that \textsc{Popper+}{} provably learns the optimal solution for most tasks in under 90 seconds.
By contrast, for many tasks, \textsc{DCC}{} and \textsc{Popper}{} do not terminate within 10 minutes.
For instance, \textsc{DCC}{} and \textsc{Popper}{} do not find a solution for \emph{buttons-goal} given 10 minutes
The reasons for this drastic improvement in learning time are because \textsc{Popper+}{} (i) only generates non-separable programs, and (ii) then tries to combine them.
The results of the \emph{buttons-goal} task need explaining.
\textsc{Popper+}{} is guaranteed to find the smallest program that covers all the positive and none of the negative examples.
On the \emph{buttons-goal} task, \textsc{Popper+}{} finds such a program in less than 60 seconds.
However, for this task, \textsc{Aleph}{} outperforms \textsc{Popper+}{} in terms of predictive accuracy (100\% vs 74\%).
The reason is that \textsc{Aleph}{} learns a very specific program that includes memorising certain examples.
In other words, \textsc{Aleph}{} includes positive examples in the solution.
For this task, memorising the training examples is suitable for high predictive accuracy on the test examples.
\textsc{Popper+}{}, by contrast, learns a more general solution, i.e. without memorising the examples, but which does not generalise as well to the test data.
Overall, the results from this experiment show that \textsc{Popper+}{} can outperform existing systems both in terms of predictive accuracies and learning times.
\begin{table}[ht]
\centering
\footnotesize
\begin{tabular}{@{}l|cccc@{}}
\toprule
\textbf{Task} & \textbf{\textsc{Popper+}{}} & \textbf{\textsc{DCC}} & \textbf{\textsc{Popper}{}} & \textbf{\textsc{Aleph}{}}\\
\midrule
\emph{trains1} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\emph{trains2} & 97 $\pm$ 1 & 98 $\pm$ 1 & 98 $\pm$ 1 & \textbf{100} $\pm$ 0 \\
\emph{trains3} & 99 $\pm$ 0 & \textbf{100} $\pm$ 0 & 79 $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\emph{trains4} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 32 $\pm$ 0 & 59 $\pm$ 16 \\
\midrule
\emph{md} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 11 $\pm$ 0 & 94 $\pm$ 0 \\
\emph{buttons} & \textbf{100} $\pm$ 0 & 19 $\pm$ 0 & 19 $\pm$ 0 & 87 $\pm$ 0 \\
\emph{rps} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 18 $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\emph{coins} & \textbf{88} $\pm$ 2 & 33 $\pm$ 16 & 17 $\pm$ 0 & 17 $\pm$ 0 \\
\emph{buttons-goal} & 76 $\pm$ 8 & 50 $\pm$ 0 & 50 $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\emph{coins-goal} & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 & 50 $\pm$ 0 & 50 $\pm$ 0 \\
\midrule
\emph{contains} & \textbf{100} $\pm$ 0 & 70 $\pm$ 12 & 60 $\pm$ 10 & 50 $\pm$ 0 \\
\emph{dropk} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 59 $\pm$ 9 \\
\emph{droplast} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{evens} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{finddup} & \textbf{100} $\pm$ 0 & 99 $\pm$ 0 & 99 $\pm$ 0 & 50 $\pm$ 0 \\
\emph{last} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{len} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{reverse} & \textbf{90} $\pm$ 9 & 50 $\pm$ 0 & 50 $\pm$ 0 & 50 $\pm$ 0 \\
\emph{sorted} & \textbf{95} $\pm$ 4 & 85 $\pm$ 9 & 75 $\pm$ 11 & 65 $\pm$ 4 \\
\emph{sumlist} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\end{tabular}
\caption{
Predictive accuracies with a \textbf{60 seconds} learning timeout.
We round accuracies to integer values.
The error is standard deviation.
}
\label{tab:q1-60}
\end{table}
\begin{table}[ht]
\centering
\small
\begin{tabular}{@{}l|cccc@{}}
\toprule
\textbf{Task} & \textbf{\textsc{Popper+}{}} & \textbf{\textsc{DCC}} & \textbf{\textsc{Popper}{}} & \textbf{\textsc{Aleph}{}}\\
\midrule
\emph{trains1} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\emph{trains2} & 97 $\pm$ 1 & 98 $\pm$ 1 & 98 $\pm$ 1 & \textbf{100} $\pm$ 0 \\
\emph{trains3} & 99 $\pm$ 0 & \textbf{100} $\pm$ 0 & 79 $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\emph{trains4} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 32 $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\midrule
\emph{md} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 28 $\pm$ 17 & 94 $\pm$ 0 \\
\emph{buttons} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 19 $\pm$ 0 & 87 $\pm$ 0 \\
\emph{rps} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 18 $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\emph{coins} & 87 $\pm$ 1 & 57 $\pm$ 16 & 17 $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\emph{buttons-goal} & 74 $\pm$ 8 & 50 $\pm$ 0 & 50 $\pm$ 0 & \textbf{100} $\pm$ 0 \\
\emph{coins-goal} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 & 93 $\pm$ 0 \\
\midrule
\emph{contains} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{dropk} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 59 $\pm$ 9 \\
\emph{droplast} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{evens} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{finddup} & \textbf{99} $\pm$ 0 & \textbf{99} $\pm$ 0 & 98 $\pm$ 0 & 50 $\pm$ 0 \\
\emph{last} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{len} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{reverse} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\emph{sorted} & \textbf{95} $\pm$ 4 & \textbf{95} $\pm$ 4 & \textbf{95} $\pm$ 4 & 65 $\pm$ 4 \\
\emph{sumlist} & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & \textbf{100} $\pm$ 0 & 50 $\pm$ 0 \\
\end{tabular}
\caption{
Predictive accuracies with a \textbf{10 minute} learning timeout.
We round accuracies to integer values.
The error is standard deviation.
}
\label{tab:q1-600}
\end{table}
\begin{table}[t!]
\small
\centering
\begin{tabular}{@{}l|cccc@{}}
\toprule
\textbf{Task} & \textbf{\textsc{Popper+}{}} & \textbf{\textsc{DCC}} & \textbf{\textsc{Popper}{}} & \textbf{\textsc{Aleph}{}}\\
\midrule
\emph{trains1} & 3 $\pm$ 0.2 & 4 $\pm$ 0.3 & 3 $\pm$ 0.2 & \textbf{2} $\pm$ 0.5 \\
\emph{trains2} & 3 $\pm$ 0.3 & 7 $\pm$ 1 & 26 $\pm$ 9 & \textbf{1} $\pm$ 0.1 \\
\emph{trains3} & 16 $\pm$ 0.6 & timeout & timeout & \textbf{13} $\pm$ 3 \\
\emph{trains4} & \textbf{13} $\pm$ 0.5 & timeout & timeout & 148 $\pm$ 50 \\
\midrule
\emph{md} & 11 $\pm$ 0.8 & timeout & 586 $\pm$ 14 & \textbf{1} $\pm$ 0.1 \\
\emph{buttons} & \textbf{23} $\pm$ 0.7 & timeout & timeout & 43 $\pm$ 3 \\
\emph{rps} & 87 $\pm$ 1 & timeout & timeout & \textbf{4} $\pm$ 0.2 \\
\emph{coins} & \textbf{50} $\pm$ 2 & timeout & timeout & 342 $\pm$ 10 \\
\emph{buttons-goal} & 44 $\pm$ 0.2 & timeout & timeout & \textbf{22} $\pm$ 0.1 \\
\emph{coins-goal} & \textbf{88} $\pm$ 0.7 & timeout & timeout & 283 $\pm$ 2 \\
\midrule
\emph{contains} & \textbf{13} $\pm$ 0.5 & 85 $\pm$ 36 & 88 $\pm$ 18 & 46 $\pm$ 0.4 \\
\emph{dropk} & 2 $\pm$ 0.2 & 5 $\pm$ 0.5 & 5 $\pm$ 0.4 & \textbf{1} $\pm$ 0.3 \\
\emph{droplast} & \textbf{2} $\pm$ 0.1 & 8 $\pm$ 0.8 & 7 $\pm$ 0.6 & 467 $\pm$ 35 \\
\emph{evens} & 2 $\pm$ 0.2 & 12 $\pm$ 0.9 & 12 $\pm$ 1 & \textbf{0.8} $\pm$ 0.1 \\
\emph{finddup} & 5 $\pm$ 0.2 & 42 $\pm$ 2 & 29 $\pm$ 3 & \textbf{0.5} $\pm$ 0 \\
\emph{last} & 2 $\pm$ 0.1 & 5 $\pm$ 0.5 & 4 $\pm$ 0.5 & \textbf{0.7} $\pm$ 0.1 \\
\emph{len} & 3 $\pm$ 0.2 & 13 $\pm$ 1 & 13 $\pm$ 0.9 & \textbf{0.8} $\pm$ 0 \\
\emph{reverse} & 28 $\pm$ 5 & 302 $\pm$ 26 & 258 $\pm$ 37 & \textbf{0.8} $\pm$ 0 \\
\emph{sorted} & 23 $\pm$ 17 & 38 $\pm$ 1 & 52 $\pm$ 7 & \textbf{0.5} $\pm$ 0.1 \\
\emph{sumlist} & 4 $\pm$ 0.1 & 40 $\pm$ 1 & 46 $\pm$ 3 & \textbf{0.3} $\pm$ 0 \\
\end{tabular}
\caption{
Termination times given a 10 minute timeout.
A \tw{timeout} entry means that the system did not terminate in the given time.
We round times over one second to the nearest second.
The error is standard deviation.
Although \textsc{Aleph}{} has low learning times in the synthesis tasks is also low predictive accuracy.
}
\label{tab:q1times}
\end{table}
\section{Conclusions and Limitations}
We have introduced an ILP approach that employs a \emph{generate}, \emph{test}, \emph{combine}, and \emph{constrain} loop.
The three key ideas are to (i) decompose programs into \emph{non-separable fragments}, (ii) learn fragments separately, and (iii) \emph{combine} fragments to learn programs with many rules and literals.
We have implemented our approach in \textsc{Popper+}{}, a new ILP system.
\textsc{Popper+}{} can learn optimal, recursive, and large programs and perform predicate invention.
Our experiments on three domains (classification, inductive general game playing, and program synthesis) show that our approach can improve predictive accuracies and reduce learning times compared to other ILP systems.
The drastic improvements we have shown in learning performance should directly transfer to problems in which LFF has already been applied, such as learning to explain Rubix cubes \cite{forest-rubix} and learning higher-order programs \cite{hopper}.
\subsection{Limitations and Future Work}
\paragraph{Noise.}
In the combine stage, \textsc{Popper+}{} searches for a combination of candidate programs that covers all the positive and none of the negative examples and that is minimal in size.
To perform this search, we use Clingo's optimisation feature.
This approach allows us to handle misclassified positive examples, i.e. false negatives.
In future work, we want to extend the approach to handle negative examples, which early work has already explored \cite{noisypopper}.
\section*{Acknowledgments}
This work was supported by the EPSRC fellowship \emph{The Automatic Computer Scientist} (EP/V040340/1).
| {'timestamp': '2022-06-06T02:15:48', 'yymm': '2206', 'arxiv_id': '2206.01614', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01614'} | arxiv |
\section{Introduction}
Neurorehabilitation is a widely used medical practice that aims to aid recovery from a nervous system injury. Its purpose is to maximize and maintain the subject's motor control while trying to restore motor functions in people with neurological impairments.
Robot-assisted training has been widely investigated as an effective neurorehabilitation approach that helps augment physical therapy and facilitates motor recovery. According to the literature~\cite{Maciejasz-2014,Zhang-2017,Qassim-2020}, such approaches can help therapists save time and effort while reproducing accurate and repetitive motions and delivering high-intensity training. In particular, upper-limb robotic rehabilitation is one of the fastest-growing areas in modern neurorehabilitation. For this approach, the authors chose to exploit the PlanArm2 prototype~\cite{Yamine20201}, a planar robotic device designed for domestic upper-limb neurorehabilitation.
The system is envisioned to be used by patients at home after an initial calibration phase supervised by professionals. However, a crucial issue for rehabilitation training is user engagement and motivation~\cite{Blank2014184}, which may be lacking if the rehabilitation system is used without a human medical coach. In these terms, we believe that introducing socially interactive agents could represent a valid solution to restore and augment the social aspects typical of an in-person rehabilitation session.
Moreover, inheriting results typical of social robotics, the enhancement of a rehabilitation system through physiological and social signals awareness may augment the system personalization level and further facilitate neuroplasticity. Therefore, the capability of a neurorehabilitation training system to model the patient's state and tune its behavior according to both the measured performance and the inferred social and physiological state could improve the engagement of the user and the outcome of the therapy.
\begin{figure}[ht]
\centerline{\includegraphics[width=0.49\textwidth]{Images/system_concept.png}}
\caption{Empathetic Neurorehabilitation robotic training system concept.}
\label{fig:system_concept}
\end{figure}
This paper investigates a technologically-supported upper-limb neurorehabilitation approach by introducing social interaction capabilities in a heterogeneous system composed of 1) a planar rehabilitation device for physical assistance interaction and 2) two socially interactive virtual agents in the role of a coaching assistant, one demanding, one supporting. In this context, physiological and social signals of the participant are analyzed and elaborated into attentiveness, stress, engagement, and pain information, which are then exploited to tune the rehabilitation session coherently.
\section{Background and Related Work}
\subsection{Neurorehabilitation Best Practice}
\label{sec:bpnt}
The constantly growing employment of technological devices in neurorehabilitation therapy can be explained by the introduced ease in reaching a significant number of movement repetitions in a chosen district and in obtaining higher patient engagement, fundamental aspects in the motor rehabilitation process. However, to do so, one must be able to reconcile movement repetition, often leading to boredom, with variability and incentive to enhance the patient's attention and commitment.
This section reports "neurorehabilitation best practices" we collected from experienced physiotherapists how they manage these issues. Based on these, a system concept is proposed.
During every therapy session, a therapist assesses the actual level of attention, commitment, engagement, and stress or pain currently experienced by the patient to deliver the correct amount of exercise and avoid the risk of too easy or too difficult exercises that may lead to a decay in interest or even frustration. In particular, the therapist monitoring the therapy session relies on the activity scores and the subject's behavior to reach this goal. For example, if the patient cannot achieve a particular performance, the selected activity is likely too difficult. On the other hand, if the patient can perform the exercise but, after some time, becomes very talkative and less performing, it is likely that decay in interest is being experienced. On this basis, the therapist must give feedback, if needed, support when the activities are too difficult or change exercise when the attention starts to decrease.
Furthermore, considering patients affected by neurological impairments, attention problems are frequent. Recording the period to which the attention could last can be useful information to provide a correct dosage of exercise.
Lastly, the management of neurological disorders can be considerably different between adults and children. In both cases, understanding when a pause or a change of exercise is necessary is crucial. However, considering adults, one can count on their responsibility to train towards an improvement, even if the activity could lead to boredom. On the other hand, children may not behave in the same way and, to augment their engagement, it is crucial to introduce gaming aspects to the exercise.
\subsection{Socially Interactive Agents as Medical Coaches}
\label{sec:agents4medicaltraining}
As a use case for interactive social agents, technologically supported health care has been researched for about 15 years. One of the early systems is the Fit Track system with the relational agent Laura \cite{Bickmore-et-al-05}. Laura has the role of an exercise advisor that interacts with patients daily for one month to motivate them to exercise more. A more recent system employs the socially interactive agent Gloria for stress management training system using biofeedback \cite{Schneeberger-et-al-21}. The training system is designed to run autonomously without a medical coach present during the training. The authors conducted an expert interview and a user study in which the novel approach was compared to the stress management training using stress diaries.
The actual training combines two methods of feedback: 1) situation awareness and 2) social interaction feedback with an awareness tool and a socially interactive agent. This approach draws on theories of embodied learning, which proclaims an interaction between bodily and cognitive functions and foresee their concurrent stimulation for more intuitive, long-lasting, and transferable learning \cite{puhl2015blending}. In the study, the awareness tool helped the user to track their sensory-motor reactions to stressful situations, increasing situation (introspective) awareness \cite{price2018interoceptive}. The agent first created a social background to embed this awareness. After a first awareness training, the awareness tool is faded out, and the social agent overtakes the feedback. This implements prominent theories on the socio-emotional routes of learning and implicit emotion regulation in particular \cite{braunstein2017explicit}. In the current context, we are looking into embedding the cognitive understanding of the task in a socio-emotional context to increase the learning effect of the neurorehabilitation training.
The results of a study revealed, HRV biofeedback training supported by a socially interactive agent tends to lower stress levels and improve adaptability to stressful situations.
For the presented neurorehabilitation approach, we rely on the Gloria biofeedback training system. However, the behavior and the training strategies are adapted to the specific needs of neurorehabilitation training.
\subsection{Robotic Neurorehabilitation}
In the last two decades, robotic devices for neurorehabilitation have been widely investigated, developed, and introduced in the market to offer a valid alternative to conventional therapy and fill the constantly growing gap between supply and demand, both for upper limb and lower limb rehabilitation~\cite{Maciejasz-2014,Zhang-2017,Qassim-2020}.
The goal of control algorithms for robotic therapy is to control robotic devices designed for rehabilitation exercises so that the participant's selected exercises provoke motor plasticity and improve motor recovery. Thus, the capability of a robot to adapt the level of assistance according to the skill and the performance of the patient is one of the most crucial features~\cite{Marchal-Crespo-2009, Meng-2015}. Furthermore, assistance is sometimes obtained not only from the biomechanical point of view but also evaluating physiological and psychological aspects~\cite{Novak-2011, Malosio-2016}, for a more fine-grained assessment of the patient's state.
Visual feedback, sometimes including immersive and augmented reality, is an almost indispensable element for robotic rehabilitation devices, to administer therapeutic exercises to increase user engagement, to propose visually-augmented exercises, even resembling Activities of Daily Living (ADLs).
Enriched communication, including virtual coaching, could increase the effect of personalized and motivating communication. This approach is more and more investigated and exploited in medical care, but its exploitation is still limited in the rehabilitation field~\cite{Tropea-2019}.
\begin{figure*}[thpb]
\centering
\includegraphics[width=0.65\textwidth, trim=0 38 0 20, clip]{Images/bailar_deployment_diagram.jpg}
\caption{Human-in-the-loop Empathetic Neurorehabilitation Trainer concept}
\label{fig:deployment}
\end{figure*}
\subsection{Social and Physiological Signals}
The level of attention a user pays to a task is usually studied in fields such as education (e.g., measuring student attentiveness during a lecture), driver assistance (e.g., monitoring attentiveness of driver to prevent accidents), etc. As noted in \cite{Cramer-2011-short}, attention is a key modulator of neuroplasticity, and information regarding the attentiveness of the patient can be important for the rehabilitation strategy. \cite{smith2003determining} demonstrated that a driver's attention state could be determined through the head and facial features. These features were extracted from a video sequence that was captured through a single camera. \cite{c12} proposed a student attention monitoring system that uses facial and body features extracted from MS Kinect 2D and 3D data. Similar to these studies, we rely on facial and body features to predict the attention level of the patient.
The patient may experience stress while performing the exercise, especially if they find the exercise hard or cannot complete the recommended exercise. Many studies \cite{c7, c8, c9} have studied stress-induced in different scenarios like public speaking, mental arithmetic tests, driving on challenging routes, hyperventilation, etc. These studies found that features extracted from ECG data like Heart Rate Variability (HRV) and EDA data like Skin Conductance Response (SCR) are good stress indicators.
Pain assessment and management are critical for a variety of illnesses and medical interventions. Recent efforts in affective computing suggest that automatic detection of pain from facial expression is a feasible goal. In this work, we adopt a deep learning method to develop a model to detect pain from facial expressions. Typically, this requires a large amount of training data. Still, the availability of pain data is limited due to patient contact, privacy concerns, and the adherence to strict ethical guidelines. However, previous studies like \cite{c6} have demonstrated that a transfer learning approach can be adopted to develop pain recognition models that perform well, despite the limited training data.
\section{Concepts}
The envisioned Empathetic Neurorehabilitation Trainer architecture is reported in Fig.~\ref{fig:deployment}. The goal of the proposed structure is to provide the patient with socially aware neurorehabilitation therapy. For this purpose, the system is equipped with a rehabilitation-specific robotic device and a virtual socially interactive agent (Fig.~\ref{fig:system_concept}). Both device and agent can adapt their behavior based on the patient's performance, as in most assistance-as-needed paradigms, and take into account the patient's physiological and social state. Moreover, these two socially interactive agents, together with the specific task to be carried out and the feedback media chosen to provide the patient with an explanation regarding the exercise, are intended to work as a single entity, actively collaborating to improve the rehabilitation session outcomes further.
All software and hardware components are realized as nodes in a ROS framework \cite{quigley2009ros}. There, a closed-loop monitoring of a set of heterogeneous parameters is introduced. In fact, during the execution of the task, the robotic device is in charge of collecting data regarding the kinematics of the patient's movement (e.g., position, speed), and a wearable device is used to extract a series of physiological values (e.g., ECG, EDA). At the same time, a camera captures the patient's upper body for social signal interpretation purposes. These raw data represent the input for a signal interpretation module (Fig.~\ref{fig:deployment}, left bottom), responsible for providing a series of higher-level quantities such as patient's performance, attentiveness, stress, amusement, and pain.
As depicted (Fig.~\ref{fig:deployment}, right bottom), a human physiotherapist has a central role in the proposed approach. In fact, professional expertise is required for the patient's initial assessment (e.g., residual mobility, attention span), used to define the backbone of a model for both the patient, the agent and a selection of suitable exercises. Moreover, a supervised machine learning module (Fig.~\ref{fig:deployment}, center bottom) is employed to learn from the physiotherapist how to optimally balance the target execution performance for the exercise and the social experience for the specific patient. In fact, a certain level of stress is beneficial for the therapy, and therefore the system is supposed to tune the exercise difficulty accordingly. Also, both challenging and entertaining portions of the session are be included to maximize the patient's attention.
Closing the loop, a Therapy Manager (Fig.~\ref{fig:deployment}, center top) actively exploits the inferred information to decide how the behavior of the socially interactive agent should be changed, which explanations (cf. awareness) should be given, and which exercise and difficulty level should be activated to optimize the therapy experience and effectiveness. The Therapy Manager is a software framework for authoring, orchestrating, and executing scenario content with task specifications. This component will be implemented using the Visual~SceneMaker (VSM) tool \cite{Gebhard-et-al-12}. In addition, VSM provides dedicated plugins for all other components using ROS communication protocol.
\subsection{Interactive Agent-based Training and Explanations}
We employ two socially interactive agents for the proposed agent-based training, one supportive agent and one demanding agent. Both take the role of a coaching assistant. According to the patient's level of training, the agent could be chosen.
The supportive agent aims to enhance the patient's motivation by creating a warm, friendly, and motivating atmosphere during the training sessions. The agent signals comprehension by head nods and brief verbal utterances, such as" OK" to create a pleasant atmosphere for the patient. The patient is also encouraged through the use of positive feedback, such as smiles \cite{Gebhard-et-al-14}. On the other hand, we have a demanding agent that appears when the patient is seen to be losing attention or interest (Sec.~\ref{sec:ssi}). Initially, the patient starts the training session with a good performance, but their performance starts deteriorating over time. When such a situation occurs, the demanding agent appears, where the patient is provided with activities with a higher level of complexity. There, the demanding agent exhibits a gaze behavior that is supposed to be perceived as dominant and shows fewer head tilts while speaking and listening \cite{10.1007/978-3-540-85483-8_19}.
Based on the described concept of assessing the affective states such as attentiveness, stress, and pain (Sec.~\ref{sec:ssi}), the agent adapts its motivational strategy. Here, we are considering the possibility of having two agents. One agent supports the patient in the case of actual difficulty during the training. The other shows a more demanding behavior and can be used if the patient is losing attention or interest, which can be detected with the help of social and physiological signals. If the exchange of them during the training exercises supports the training regarding, for example, efficiency, it is part of future investigations.
The coaching assistant follows the best practices of training professionals (Sec.~\ref{sec:bpnt}). The training always starts with a pre-screening phase. This phase serves for the identification of patient issues and the selection of further training sessions. In the pre-screening session, the physiotherapist observes how the patient interacts with the agent and the device and what the patient can achieve. In addition, the movement space is personalized, e.g., space is increased if a noticeable improvement in the patient's movement is detected. Since every patient is different from the other, they might face difficulties in different areas, e.g., some patients may find it difficult to control the smoothness of movement. Others may have difficulties in gripping.
The exercises selected for all patient resembles actual day-to-day useful movements. During the training sessions, time and difficulty are tailored automatically. The system adapts to the level of attention or stress. For example, if the level of attention of the patient decreases, more competitive or challenging exercises/tasks cannot be provided. Strategies to overcome this phase to suggest a training pause or offer playful intermezzos. The particular realization always follows best practices (Sec.~\ref{sec:bpnt}), and known approaches (Sec.~\ref{sec:agents4medicaltraining}) are part of future investigations.
Content-wise, each session is represented by small training fragments. By combining such fragments, the difficulty and time of a training session can be tuned. In addition, each session is followed by some relaxation period, which could involve playful, less stressful activities.
\subsection{Neurorehabilitation Training Device}
This work exploits the PlanArm2 rehabilitation device~\cite{Yamine20201}, a 2-DOF planar robotic prototype validated for its active, passive, and assistive upper-limb rehabilitation capabilities.
The selected device has been developed specifically to achieve an acceptable compromise regarding workspace symmetry concerning the sagittal plane, relatively large workspace, portability, and affordability, rendering it suitable for domestic training sessions. Furthermore, from a long-term point of view, the system could be autonomously used by patients directly at home after an initial calibration phase supervised by professionals. In these terms, the presence of a socially interactive agent could provide the missing social interaction and improve the patient's experience while still guaranteeing an effective training session. However, not all cases are suited for autonomous rehabilitation, which stresses the importance of the patient's initial assessment performed by a specialist.
Besides the agent, the device itself is supposed to adapt in a social way. Therefore, the envisioned assistive control logic exposes a series of parameters intended to be automatically tuned not only based on the patient's performance, as in most assist-as-needed paradigms, but also considering the patient's physiological and social inferred state.
An example of an adjustable parameter is the target speed of execution. By increasing this value, different effects can be expected: in some cases, the exercise may become too stressful and might generate frustration or pain in the patient. In other cases, it could render the activity more challenging and augment the patient's engagement. By monitoring performance, social and physiological signals, the system should be able to tune the parameter correctly, also based on the therapist's experience embedded in the Supervised Machine Learning (Fig.~\ref{fig:deployment}, center bottom) module.
Similarly, a series of additional parameters are available for adaption in the context of the proposed assistive rehabilitation controller. For instance, given an ideal target trajectory to be followed by the patient, the level of regular and tangential assistance force provided can be independently tuned to the patient's needs. By regulating these assistance parameters, one could range from entirely passive to completely active rehabilitation paradigms, meaning that the same device could be used for a wide range of patients after a therapist has properly tuned and trained the system.
\subsection{Signal Interpretation}
\label{sec:ssi}
During the training sessions, the social signals from the patients can be used to infer useful information about their experience. We identified the following emotional states that would serve as an input to the agent's motivational strategy.
\subsubsection{Attentiveness} The patient may get distracted during the training session because of boredom, lack of motivation. Motivation and attention can be critical modulators of neuroplasticity, contributing to determining the actual outcome of a rehabilitation therapy~\cite{Cramer-2011-short}. Therefore, the level of attention of the patient is an important input to the agent's motivational strategy in neurorehabilitation. Previous works have demonstrated that attentiveness can be predicted through physiological signals like EEG \cite{c11} and facial and body pose features like gaze direction, head orientation, body posture \cite{c12}. Deep learning models are trained to focus on facial and body features that can be extracted using the camera.
\subsubsection{Stress and amusement} These affective states are crucial as we introduce some elements of gamification to the training session. On the one hand, the patient may be stressed, for example, when the exercise is too hard. On the other hand, the patient may enjoy the gamification and experience flow. The agent's behavior would differ depending on which state is detected. Physiological signals such as ECG and EDA have been demonstrated to be very effective in detecting stress \cite{c7, c8}. The WESAD data set \cite{c9} is suitable for our use case as it contains multiple physiological signals from wearable sensors and is annotated for the states we intent to classify (stress, amusement, neutral). We adapt the neural network architecture proposed in \cite{c10} to train an LSTM (Long short-term memory) network to detect stress and amusement.
\subsubsection{Pain} Pain is an important social component, as the expression of pain triggers social reactions such as empathy and care \cite{c2}. Many health-care related fields are deploying image or video based automatic pain detection \cite{c3, c4}. Our idea is to detect pain from the facial expressions of the patient captured by the front camera. To achieve this, we train a deep learning model that can discern pain and no-pain images. We use the images from UNBC-McMaster shoulder pain expression database \cite{c5} to train our model. This data set contains images of 25 participants suffering from shoulder pain while performing a range of motions with their affected and unaffected limb - a scenario similar to our use case. The small number of unique samples in this data set would affect the performance of our model. Similar to \cite{c6}, we use a transfer learning approach to tackle this.
To ensure that our models are generalizable and not over-tuned on a specific dataset, we perform cross-dataset validations by testing our model on different datasets.
\subsection{Socially Interactive Agent and Visual Explanations}
For the presented approach, a socially interactive agent together with the current training task and explanations will be displayed on a monitor Fig.~\ref{fig:system_concept}). The agent acts as a mediator to motivate, inform, and help the patient carry out specific neurorehabilitation tasks. The agent's behavior and the rehabilitation device are tuned in a way that it seems like they are one entity, and the agent is helping the patient apply a certain amount of force. Another task of the agent is to verbally give explanations of the current (and past) states of the training if asked by the patient or if best practice strategies (Sec.~\ref{sec:bpnt}) suggest giving explanations to overcome specific training situations pro-actively.
Technology-wise, the agent's behavior is modeled with the open-source Visual~SceneMaker (VSM, \href{http://scenemaker.dfki.de}{scenemaker.dfki.de}) toolkit \cite{Gebhard-et-al-12}. The tool is explicitly designed to facilitate studies with interactive agents. It comes with a real-time execution and authoring component for modeling verbal and non-verbal behavior of virtual agents and system actions. VSM also allows adapting an agent's behavior relying on external information procedurally. The agent's contributions and behavior are influenced by the patient's social and physiological signals, and these signals are interpreted in real-time by a social signal interpretation framework (SSI, \href{http://openssi.net}{openssi.net}) (Sec.~\ref{sec:ssi}).
The Gloria agent is a high-quality agent with a natural human appearance and verbal and nonverbal dialogue skills. The agent software independently runs in a web browser (\href{https://www.charamel.com}{charamel.com}). The agent is capable of performing social cue-based interaction with the user. It performs lip-sync speech output using the state-of-the-art CereProc (\href{https://www.cereporc.com}{cereproc.com}) Text-To-Speech system. For a more advanced animation control, Gloria allows the direct manipulation of skeleton model joints (e.g., neck joint). In addition, it comes with 36 conversational motion-captured gestures, which can be modified during run-time in some aspects (e.g., overall speed). Moreover, it provides 14 facial expressions, which contains, among others, the six basic emotional expressions defined by Ekman \cite{Ekman92}.
\section{Summary and Future Work}
In this paper, we have presented an approach for an empathetic robotic neurorehabilitation system to help the patients train at home without a therapist but with a socially interactive agent in the role of a coaching assistant. To ensure proper and suitable training exercises, the system is prepared for patients with the help of a professional physiotherapist before it can be used at home. Our vision is to maximize the training effect by measuring social signals, e.g., attentiveness and stress, and physiological signals, e.g., EEG and EDA, to tailor the time and difficulty of training exercises. The interactive social agent motivates and gives explanations. Patients can choose if the agent should behave supportive or demanding.
The following steps consist of evaluating several aspects concerning training efficiency with objective measurements (e.g., overall speed, precision) and standard questionnaires. Furthermore, we investigate if the presence of an interactive agent during therapy sessions has a significant impact on the user's engagement and training progress. Finally, another future evaluation asks if the social and explanatory skills of the system (with or without an agent) impact the training progress?
\bibliographystyle{Bibliography/IEEEtran}
| {'timestamp': '2022-06-06T02:14:58', 'yymm': '2206', 'arxiv_id': '2206.01587', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01587'} | arxiv |
\section{Adapted Experimental Setup}\label{sec:adapted_setup}
\begin{figure*}[!ht]
\centering
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme0n1p1_samsung_throughput.pdf}\label{fig:samsung_iops}}\hfill
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme1n1p2_optane_throughput.pdf}\label{fig:optane_iops}}
\vspace{-0.3cm}
\caption{Peak throughput of (a) the Samsung SSD and (b) the Optane SSD under various fio read and write workloads, with an increasing I/O queue depth (1-1024) and 4KiB block size.}
\label{fig:conventional_iops}
\end{figure*}
Based on the prior failed experiments, we adapt the experimental setup by committing the unused space with a cold file in an effort to fully utilize the ZNS device, instead of leaving the unused space empty. We additionally make use of two conventional SSDs, one of which is a Samsung flash-based SSD and another Optane-based SSD. The conventional SSDs are used to provide a performance comparison between the conventional namespace on the ZNS device and regular SSDs. Detailed characteristics of the additional SSDs are presented in Table~\ref{tab:SSD_architecture}.
The conventional SSDs do not support multiple namespaces, therefore separate partitions are used, with the same 100GB of experimental space, and the remaining space serving as storage for cold data. While the ZNS device used during the experiments supports setting sector sizes of 512B and 4KiB, we set the device to 512B, since the used conventional SSDs only support 512B sectors, and we aim to keep device configurations as similar as possible. Prior to running experiments devices are pre-conditioned to steady state performance by writing the entire space numerous times.
\section{General Information}
Throughout this guide, commands and set up explanation contain names of the specific NVMe device which are depicting their configuration in our system. \textit{nvme0n1p1} depicts the Samsung SSD, and \textit{nvme1n1p2} the Optane SSD, both of which only support a single namespace, requiring a partition to set up the 100GB experimental space. The conventional namespace of the ZNS device is \textit{nvme2n1} and the zoned namepace is \textit{nvme2n2}. We provide scripts for automation of all these benchmarks~\footnote{Available at \url{https://github.com/nicktehrany/ZNS-Study}}, as often numerous steps and retrieval of device specific information is required.
\section{Device Setup}\label{appendix:Device_Setup}
This section contains all required setup for devices, including namespace configuration, as well as the required applications for the different configurations used in this evaluation. To interact with ZNS devices, libnvme~\footnote{Available at \url{https://github.com/linux-nvme/libnvme}}, nvme-cli~\footnote{Available at \url{https://github.com/linux-nvme/nvme-cli}}, blkzone from util-linux~\footnote{Available at \url{https://github.com/util-linux/util-linux}}, libzbd~\footnote{Available at \url{https://github.com/westerndigitalcorporation/libzbd}}, and all their dependencies need to be installed. Note, ZNS integration is largely still new to applications used in this evaluation, therefore using the master branch is often required. Additionally, ZNS support was added to the Linux Kernel 5.9, therefore this version or newer one is required.
\subsection{ZNS Device Configuration}
As we are using several namespaces on the ZNS device, one to expose a small amount of conventional randomly writable area, another of 100GiB (50 zones), and one for the remaining available space. The command for identifying the available size of the device is shown in listing~\ref{Listing:ZNS_info}, note that the ZNS device is configured to a 512B sector size. See Appendix~\ref{appendix:ZNS_info} on how to retrieve the supported sector sizes for a device. Next, the creation of namespaces is depicted in listing~\ref{Listing:ZNS_setup}. After creation of the namespaces, it is important to set the appropriate scheduler for all zones namespaces, as applications often do not do this automatically or check if the desired scheduler is set.
\begin{lstlisting}[language=bash,caption={Setting up NVMe ZNS namespaces.},label={Listing:ZNS_setup}]
# Create a 100GiB namespace, size is given in 512B sectors
$ sudo nvme create-ns /dev/nvme2 -s 209715200 -c 209715200 -b 512 --csi=2
# Repeat for all namespaces with according size
# Attach all namespaces to same controller (adapt -n argument with ns id)
sudo nvme attach-ns /dev/nvme2 -n 1 -c 0
# Set the correct scheduler for all zoned namespaces (adapt device path for each ns)
$ echo mq-deadline | sudo tee /sys/block/nvme2n2/queue/scheduler
\end{lstlisting}
\subsection{f2fs Configuration}
Setting up of f2fs requires f2fs-tools~\footnote{Available at \url{https://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk/f2fs-tools.git/about/}} to make the file system. Configurations of f2fs with a ZNS device require an additional regular block device that is randomly writable, due to f2fs using in place updates for metadata and the superblock. In addition, both devices have to be configured to the same sector size. The exact commands for creating of the f2fs file system and mounting it are shown in listing~\ref{Listing:f2fs}. The order of devices specified lists one or more zoned device, followed by a single conventional block device that is randomly writable. The location of the superblock is used for mounting, hence only the randomly writable device used for file system creating is provided in the mount command.
\begin{lstlisting}[language=bash,caption={Creating and mounting of f2fs file system. Requires the ZNS device and an additional randomly writable block device.},label={Listing:f2fs}]
# Format devices and create fs
$ sudo mkfs.f2fs -f -m -c /dev/nvme2n2 /dev/nvme2n1
$ sudo mount -t f2fs /dev/nvme2n1 /mnt/f2fs/
\end{lstlisting}
\subsection{ZenFS Configuration}
ZenFS~\footnote{Available at \url{https://github.com/westerndigitalcorporation/zenfs}} provides the storage backend for RocksDB to provide usage of ZNS devices. The ZenFS file system allows to be backed up and recovered to avoid data loss in failure events. Setting up of ZenFS requires the zoned device and an additional auxiliary path on another device with a file system, where it places the backup files, as well as any LOG and LOCK files required during RocksDB runtime. The command to set up ZenFS on a zoned device is shown in listing~\ref{Listing:zenfs}. The auxiliary path is placed on a conventional block device that is mounted with f2fs.
\begin{lstlisting}[language=bash,caption={Creating of ZenFS file system. Requires an auxiliary path to place metadata.},label={Listing:zenfs}]
$ sudo ./plugin/zenfs/util/zenfs mkfs --zbd=nvme2n2 --aux_path=/home/nty/rocksdb_aux_path/zenfs2n2
\end{lstlisting}
\subsection{Namespace initialization}
As mentioned previously, we utilize a 100GiB namespace (\textit{nvme2n2}) for experiments and leave the remaining available space in a separate namespace (\textit{nvme2n3}) to be filled with cold data. Listing~\ref{Listing:ZNS_Cold_Data_NS} shows how this is achieved using fio~\footnote{Available at \url{https://github.com/axboe/fio}}. For fio to be able to write the entire namespace on the device, it requires the block size to be a multiple of the zone capacity (see listing~\ref{Listing:ZNS_info} on how to retrieve it). Similarly, the conventional devices (Optane and Samsung SSDs) also have their free space filled with cold data with the second shown command. The command is set up to write 2TiB however, fio will quit once the device is full. Additionally, note that as mentioned earlier the conventional SSDs only support a single namespace and hence have separate partitions set up for the experimental and cold data space.
\begin{lstlisting}[language=bash,caption={Filling namespace 3 with cold data.},label={Listing:ZNS_Cold_Data_NS}]
# Fill ZNS free space with cold data
$ sudo fio --name=zns-fio --filename=/dev/nvme2n3 --direct=1 --size=$((4194304*512*`cat /sys/block/nvme2n3/queue/nr_zones`)) --ioengine=libaio --zonemode=zbd --iodepth=8 --rw=write --bs=512K
# Fill conventional SSD free space with cold data
$ sudo fio --name=zns-fio --filename=/dev/nvme0np2 --direct=1 --size=2T --ioengine=libaio --iodepth=8 --rw=write --bs=512K
\end{lstlisting}
\section{Getting ZNS Device Information}\label{appendix:ZNS_info}
There are several attributes to the ZNS device that are required for later experiments, such as the zone capacity and the number of allowed active zones. Listing~\ref{Listing:ZNS_info} illustrates how to retrieve these. Supported sector sizes can be checked with the provided command, and are presented in powers of 2. Hence, a \textit{lbads:9} is equivalent to $2^9=512$ Bytes. We additionally retrieve the NUMA node at which the device is attached to, in order to pin workloads to this specific NUMA node.
\begin{lstlisting}[language=bash,caption={Retrieving information about the ZNS device.},label={Listing:ZNS_info}]
# Get the available device capacity in 512B sectors
$ sudo nvme id-ctrl /dev/nvme2 | grep tnvmcap | awk '{print $3/512}'
# Get the zone capacity in MiB
$ sudo nvme zns report-zones /dev/nvme2n2 -d 1 | grep -o 'Cap:.*$' | awk '{print strtonum($2)*512/1024/1024}'
# Get maximum supported active zones
$ cat /sys/block/nvme2n2/queue/max_active_zones
# Get the supported sector sizes in powers of 2
$ sudo nvme id-ns /dev/nvme2n2 | grep -o "lbads:[0-9]*"
# Get NUMA node device is attached at
$ cat/sys/block/nvme2n1/device/numa_node
\end{lstlisting}
\section{ZNS Block-Level I/O Performance}
This section contains the commands used to establish the baseline maximum performance of the device, as well as extracted metrics for comparison to later experiments. All experiments for this are using fio as benchmarking tool. Appendix~\ref{appendix:Conv_device_performance} shows the set-up and commands for the provided evaluation in \cref{sec:block-level_ZNS_IO_Conv_ns}, and Appendix~\ref{appendix:Zoned_device_performance} shows the same evaluation on the ZNS device, as presented in \cref{sec:block-level_ZNS_IO_Zoned_ns}.
\subsection{Conventional Device Performance}\label{appendix:Conv_device_performance}
\noindent \textbf{Device throughput:} We run sequential and random writing and reading benchmarks for a block size (I/O size) of 4KiB under varying I/O queue depths to identify the maximum achievable IOPs of the devices. We run this on all three devices, since they all expose the regular conventional block device interface without write constraints, hence we only use the conventional namespace of the ZNS device in this section. The commands are shown in Listing~\ref{listing:conv_performance}.
The order of benchmarks is intentional such that randomwrite first runs, then the namespace is reset and written with the sequential benchmark. Overwrite benchmarks are done similarly with sequential and random writing after the entire namespace is filled with a write benchmark. Note that benchmarks are pinned to the NUMA node where the device is attached (see Appendix~\ref{appendix:ZNS_info} for retrieval of this). All defined variables (indicated by the \$ before a variable) are set up by our script, however for manual running of these commands require to simply be replaced by their associated value. The name and output argument depict naming for our plotting script to parse, however can simply be changed.
\noindent \textbf{ZNS device bandwidth:} We additionally showed the bandwidth scaling for the conventional namespace on the ZNS device for a I/O queue depth of 4 and increasing block sizes, which are shown in Listing~\ref{listing:conv_bandwidth}. Again, replace all defined variables with their respective value.
\begin{lstlisting}[language=bash,caption={Establishing the peak IOPs for the conventional devices with 4KiB block size and varying I/O queue depths.},label={listing:conv_performance}]
# We define several variables, replace these with values
# DEV: device name (e.g., nvme2n1)
# depth: I/O queue depth (from 1-1024 in powers of 2)
# DEV_NUMA_NODE: NUMA Node of the device
# SIZE: device size (e.g., 100G)
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_randwrite_4Ki_queue-depth-$depth --output=$DEV_randwrite_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=randwrite --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
# Reset the namespace between write benchmarks (only on namespaces, not partitions)
$ sudo nvme format /dev/$DEV -f
# Run remaining benchmarks
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_write_4Ki_queue-depth-$depth --output=$DEV_write_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_read_4Ki_queue-depth-$depth --output=$DEV_read_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=read --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_randread_4Ki_queue-depth-$depth --output=$DEV_randread_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=randread --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
# Namespace is still full so run overwrite benchs
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_overwrite-seq_4Ki_queue-depth-$depth --output=$DEV_overwrite-seq_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_overwrite-rand_4Ki_queue-depth-$depth --output=$DEV_overwrite-rand_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=randwrite --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
\end{lstlisting}
\begin{lstlisting}[language=bash,caption={Establishing the maximum achievable bandwidth of the ZNS convention namespace with I/O queue depth of 4 and increasing block size.},label={listing:conv_bandwidth}]
# We define several variables, replace these with values
# DEV: device name (e.g., nvme2n1)
# block_size: I/O size (from 4KiB to 128KiB in powers of 2)
# DEV_NUMA_NODE: NUMA Node of the device
# SIZE: device size (e.g., 100G)
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_randwrite_$block_size_queue-depth-4 --output=$DEV_randwrite_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=randwrite --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
# Reset the namespace between write benchmarks (only on namespaces, not partitions)
$ sudo nvme format /dev/$DEV -f
# Run remaining benchmarks
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_write_$block_size_queue-depth-4 --output=$DEV_write_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=write --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_read_$block_size_queue-depth-4 --output=$DEV_read_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=read --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_randread_$block_size_queue-depth-4 --output=$DEV_randread_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=randread --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
# Namespace is still full so run overwrite benchs
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_overwrite-seq_$block_size_queue-depth-4 --output=$DEV_overwrite-seq_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=write --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_overwrite-rand_$block_size_queue-depth-4 --output=$DEV_overwrite-rand_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=randwrite --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
\end{lstlisting}
\subsection{Zoned Device Performance}\label{appendix:Zoned_device_performance}
We run various workloads on the zoned namespace of the ZNS device, and compare the performance of the scheduler set to \textit{mq-deadline} and \textit{none}. Listing~\ref{Listing:ZNS_setup} showed how to change the scheduler for a namespace. For all benchmarks we utilize fio configured to use 4KiB I/Os.
\noindent \textbf{Write performance:} The benchmarks are shown in Listing~\ref{listing:ZNS_baseline_performance}. The listing also shows the write benchmark that was used to produce Figure~\ref{fig:ZNS_concur_write_seq}. This benchmark writes a single 4KiB I/O to a zone and we increase the number of concurrent writes that are issued to the increasing number of active zones. Therefore, the benchmarks for the different schedulers have the exact same command, and only requires to change the scheduler in between iterations, when the number of concurrent jobs is increased. Note, we also use a 50 zone namespace and have a maximum of 14 active zones, which is why the \textit{offset\_increment} flag is set to 3z, such that each additional thread starts at an increasing offset of 3 zones and all 14 threads can still fit into the namespace when running concurrently. In addition, the write size of each thread is 3z. Also note that the benchmarks with I/O queue depth of 1 and increasing threads over active zones utilize the \textit{psync} ioengine, since I/Os are synchronous, as opposed to \textit{libaio} with asynchronous benchmarks where I/O queue depth is larger than 1.
\begin{lstlisting}[language=bash,caption={Measuring write latency for the schedulers with increasing number of active zones and a single outstanding I/O per zone.},label={listing:ZNS_baseline_performance}]
# We define several variables, replace these with values
# DEV: device name (e.g., nvme2n2)
# DEV_NUMA_NODE: NUMA Node of the device
# scheduler: current scheduler
# jobs: [1-14] number of active zones
# Write benchmark, change the scheduler between iterations
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$(echo "${DEV}_${scheduler}_4Ki_nummjobs-${jobs}") --output=$(echo "${DEV}_${scheduler}_4Ki_numjobs-${jobs}.json") --output-format=json --filename=/dev/$DEV --direct=1 --size=3z --offset_increment=3z --ioengine=psync --zonemode=zbd --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --group_reporting --numjobs=$jobs --percentile_list=50:95
\end{lstlisting}
The next write benchmark, as was shown in Figure~\ref{fig:ZNS_concur_write_seq_iodepth}, runs \textit{mq-deadline} with a single zone and an increasing I/O queue depth and \textit{none} runs just as before, with a single I/O per zone and an increasing number of active zones. Listing~\ref{listing:ZNS_concur_write_seq_iodepth} shows these specific commands. This benchmark defines the size as the total space of the device, since it runs a single thread.
\begin{lstlisting}[language=bash,caption={Measuring write latency for the schedulers with increasing number of active zones and a single outstanding I/O per zone.},label={listing:ZNS_concur_write_seq_iodepth}]
# In addition to the prior defined variables we also define
# SIZE: device size (e.g., 100G)
# depth: [1-14] I/O queue depth,
# and numjobs for none
# mq-deadline benchmark
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$(echo "${DEV}_mq-deadline_${BS}_iodepth-${depth}") --output=$(echo "${DEV}_mq-deadline_${BS}_iodepth-${depth}.json") --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --zonemode=zbd --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --iodepth=$depth --time_based --percentile_list=50:95
# none benchmark
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$(echo "${DEV}_none_4Ki_nummjobs-${jobs}") --output=$(echo "${DEV}_none_4Ki_numjobs-${jobs}.json") --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --offset_increment=3z --ioengine=psync --zonemode=zbd --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --numjobs=$depth --time_based --group_reporting --percentile_list=50:95
\end{lstlisting}
\noindent \textbf{Read performance:} Read performance was measured with sequential reading of 4KiB on a single zone and an increasing I/O queue depth for both schedulers. Recall, that ZNS devices only have a sequential write constraint, and hence read requests can be issued with increasing I/O queue depth under any scheduler and do not have to be at the write pointer of a zone. Listing~\ref{listing:ZNS_concur_read_seq_iodepth} shows the command for this particular benchmark. The benchmark increases only the I/O queue depth from 1 to 14, and commands are the same under both scheduler configurations, however the correct scheduler has to be set before each iteration.
Next, we run the random read benchmark. The \textit{mq-deadline} configuration uses the exact same set up as for sequential reading, namely issuing 4KiB I/Os in a single zone with an increasing I/O queue depth. However, \textit{none} issues a single 4KiB I/O per zone, with an increasing number of concurrent threads. The command from Listing~\ref{listing:ZNS_concur_read_seq_iodepth} can be used for the \textit{mq-deadline} scheduler, and the \textit{none} scheduler can use the command in Listing~\ref{listing:ZNS_concur_write_seq_iodepth}, with the benchmark parameter \textit{--rw=randread}. Note, that similar to the prior read benchmark, the namesapce needs to be full in order to be able to read data.
\begin{lstlisting}[language=bash,caption={Measuring sequential read performance for 4KiB I/Os in a single zone with increasing I/O queue depth.},label={listing:ZNS_concur_read_seq_iodepth}]
# Defined variables
# scheduler: current scheduler
# depth: [1-14] I/O queue depth
# Change scheduler between iterations
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$(echo "${DEV}_${scheduler}_4Ki_iodepth-${depth}") --output=$(echo "${DEV}_${scheduler}_4Ki_iodepth-${depth}.json") --output-format=json --filename=/dev/$DEV --direct=1 --size=SIZE --ioengine=libaio --zonemode=zbd --rw=read --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --iodepth=$depth --time_based --percentile_list=50:95
\end{lstlisting}
\section{Footnotes, Verbatim, and Citations}
\section*{Acknowledgments}
This work is generously supported by Western Digital (WD) donations. Matias Bjørling and the ZNS team at Western
Digital provided many helpful and explanatory comments during the course of this study. We also thank Hans Holmberg for
providing comments and feedback on the report.
Animesh Trivedi is supported by the NWO grant number OCENW.XS3.030, Project Zero: Imagining a Brave CPU-free World!
\section*{Availability}
All the collected data during this evaluation, scripts for running benchmarks, as well as plotting results are made publicly available at \url{https://github.com/nicktehrany/ZNS-Study}. Instructions and commands for usage of ZNS devices and reproducing of this evaluation are additionally provided in the Appendix.
\bibliographystyle{plain}
\section{Adapted Experimental Setup}\label{sec:adapted_setup}
\begin{figure*}[!ht]
\centering
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme0n1p1_samsung_throughput.pdf}\label{fig:samsung_iops}}\hfill
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme1n1p2_optane_throughput.pdf}\label{fig:optane_iops}}
\vspace{-0.3cm}
\caption{Peak throughput of (a) the Samsung SSD and (b) the Optane SSD under various fio read and write workloads, with an increasing I/O queue depth (1-1024) and 4KiB block size.}
\label{fig:conventional_iops}
\end{figure*}
Based on the prior failed experiments, we adapt the experimental setup by committing the unused space with a cold file in an effort to fully utilize the ZNS device, instead of leaving the unused space empty. We additionally make use of two conventional SSDs, one of which is a Samsung flash-based SSD and another Optane-based SSD. The conventional SSDs are used to provide a performance comparison between the conventional namespace on the ZNS device and regular SSDs. Detailed characteristics of the additional SSDs are presented in Table~\ref{tab:SSD_architecture}.
The conventional SSDs do not support multiple namespaces, therefore separate partitions are used, with the same 100GB of experimental space, and the remaining space serving as storage for cold data. While the ZNS device used during the experiments supports setting sector sizes of 512B and 4KiB, we set the device to 512B, since the used conventional SSDs only support 512B sectors, and we aim to keep device configurations as similar as possible. Prior to running experiments devices are pre-conditioned to steady state performance by writing the entire space numerous times.
\section{General Information}
Throughout this guide, commands and set up explanation contain names of the specific NVMe device which are depicting their configuration in our system. \textit{nvme0n1p1} depicts the Samsung SSD, and \textit{nvme1n1p2} the Optane SSD, both of which only support a single namespace, requiring a partition to set up the 100GB experimental space. The conventional namespace of the ZNS device is \textit{nvme2n1} and the zoned namepace is \textit{nvme2n2}. We provide scripts for automation of all these benchmarks~\footnote{Available at \url{https://github.com/nicktehrany/ZNS-Study}}, as often numerous steps and retrieval of device specific information is required.
\section{Device Setup}\label{appendix:Device_Setup}
This section contains all required setup for devices, including namespace configuration, as well as the required applications for the different configurations used in this evaluation. To interact with ZNS devices, libnvme~\footnote{Available at \url{https://github.com/linux-nvme/libnvme}}, nvme-cli~\footnote{Available at \url{https://github.com/linux-nvme/nvme-cli}}, blkzone from util-linux~\footnote{Available at \url{https://github.com/util-linux/util-linux}}, libzbd~\footnote{Available at \url{https://github.com/westerndigitalcorporation/libzbd}}, and all their dependencies need to be installed. Note, ZNS integration is largely still new to applications used in this evaluation, therefore using the master branch is often required. Additionally, ZNS support was added to the Linux Kernel 5.9, therefore this version or newer one is required.
\subsection{ZNS Device Configuration}
As we are using several namespaces on the ZNS device, one to expose a small amount of conventional randomly writable area, another of 100GiB (50 zones), and one for the remaining available space. The command for identifying the available size of the device is shown in listing~\ref{Listing:ZNS_info}, note that the ZNS device is configured to a 512B sector size. See Appendix~\ref{appendix:ZNS_info} on how to retrieve the supported sector sizes for a device. Next, the creation of namespaces is depicted in listing~\ref{Listing:ZNS_setup}. After creation of the namespaces, it is important to set the appropriate scheduler for all zones namespaces, as applications often do not do this automatically or check if the desired scheduler is set.
\begin{lstlisting}[language=bash,caption={Setting up NVMe ZNS namespaces.},label={Listing:ZNS_setup}]
# Create a 100GiB namespace, size is given in 512B sectors
$ sudo nvme create-ns /dev/nvme2 -s 209715200 -c 209715200 -b 512 --csi=2
# Repeat for all namespaces with according size
# Attach all namespaces to same controller (adapt -n argument with ns id)
sudo nvme attach-ns /dev/nvme2 -n 1 -c 0
# Set the correct scheduler for all zoned namespaces (adapt device path for each ns)
$ echo mq-deadline | sudo tee /sys/block/nvme2n2/queue/scheduler
\end{lstlisting}
\subsection{f2fs Configuration}
Setting up of f2fs requires f2fs-tools~\footnote{Available at \url{https://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk/f2fs-tools.git/about/}} to make the file system. Configurations of f2fs with a ZNS device require an additional regular block device that is randomly writable, due to f2fs using in place updates for metadata and the superblock. In addition, both devices have to be configured to the same sector size. The exact commands for creating of the f2fs file system and mounting it are shown in listing~\ref{Listing:f2fs}. The order of devices specified lists one or more zoned device, followed by a single conventional block device that is randomly writable. The location of the superblock is used for mounting, hence only the randomly writable device used for file system creating is provided in the mount command.
\begin{lstlisting}[language=bash,caption={Creating and mounting of f2fs file system. Requires the ZNS device and an additional randomly writable block device.},label={Listing:f2fs}]
# Format devices and create fs
$ sudo mkfs.f2fs -f -m -c /dev/nvme2n2 /dev/nvme2n1
$ sudo mount -t f2fs /dev/nvme2n1 /mnt/f2fs/
\end{lstlisting}
\subsection{ZenFS Configuration}
ZenFS~\footnote{Available at \url{https://github.com/westerndigitalcorporation/zenfs}} provides the storage backend for RocksDB to provide usage of ZNS devices. The ZenFS file system allows to be backed up and recovered to avoid data loss in failure events. Setting up of ZenFS requires the zoned device and an additional auxiliary path on another device with a file system, where it places the backup files, as well as any LOG and LOCK files required during RocksDB runtime. The command to set up ZenFS on a zoned device is shown in listing~\ref{Listing:zenfs}. The auxiliary path is placed on a conventional block device that is mounted with f2fs.
\begin{lstlisting}[language=bash,caption={Creating of ZenFS file system. Requires an auxiliary path to place metadata.},label={Listing:zenfs}]
$ sudo ./plugin/zenfs/util/zenfs mkfs --zbd=nvme2n2 --aux_path=/home/nty/rocksdb_aux_path/zenfs2n2
\end{lstlisting}
\subsection{Namespace initialization}
As mentioned previously, we utilize a 100GiB namespace (\textit{nvme2n2}) for experiments and leave the remaining available space in a separate namespace (\textit{nvme2n3}) to be filled with cold data. Listing~\ref{Listing:ZNS_Cold_Data_NS} shows how this is achieved using fio~\footnote{Available at \url{https://github.com/axboe/fio}}. For fio to be able to write the entire namespace on the device, it requires the block size to be a multiple of the zone capacity (see listing~\ref{Listing:ZNS_info} on how to retrieve it). Similarly, the conventional devices (Optane and Samsung SSDs) also have their free space filled with cold data with the second shown command. The command is set up to write 2TiB however, fio will quit once the device is full. Additionally, note that as mentioned earlier the conventional SSDs only support a single namespace and hence have separate partitions set up for the experimental and cold data space.
\begin{lstlisting}[language=bash,caption={Filling namespace 3 with cold data.},label={Listing:ZNS_Cold_Data_NS}]
# Fill ZNS free space with cold data
$ sudo fio --name=zns-fio --filename=/dev/nvme2n3 --direct=1 --size=$((4194304*512*`cat /sys/block/nvme2n3/queue/nr_zones`)) --ioengine=libaio --zonemode=zbd --iodepth=8 --rw=write --bs=512K
# Fill conventional SSD free space with cold data
$ sudo fio --name=zns-fio --filename=/dev/nvme0np2 --direct=1 --size=2T --ioengine=libaio --iodepth=8 --rw=write --bs=512K
\end{lstlisting}
\section{Getting ZNS Device Information}\label{appendix:ZNS_info}
There are several attributes to the ZNS device that are required for later experiments, such as the zone capacity and the number of allowed active zones. Listing~\ref{Listing:ZNS_info} illustrates how to retrieve these. Supported sector sizes can be checked with the provided command, and are presented in powers of 2. Hence, a \textit{lbads:9} is equivalent to $2^9=512$ Bytes. We additionally retrieve the NUMA node at which the device is attached to, in order to pin workloads to this specific NUMA node.
\begin{lstlisting}[language=bash,caption={Retrieving information about the ZNS device.},label={Listing:ZNS_info}]
# Get the available device capacity in 512B sectors
$ sudo nvme id-ctrl /dev/nvme2 | grep tnvmcap | awk '{print $3/512}'
# Get the zone capacity in MiB
$ sudo nvme zns report-zones /dev/nvme2n2 -d 1 | grep -o 'Cap:.*$' | awk '{print strtonum($2)*512/1024/1024}'
# Get maximum supported active zones
$ cat /sys/block/nvme2n2/queue/max_active_zones
# Get the supported sector sizes in powers of 2
$ sudo nvme id-ns /dev/nvme2n2 | grep -o "lbads:[0-9]*"
# Get NUMA node device is attached at
$ cat/sys/block/nvme2n1/device/numa_node
\end{lstlisting}
\section{ZNS Block-Level I/O Performance}
This section contains the commands used to establish the baseline maximum performance of the device, as well as extracted metrics for comparison to later experiments. All experiments for this are using fio as benchmarking tool. Appendix~\ref{appendix:Conv_device_performance} shows the set-up and commands for the provided evaluation in \cref{sec:block-level_ZNS_IO_Conv_ns}, and Appendix~\ref{appendix:Zoned_device_performance} shows the same evaluation on the ZNS device, as presented in \cref{sec:block-level_ZNS_IO_Zoned_ns}.
\subsection{Conventional Device Performance}\label{appendix:Conv_device_performance}
\noindent \textbf{Device throughput:} We run sequential and random writing and reading benchmarks for a block size (I/O size) of 4KiB under varying I/O queue depths to identify the maximum achievable IOPs of the devices. We run this on all three devices, since they all expose the regular conventional block device interface without write constraints, hence we only use the conventional namespace of the ZNS device in this section. The commands are shown in Listing~\ref{listing:conv_performance}.
The order of benchmarks is intentional such that randomwrite first runs, then the namespace is reset and written with the sequential benchmark. Overwrite benchmarks are done similarly with sequential and random writing after the entire namespace is filled with a write benchmark. Note that benchmarks are pinned to the NUMA node where the device is attached (see Appendix~\ref{appendix:ZNS_info} for retrieval of this). All defined variables (indicated by the \$ before a variable) are set up by our script, however for manual running of these commands require to simply be replaced by their associated value. The name and output argument depict naming for our plotting script to parse, however can simply be changed.
\noindent \textbf{ZNS device bandwidth:} We additionally showed the bandwidth scaling for the conventional namespace on the ZNS device for a I/O queue depth of 4 and increasing block sizes, which are shown in Listing~\ref{listing:conv_bandwidth}. Again, replace all defined variables with their respective value.
\begin{lstlisting}[language=bash,caption={Establishing the peak IOPs for the conventional devices with 4KiB block size and varying I/O queue depths.},label={listing:conv_performance}]
# We define several variables, replace these with values
# DEV: device name (e.g., nvme2n1)
# depth: I/O queue depth (from 1-1024 in powers of 2)
# DEV_NUMA_NODE: NUMA Node of the device
# SIZE: device size (e.g., 100G)
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_randwrite_4Ki_queue-depth-$depth --output=$DEV_randwrite_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=randwrite --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
# Reset the namespace between write benchmarks (only on namespaces, not partitions)
$ sudo nvme format /dev/$DEV -f
# Run remaining benchmarks
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_write_4Ki_queue-depth-$depth --output=$DEV_write_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_read_4Ki_queue-depth-$depth --output=$DEV_read_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=read --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_randread_4Ki_queue-depth-$depth --output=$DEV_randread_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=randread --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
# Namespace is still full so run overwrite benchs
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_overwrite-seq_4Ki_queue-depth-$depth --output=$DEV_overwrite-seq_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_overwrite-rand_4Ki_queue-depth-$depth --output=$DEV_overwrite-rand_4Ki_queue-depth-$depth.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=$depth --rw=randwrite --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
\end{lstlisting}
\begin{lstlisting}[language=bash,caption={Establishing the maximum achievable bandwidth of the ZNS convention namespace with I/O queue depth of 4 and increasing block size.},label={listing:conv_bandwidth}]
# We define several variables, replace these with values
# DEV: device name (e.g., nvme2n1)
# block_size: I/O size (from 4KiB to 128KiB in powers of 2)
# DEV_NUMA_NODE: NUMA Node of the device
# SIZE: device size (e.g., 100G)
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_randwrite_$block_size_queue-depth-4 --output=$DEV_randwrite_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=randwrite --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
# Reset the namespace between write benchmarks (only on namespaces, not partitions)
$ sudo nvme format /dev/$DEV -f
# Run remaining benchmarks
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_write_$block_size_queue-depth-4 --output=$DEV_write_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=write --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_read_$block_size_queue-depth-4 --output=$DEV_read_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=read --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_randread_$block_size_queue-depth-4 --output=$DEV_randread_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=randread --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
# Namespace is still full so run overwrite benchs
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_overwrite-seq_$block_size_queue-depth-4 --output=$DEV_overwrite-seq_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=write --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$DEV_overwrite-rand_$block_size_queue-depth-4 --output=$DEV_overwrite-rand_$block_size_queue-depth-4.json --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --iodepth=4 --rw=randwrite --bs=$block_size --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --time_based --percentile_list=50:95
\end{lstlisting}
\subsection{Zoned Device Performance}\label{appendix:Zoned_device_performance}
We run various workloads on the zoned namespace of the ZNS device, and compare the performance of the scheduler set to \textit{mq-deadline} and \textit{none}. Listing~\ref{Listing:ZNS_setup} showed how to change the scheduler for a namespace. For all benchmarks we utilize fio configured to use 4KiB I/Os.
\noindent \textbf{Write performance:} The benchmarks are shown in Listing~\ref{listing:ZNS_baseline_performance}. The listing also shows the write benchmark that was used to produce Figure~\ref{fig:ZNS_concur_write_seq}. This benchmark writes a single 4KiB I/O to a zone and we increase the number of concurrent writes that are issued to the increasing number of active zones. Therefore, the benchmarks for the different schedulers have the exact same command, and only requires to change the scheduler in between iterations, when the number of concurrent jobs is increased. Note, we also use a 50 zone namespace and have a maximum of 14 active zones, which is why the \textit{offset\_increment} flag is set to 3z, such that each additional thread starts at an increasing offset of 3 zones and all 14 threads can still fit into the namespace when running concurrently. In addition, the write size of each thread is 3z. Also note that the benchmarks with I/O queue depth of 1 and increasing threads over active zones utilize the \textit{psync} ioengine, since I/Os are synchronous, as opposed to \textit{libaio} with asynchronous benchmarks where I/O queue depth is larger than 1.
\begin{lstlisting}[language=bash,caption={Measuring write latency for the schedulers with increasing number of active zones and a single outstanding I/O per zone.},label={listing:ZNS_baseline_performance}]
# We define several variables, replace these with values
# DEV: device name (e.g., nvme2n2)
# DEV_NUMA_NODE: NUMA Node of the device
# scheduler: current scheduler
# jobs: [1-14] number of active zones
# Write benchmark, change the scheduler between iterations
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$(echo "${DEV}_${scheduler}_4Ki_nummjobs-${jobs}") --output=$(echo "${DEV}_${scheduler}_4Ki_numjobs-${jobs}.json") --output-format=json --filename=/dev/$DEV --direct=1 --size=3z --offset_increment=3z --ioengine=psync --zonemode=zbd --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --group_reporting --numjobs=$jobs --percentile_list=50:95
\end{lstlisting}
The next write benchmark, as was shown in Figure~\ref{fig:ZNS_concur_write_seq_iodepth}, runs \textit{mq-deadline} with a single zone and an increasing I/O queue depth and \textit{none} runs just as before, with a single I/O per zone and an increasing number of active zones. Listing~\ref{listing:ZNS_concur_write_seq_iodepth} shows these specific commands. This benchmark defines the size as the total space of the device, since it runs a single thread.
\begin{lstlisting}[language=bash,caption={Measuring write latency for the schedulers with increasing number of active zones and a single outstanding I/O per zone.},label={listing:ZNS_concur_write_seq_iodepth}]
# In addition to the prior defined variables we also define
# SIZE: device size (e.g., 100G)
# depth: [1-14] I/O queue depth,
# and numjobs for none
# mq-deadline benchmark
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$(echo "${DEV}_mq-deadline_${BS}_iodepth-${depth}") --output=$(echo "${DEV}_mq-deadline_${BS}_iodepth-${depth}.json") --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --ioengine=libaio --zonemode=zbd --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --iodepth=$depth --time_based --percentile_list=50:95
# none benchmark
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$(echo "${DEV}_none_4Ki_nummjobs-${jobs}") --output=$(echo "${DEV}_none_4Ki_numjobs-${jobs}.json") --output-format=json --filename=/dev/$DEV --direct=1 --size=$SIZE --offset_increment=3z --ioengine=psync --zonemode=zbd --rw=write --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --numjobs=$depth --time_based --group_reporting --percentile_list=50:95
\end{lstlisting}
\noindent \textbf{Read performance:} Read performance was measured with sequential reading of 4KiB on a single zone and an increasing I/O queue depth for both schedulers. Recall, that ZNS devices only have a sequential write constraint, and hence read requests can be issued with increasing I/O queue depth under any scheduler and do not have to be at the write pointer of a zone. Listing~\ref{listing:ZNS_concur_read_seq_iodepth} shows the command for this particular benchmark. The benchmark increases only the I/O queue depth from 1 to 14, and commands are the same under both scheduler configurations, however the correct scheduler has to be set before each iteration.
Next, we run the random read benchmark. The \textit{mq-deadline} configuration uses the exact same set up as for sequential reading, namely issuing 4KiB I/Os in a single zone with an increasing I/O queue depth. However, \textit{none} issues a single 4KiB I/O per zone, with an increasing number of concurrent threads. The command from Listing~\ref{listing:ZNS_concur_read_seq_iodepth} can be used for the \textit{mq-deadline} scheduler, and the \textit{none} scheduler can use the command in Listing~\ref{listing:ZNS_concur_write_seq_iodepth}, with the benchmark parameter \textit{--rw=randread}. Note, that similar to the prior read benchmark, the namesapce needs to be full in order to be able to read data.
\begin{lstlisting}[language=bash,caption={Measuring sequential read performance for 4KiB I/Os in a single zone with increasing I/O queue depth.},label={listing:ZNS_concur_read_seq_iodepth}]
# Defined variables
# scheduler: current scheduler
# depth: [1-14] I/O queue depth
# Change scheduler between iterations
$ sudo numactl -m $DEV_NUMA_NODE fio --name=$(echo "${DEV}_${scheduler}_4Ki_iodepth-${depth}") --output=$(echo "${DEV}_${scheduler}_4Ki_iodepth-${depth}.json") --output-format=json --filename=/dev/$DEV --direct=1 --size=SIZE --ioengine=libaio --zonemode=zbd --rw=read --bs=4Ki --runtime=30 --numa_cpu_nodes=$DEV_NUMA_NODE --ramp_time=10 --iodepth=$depth --time_based --percentile_list=50:95
\end{lstlisting}
\section{Background}\label{sec:background}
Applications and file systems rely on the Linux block layer to provide interfaces and abstractions for accessing the underlying storage media. Originally designed to match the hardware characteristics of HDDs the block layer presents the storage as a linear address space, allowing for sequential and random writes. Flash storage however has different write constraints due to its architecture. Relying on the FTL to hide the device management idiosyncrasies however leads to negative performance impacts due to the unpredictable performance from the device garbage collection~\cite{2015-Kim-SLO_complying_ssds,2014-yang-dont_stack_log_on_log}, large tail latency it causes~\cite{2013-Dean-tail_at_scale}, and increased write amplification~\cite{2014-Desnoyers-Analytic_Models_SSD}. The increased write amplification additionally reduces the device lifetime, since flash cells on SSDs have limited program/erase cycles.
Furthermore, garbage collection requires the device to maintain a certain amount of free space, called the \textit{overprovisioning space}, such that the FTL is able to move valid pages. Most commonly used overprovisioning takes between 10-28\% of the device capacity. One of the possible FTL design uses a fully-associative mapping of host logical block addresses (LBAs) to physical addresses~\cite{2009-Gupta-DFTL} in order to provide the LBAs of the page(s) that contain valid data. Such a design requires significant resources in order to store all mappings.
\subsection{Zoned Storage}\label{sec:zoned_storage}
The arrival of ZNS SSDs eliminates the need for on device garbage collection done by the FTL, pushing this responsibility to the host. This provides the host with more opportunity for optimized data placement, through mechanisms such as data grouping, and makes garbage collection overheads predictable. The concept of exposing storage as zones is not new, as it was already introduced when Shingled Magnetic Recording (SMR) HDDs~\cite{Feldman2013ShingledMR,Gibson2011PrinciplesOO,Suresh2012ShingledMR} appeared, which also enforce a sequential write constraint. The zoned storage model was established with the addition of Zoned Block Device (ZBD) support in the Linux Kernel 4.10.0~\cite{2021-ZNS-ZBD_docs}, in an effort to avoid the mismatch between the block layer and the sequential write constraint on devices.
The standards defining the management of SMR HDDs in the zoned storage model came through the Zoned Device ATA Command Set (ZAC)~\cite{2015-ZAC} and the Zoned Block Command (ZBC)~\cite{2014-ZBC} specifications. Since zones require sequential writing, the address of the current write is managed with a \textit{write pointer}. The write pointer is incremented to the LBA of the next write only after a successful write. In order to manage zones, each zone has a state associated to it. These are to identify the condition of a zone, which can be any of the following; \textit{EMPTY} to indicate a zone is empty, \textit{OPEN} which is required for a zone to allow writes, \textit{FULL} to indicate the write pointer is at the zone capacity, \textit{CLOSED} which is used to release resources for the zone (e.g., write buffers on the ZNS device) without resetting a zone, this additionally does not allow writes to continue in the zone until it is transitioned to \textit{OPEN} again, \textit{OFFLINE} which makes all data in the zone inaccessible until the zone is reset, and \textit{READ-ONLY}. The command sets provide the proper mechanisms to transition zones between any of the states.
While the majority of available space for both SMR and ZNS devices is utilized by sequential write required zones, they can also expose a limited amount of randomly writable area. This is mainly intended for metadata as this space only occupies a very small percentage of the device capacity. For example, the ZNS device used in this evaluation could expose 4 zones as randomly writable, equivalent to approximately 4GiB, compared to the total device size of 7.2TiB.
\begin{figure}[]
\centering
\includegraphics[width=0.48\textwidth]{figs/ZNS_HW.pdf}
\caption{Layout of a ZNS SSD, depicting zone capacity, write pointer, and zone states associated to each zone. Adapted from~\cite{2021-Bjorling-ZNS}.}
\label{fig:ZNS_HW}
\end{figure}
The newly introduced ZNS SSDs are standardized through the NVMe specification~\cite{2022-nvme-spec}, which builds on the foundations established with ZBD support. While the zoned storage model aims to provide a unified software stack for all zoned devices (SMR and ZNS devices), the NVMe specification introduces several new concepts particular to ZNS devices. Firstly, it defines a \textit{zone capacity} for each zone, stating the usable capacity of a zone, which is less than or equal to the size of the zone. Figure~\ref{fig:ZNS_HW} shows an example layout of zones on a ZNS SSD and each zone's associated state. Zone capacity is kept separate from the zone size such that the capacity can be aligned to the erase unit of the underlying flash media, and such that the zone size can be kept as a power of two value. This is required for easier conversions between LBAs and zone offsets.
Secondly, the \textit{active zones} limit specifies the maximum number of zones that can be active (in \textit{OPEN} or
\textit{CLOSED} state) at any point in time. As the SSD requires to allocate resources for each active zone, such as the
write buffers, it enforces a maximum on the active zones. Lastly, the NVMe specification introduces the \textit{zone
append} command~\cite{bjorling2020zoneappend}, providing the option for the host to maintain multiple outstanding I/Os
in a zone. The ZNS controller writes the data at the write pointer, and returns the LBA of the write to the host.
Therefore, making append especially beneficial if a large number of small writes are issued.
If applications do not utilize the append command, they are required to ensure correct ordering among I/Os such that writes happen at the correct LBA, equal to the write pointer of the zone. ZNS devices additionally require the use of direct I/O, bypassing the page cache. This enforces to align with the sequential write constraint of zones, such that pages from the page cache are not written at out-of-order LBAs.
\subsection{ZNS I/O Scheduling}
Adhering to the sequential write requirement with ZNS devices under multiple outstanding I/O requests requires an appropriate scheduler to be set. It is responsible for ensuring writes are submitted at consecutive LBAs on the device~\cite{2021-ZNS-documentation}. However, requests can additionally be reordered on the device~\cite{2022-nvme-spec}, making the host responsible for ensuring command ordering. For this the \textit{mq-deadline} scheduler has to be enabled. It enforces that just a single write I/O is submitted and holds all subsequent I/Os until completion of the submitted I/O. This allows to submit numerous asynchronous write requests while adhering to the sequential write requirement and enforcing correct command ordering.
Additionally, the scheduler set to \textit{none} can also be used with ZNS devices, bypassing the Linux Kernel I/O scheduler, however this does not enforce sequential write ordering or command ordering, as I/O requests are directly issued to the device. Hence, if this scheduler is set writes have to be issued synchronously and at the correct LBA. As ZNS devices only enforce sequential write ordering, reading can be done with both schedulers asynchronously under any number of outstanding I/Os, and random or sequential accesses.
\subsection{ZNS Application Integration}
With the zoned storage model providing a unified software stack for SMR and ZNS devices and support for SMR having been in numerous applications for some time, required changes for added support of ZNS devices was minimal. We focus primarily on f2fs (with f2fs-tools~\footnote{f2fs-tools provides the mkfs.f2fs functionality to format the storage device in order to mount the f2fs file system. ZNS support was added in version 1.14.0. Available at \url{https://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk/f2fs-tools.git/about}})~\cite{2015-Changman-f2fs}, and ZenFS (commit \textit{5ca1df7})~\cite{2021-Bjorling-ZNS}, a RocksDB storage backend for zoned storage devices.
\noindent \textbf{f2fs:} f2fs had existing support for the ZBC/ZAC specification~\cite{2016-Axboe-f2fs_ZBC_patch}, making the changes for supporting ZNS devices minimal~\cite{2021-Bjorling-ZNS}. The changes include adding the zone capacity and limiting the maximum number of active zones. f2fs manages the storage as a number of segments (typically 2MiB), of which one or more are contained in a section. Sections are the erase unit of f2fs, and segments in a section are written sequentially. The segments are aligned to the zone size, such that they do not span across zones. Since ZNS devices have a zone capacity, which is possibly smaller than the zone size, an additional segment type \textit{unusable} was added in order identify segments outside the usable zone capacity. Partially usable segments are also supported with the \textit{partial} segment type, in order to fully utilize the entire zone capacity if a segment is not aligned to zone capacity.
The maximum active zones was already implemented by limiting the maximum number of open segments at any point in time. By default, this is set to 6, however if the device supports less active zones, f2fs will decrease this at file system creation time. While f2fs supports ZNS devices, it requires an additional randomly writable block device for metadata, which is updated in-place, as well as caching of writes prior to writing to the zoned device.
\noindent \textbf{ZenFS:} ZenFS provides the file system plugin for RocksDB to utilize zoned block devices. RocksDB is an LSM-tree based persistent key-value store~\cite{2017-Dong-Optimizing-RocksDB,2022-Rocksdb-src} optimized for flash based SSDs. It works by maintaining tables at different levels in the LSM tree, of which the first level is in memory and all other levels are on the storage device. Writes initially go into the table in the first level, called the \textit{memtable}, which gets flushed to the next level periodically or when it is full. Flushing will merge the flushed table with one from the next level, such that keys are ordered and do not overlap. This process is called \textit{compaction}. Tables at lower levels than the memtable are referred to as Sorted String Tables (SSTs). SSTs are immutable, written sequentially, and erased as a single unit, hence making it a flash friendly architecture~\cite{2021-Bjorling-ZNS}.
With zoned storage devices the RocksDB data files need to be aligned to the zone capacity for most efficient device utilization. ZenFS maps RocksDB data files to a number of \textit{extents}, which are contiguous regions that are written sequentially. Extents are written to a single zone, such that they do not span across multiple zones, and multiple extents can be written into one zone, depending on the extent size and zone capacity. Selection of extent placement into zones relies on the provided lifetime hints that RocksDB gives with its data files. ZenFS places an extent into a zone where the to be written extent's lifetime is smaller than the largest lifetime of the other extents in the zone, such that it is not unnecessarily delaying the resetting of a zone. ZenFS resets a zone when all the files that have extents in that particular zone have been invalidated.
While RocksDB provides the option to set the maximum size for data files, data files will not have precisely this size due to compaction resulting in varying sized data files. ZenFS manages this by setting a configurable utilization percentage for the zones, which it fills up to this percentage, leaving space if files are larger than specified. While ZenFS requires at least 3 zones to run, of which one is for journaling, another is the metadata, and the last is a data zone, if the device supports more active zones, the active zones can be increased by setting a larger number of concurrent compactions in RocksDB. This can be up to the value of maximum active zones (minus the metadata and journaling zone), however performance gains for more than 12 active zones on particular ZNS devices are insignificant~\cite{2021-Bjorling-ZNS}.
\section{Conclusion}\label{sec:conclusion}
The newly standardized ZNS device present a unique new addition to the host storage stack. Pushing the garbage collection responsibility up in the stack to the host allows for more optimal data placement, providing predictable garbage collection overheads, compared to overheads from conventional flash storage. We provide one of the first systematic studies analyzing the performance implications of ZNS integration, and present an initial set of development guidelines for ZNS devices.
While we mainly focus on the block-level performance of ZNS devices, we additionally provide our unsuccessful experiments and pitfalls to avoid, and furthermore propose numerous future work ideas to evaluate ZNS device integration further and extend the guidelines provided in this work. Main findings in this evaluation show that sequential reads on ZNS devices achieve almost double the peak bandwidth of writes, and larger I/Os ($\ge$ 16KiB) are required for fully saturating the device bandwidth. Additionally, the selection of scheduler for ZNS devices can provide workload dependent performance gains.
\section{Block-Level Device Performance}\label{sec:evaluation}
Focusing on the block-level performance of ZNS devices, we design several benchmarks using the fio benchmarking tool~\cite{fio-src}. In particular, we evaluate the following aspects of ZNS performance:
\begin{itemize}
\item \textbf{ZNS block I/O performance for the conventional namespace (\cref{sec:block-level_ZNS_IO_Conv_ns}).} We establish the baseline performance of block I/O on the ZNS device for its conventional namespace, which is exposed as a small randomly writable space. We measure the achievable throughput and compare it to performance of conventional SSDs. Main findings show that, for achieving peak write bandwidth of the device larger block sizes are required.
\item \textbf{ZNS block I/O performance for the zoned namespace (\cref{sec:block-level_ZNS_IO_Zoned_ns}).} We measure the performance of the ZNS device, benchmarking its zoned namespace. Specifically, we identify the performance of the \textit{mq-deadline} and \textit{none} scheduler under various read and write workloads. Results show that sequential write performance is higher with the \textit{mq-deadline} scheduler, and read performance achieves lower median and tail latency with the scheduler set to \textit{none}.
\end{itemize}
\subsection{Conventional Device Performance}\label{sec:block-level_ZNS_IO_Conv_ns}
To measure the block-level I/O performance of the conventional namespace we run several fio workloads over the namespace and compare its performance to that of the Optane and Samsung SSDs.
\begin{figure*}[!htb]
\centering
\subfloat[\label{fig:ZNS_conv_iops}]{
\begin{tikzpicture}
\node[anchor=south west, inner sep=0] at (2,0) {\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme2n1_ZNS_conv_throughput.pdf}};
\draw[black,thick] (9.5,5.7) -- (9.8,5.7) -- (9.8,4.5) -- (9.5,4.5);
\node[font=\fontsize{8pt}{8pt}\color{black!90},anchor=center,text centered,align=center] at (10.3,5.1) {reads};
\draw[black,thick] (9.5,1.9) -- (9.8,1.9) -- (9.8,1.4) -- (9.5,1.4);
\node[font=\fontsize{8pt}{8pt}\color{black!90},anchor=center,text centered,align=center] at (10.35,1.65) {writes};
\end{tikzpicture}}\hfill
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme2n1_ZNS_conv_scaled_bandwidth.pdf}\label{fig:ZNS_scaled_bw}}
\vspace{-0.3cm}
\caption{Performance evaluation of the conventional namespace on the ZNS device with (a) the peak throughput under various fio read and write workloads, with an increasing I/O queue depth (1-1024) and 4KiB block size, and (b) the maximum achievable bandwidth with an I/O queue depth of 4 and an increasing block size (4KiB-128KiB).}
\end{figure*}
\noindent \textbf{Device throughput:} First, we measure the performance of the Optane and Samsung SSDs. For this, we run a fio benchmark that issues 4KiB read and write I/Os (I/O size is commonly referred to as the block size throughout this section). Specifically, we run the following benchmarks; sequential write, random write, sequential read, random read, sequential overwrite, and random overwrite. The overwrite benchmarks are achieved by fully writing the entire namespace and running a sequential and random write benchmark on the full namespace. Benchmarks are repeated with varying I/O queue depths, indicating the number of outstanding I/Os to maintain~\cite{2017-fio-documentation}. To avoid performance impact of NUMA effects on the results, we pin each workload to the NUMA node where the respective device is attached.
Figures~\ref{fig:samsung_iops} and~\ref{fig:optane_iops} show the performance of the benchmarks for the Samsung SSD and the Optane based SSD, respectively. Both devices show a stable peak performance of 300KIOPs for small queue depths of 4, except for random reading on the Samsung SSD, which requires 16 outstanding I/Os to reach peak IOPs. Next, we run the same benchmarks on the conventional namespace exposed by the ZNS device. Figure~\ref{fig:ZNS_conv_iops} shows that the ZNS device only reaches a peak of 296KIOPs for read benchmarks at deeper queue depths of 8 and 64 for sequential and random reading, respectively. Write benchmarks reach peak performance at a shallow queue depth of 2, however performance is only 19\% of the peak device throughput of 296 KIOPs.
\noindent \textbf{ZNS device bandwidth:} As write performance for the conventional namespace is 81\% below the peak throughput of 296KIOPs, we additionally measure the achievable bandwidth for the ZNS device for larger block sizes. For this, we increase the block size to power of 2 values from 4KiB to 128KiB, and maintain a lower queue depth of 4. The resulting performance is depicted in Figure~\ref{fig:ZNS_scaled_bw}, showing an increase to a peak write bandwidth of 1GiB for block sizes from 16KiB and larger. Note, the throughput in Figure~\ref{fig:ZNS_conv_iops} reached peak performance of 296 KIOPS on sequential reading with a block size of 4KiB and a queue depth of 4, which is equivalent to $296\text{KIOPs}*4\text{KiB}=1.13\text{GiB}$. However, with an increasing block size the bandwidth increases to a peak of 2GiB for sequential reads. Unlike the sequential read performance, the write performance only reaches a peak bandwidth of 1GiB.
\noindent \textbf{Recommendations:} Based on this evaluation we can identify that for the particular ZNS device evaluated \textbf{(i)} sequential reading achieves a 94.2\% larger peak bandwidth than write performance at block size $\geq$ 16KiB, (\textbf{ii}) peak throughput of 296KIOPs for sequential reading is reached at lower queue depth of 4, while random reading requires deeper queues $\geq 64$ to achieve the same throughput, and \textbf{(iii)} for achieving peak write bandwidth of the device larger block sizes ($\geq$ 16KiB) are required.
\subsection{Zoned Device Performance}\label{sec:block-level_ZNS_IO_Zoned_ns}
These benchmarks focus purely on the zoned namespace performance, and quantify the overheads of using \textit{mq-deadline} and \textit{none} schedulers with ZNS devices. The \textit{mq-deadline} scheduler can utilize a higher I/O queue depth ($>1$), as it holds back I/Os and only submits a single I/O at a time, and with \textit{none} the host needs to ensure the I/O queue depth is equal to one.
\noindent \textbf{Read performance:} First, we measure the performance of sequential and random reading with both schedulers. Recall that ZNS does not enforce reading constraints, and thus both schedulers can have any number of outstanding read requests, with sequential or random accesses. The sequential read benchmark is configured to issue 4KiB read I/Os in a single zone, under both schedulers, and an increasing I/O queue depth, ranging from 1-14. Results presented in Figure~\ref{fig:ZNS_concur_read_seq_iodepth} show that the scheduler set to \textit{none} achieves a 9.95\% lower median and 9.66\% lower tail latency at an I/O queue depth of 14. This is due to the added overhead of having the \textit{mq-deadline} scheduler compared to \textit{none} bypassing the Linux I/O scheduler.
Next, we benchmark random read performance. However, as sequential reading in a single zoned showed that bypassing the Linux I/O scheduler provides lower median and tail latency, we measure random reading by utilizing multiple zones for the \textit{none} scheduler. Specifically, \textit{mq-deadline} is set up with the same configuration as with sequential reading, issuing 4KiB I/Os in a single zone with an increasing I/O queue depth, while \textit{none} is set to issue a single I/O to a zone with an increasing number of concurrent threads (also ranging from 1-14, up to the maximum number of active zones). Thus, both schedulers have a particular number of outstanding I/Os (x-axis). Results shown in Figure~\ref{fig:ZNS_concur_read_rand} show that up to 4 outstanding I/Os \textit{mq-deadline} has a higher median latency, ranging between 1.23-4.79\% higher than median latency of \textit{none}. However, for more outstanding I/Os ($> 4$) both schedulers similar performance.
\begin{figure*}[!t]
\centering
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme2n2_concur_read_seq_iodepth.pdf}\label{fig:ZNS_concur_read_seq_iodepth}}\hfill
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme2n2_concur_read_rand.pdf}\label{fig:ZNS_concur_read_rand}}
\vspace{-0.3cm}
\caption{Latency of (a) issuing 4KiB sequential read I/Os in a single zone and increasing I/O queue depth (1-14) with \textit{mq-deadline} and \textit{none} schedulers, and (b) issuing 4KiB random read I/Os in a single zone with \textit{mq-deadline} and a single 4KiB random read I/O in each zone with increasing concurrent threads for the \textit{none} scheduler, giving both schedulers a certain number of outstanding random read I/Os (x-axis).}
\end{figure*}
\begin{figure*}[!htb]
\centering
\subfloat[]{\includegraphics[width=0.48\textwidth]{graphs/IO_Performance/nvme2n2_concur_write_seq.pdf}\label{fig:ZNS_concur_write_seq}}\hfill
\subfloat[]{\includegraphics[width=0.48\textwidth]{graphs/IO_Performance/nvme2n2_concur_write_seq_iodepth.pdf}\label{fig:ZNS_concur_write_seq_iodepth}}
\vspace{-0.3cm}
\caption{Latency of (a) concurrently issuing 4KiB sequential write I/Os over an increasing number of active zones (and threads) and an I/O queue depth of 1 under \textit{mq-deadline} and \textit{none} scheduler, and (b) issuing 4KiB sequential write I/Os with increasing I/O queue depth (1-14) for \textit{mq-deadline} in a single zone, and I/O queue depth of 1 and increasing active zones (1-14) and concurrent threads with \textit{none} scheduler, giving both schedulers a certain number of outstanding write I/O requests (x-axis).}
\end{figure*}
\noindent \textbf{Write performance:} Next, we measure the performance of the ZNS device under write workloads with both schedulers. ZNS devices enforce write constraints, therefore only \textit{mq-deadline} can utilize I/O queue depths $> 1$. We first benchmark the performance of both schedulers by issuing a single 4KiB sequential write I/O in a zone with an increasing number of concurrent threads split across available zones on the device. The number of concurrent threads ranges from 1-14, equivalent to the maximum number of active zones on the device. Figure~\ref{fig:ZNS_concur_write_seq} shows that the resulting performance of both schedulers is nearly identical over all numbers of outstanding I/O requests.
Next, we measure the performance of \textit{mq-deadline} issuing I/Os in a single zone and increasing the I/O queue depth, rather than splitting individual I/Os concurrently across zones. The benchmark with the \textit{none} scheduler is the same as for the prior write benchmark, namely issuing 4KiB I/Os concurrently with an increasing number of threads split across the active zones. This allows both benchmarks to have a specific number of outstanding I/O requests (x-axis). Figure~\ref{fig:ZNS_concur_write_seq_iodepth} shows that the scheduler set to \textit{mq-deadline} achieves a 72.74\% lower median and 83.27\% lower tail latency. The lower latency for \textit{mq-deadline} as the number of outstanding I/Os increases is due to the merging of I/O requests into larger I/Os, as all the I/Os are at consecutive LBAs. This allows it to issue overall less I/Os than with \textit{none} scheduling in this configuration.
\noindent \textbf{Recommendations:} With this evaluation we can identify that \textbf{(i)} random read heavy workloads should avoid the Linux I/O scheduler by setting it to \textit{none}, providing up to 9.95\% lower median latency, and \textbf{(ii)} multiple outstanding write I/Os should utilize the \textit{mq-deadline} scheduler to merge I/Os in a single zone, rather than splitting I/Os concurrently over multiple zones.
\section{Experimental Setup}\label{sec:exp_setup}
\begin{table*}[]
\centering
\begin{tabular}{||c|c|c|c||}
\hline
& Optane SSD & Samsung SSD & ZNS SSD \\ \hline \hline
Model & INTEL SSDPE21D280GA & Samsung SSD 980 PRO & WZS4C8T4TDSP303 \\
Media Size & 260.8GiB & 1.8TiB & 7.2TiB \\
Usable Capacity & 260.8GiB & 1.8TiB & 3.8TiB \\
Sector Size & 512B & 512B & 512B \\
Zone Size & - & - & 2048MiB \\
Zone Capacity & - & - & 1077MiB \\
Number of Zones & - & - & 3688 \\
\hline
\end{tabular}
\caption{SSD architecture of the three utilized devices during experimentation. ZNS information depicts the zoned namespace on the ZNS device.}
\vspace{-0.4cm}
\label{tab:SSD_architecture}
\end{table*}
For the experiments we utilize a ZNS device, whose details and properties are depicted in Table~\ref{tab:SSD_architecture}. The initial goal of this evaluation was to evaluate all possible integrations of ZNS devices. For this we establish the following configuration:
\noindent \textbf{f2fs.} The f2fs (Figure~\ref{fig:ZNS_configurations}(c)) parameters are mostly kept at its default options, with the only change being the enforcing of 10\% overprovisioning. Since f2fs requires a randomly writable device for its metadata, we expose 4 of the zones on the ZNS device as randomly writable space, corresponding to the maximum amount that the ZNS device can expose as randomly writable space. This space is then used by f2fs for metadata and write caching. However, this requires the zoned space of f2fs (where the actual file system data will be) to align with the size of the randomly writable space, i.e., the randomly writable space has to be large enough to fit all the metadata for the file system. Therefore, the resulting largest possible size that successfully formats the f2fs file system on the zoned space is 100GiB. As a result, we create a 100GiB namespace from the available zoned capacity for the f2fs file system, which we utilize for all experiments. We do not use an additional larger randomly writable device, as we aim to avoid performance implications of multiple devices, which would make it difficult to differentiate between performance effects from the ZNS device and the additional block device.
\noindent \textbf{ZenFS.} ZenFS (Figure~\ref{fig:ZNS_configurations}(d)) requires an auxiliary path for its metadata to store LOG and LOCK files for RocksDB at runtime. With this it additionally allows to backup and recover a file system through its command line options, however we do not utilize this option in our evaluation. For the auxiliary path we use the 4GiB randomly writable space exposed by the ZNS device and create a f2fs file system on it which is mounted for solely the ZenFS auxiliary path to be placed on.
As the largest zoned space that successfully formats f2fs is 100GiB, we utilize a 100GiB namespace for all experiments, alongside the 4GiB randomly writable namespace, and all remaining capacity is left in an unused namespace. Throughout the evaluation we refer to the 4GiB randomly writable space exposed by the ZNS device as the \textit{conventional namespace}, and the namespace containing the zoned storage on the ZNS device is referred to as the \textit{zoned namespace}. Lastly, since the ZNS specification was integrated in Linux Kernel 5.9.0+, we use a later Kernel version 5.12.0.
\section{Future Work}\label{sec:future_work}
With ZNS devices having just been introduced, they leave a plethora of avenues to explore. In particular, as we showcased in Figure~\ref{fig:ZNS_configurations}, there are numerous possibilities of integrating ZNS devices into the host software stack. In this evaluation we focus mainly on the block-level ZNS performance and provide several initial guidelines for developers. Expansion of these is left as future work by exploring the additional levels of integration. Specifically this includes evaluating the following aspects of ZNS devices:
\begin{itemize}
\item What is the performance of the varying levels of integration for ZNS devices in terms of achievable IOPs, latency, transactions/sec, and additional instructions required? Under sequential and random, read and write workloads, are there performance implications of a specific integration, and what rules can be established when building applications for a particular integration?
\item How is garbage collection influenced by the different levels of integration? Does building application specific garbage collection policies provide superior performance over other levels of integration? In particular how does an almost fully utilized device (e.g., 95\% utilization) affect garbage collection performance at the different levels?
\item Do multiple applications running on the same ZNS device interfere with each other? This includes a shared device with multiple namespaces, shared block-level interface with for example multiple concurrently running file systems, and lastly a shared file system on ZNS with multiple concurrent applications. Does in each case an application's garbage collection impact the performance of concurrently running applications?
\end{itemize}
As we evaluated some of these aspects and failed to produce insightful results, we propose to evaluate them by taking into account our shortcomings and considering the assumptions we provide in Section~\ref{sec:pitfalls_to_avoid}. An additional exploration that became apparent during this study was that there is currently no enforcing on the number of active zones at a time. The device only allows a maximum number of zones to be active at any point in time, however there is no managing of how active zones are split across namespaces on the device, or across applications running on the same namespace. Especially, as the device supports a larger number of namespaces to be created than active zones that can be open, a zone manager is required to assign zones across namespaces and applications, and provide fair resource sharing across namespaces and applications, enforcing that the maximum number is not exceeded, even if there are more concurrent applications running.
Lastly, we suggest the exploration of file system improvements for f2fs, and other ZNS specific file systems, with grouping of files by creation time, death time, or owner as was suggested in~\cite{2021-Stavrinos-Blockhead} and similarly evaluated for conventional SSDs in~\cite{2017-He-SSD-Unwritten-Contract}. This would provide the possibility for optimizing garbage collection and improving the device performance at the file system integration level.
\section{Introduction}
The introduction of flash storage provided significant changes in the storage hierarchy. Achieving as low as single
digit $\mu$-second latency, several GB/s of bandwidth, and millions of I/O operations per second
(IOPS)~\cite{2022-samsung-zand,2022-intel-p}, they offer significant performance gains over prior storage technologies,
such as Hard Disk Drives (HDDs). Flash storage is organized in pages (typically 16KiB in
size)~\cite{2008-Agrawal-Design-Tradeoff-SSD}, representing the unit of read and write accesses, of which multiple pages
are combined into a block (typically multiple MiB in size). Blocks are further packed in planes and dies to manage data
and control connectivity to the host. Flash pages do not support in-place updates. As a result, pages have to be erased
prior to being written again. However, erase operations require substantially more time than read and write
operations~\cite{2009-Gupta-DFTL}. Therefore, erase operations are done at block granularity to amortize the erase
overhead. Additionally, flash storage requires pages within a block to be written sequentially.
Flash storage therefore includes complex firmware, called the Flash Translation Layer (FTL), to provide the seemingly
in-place updates of data and hide the sequential write constraints of devices by exposing a sector/page-addressable
SSD~\cite{2008-Agrawal-Design-Tradeoff-SSD}. Furthermore, a crucial task of the FTL is to run
\textit{garbage collection} (GC), in order to erase blocks with invalid pages and free up space. For this, the FTL reads out valid pages of
data from a block and relocates the data to a free block, followed by erasing of the original block. Garbage collection
is triggered periodically, or when the device is running low on free space to write data.
The resulting interface exposed by conventional flash storage allows it to mimic the behavior of HDDs, thus requiring
no changes in the host storage software to access the underlying flash storage. However, recent research results made evident that hiding the flash management complexities
from the host leads to suboptimal data placement, unpredictable performance overheads, and shortens the lifetime of
flash devices~\cite{2017-He-SSD-Unwritten-Contract}. Therefore, researchers have proposed to open the flash storage
interface and expose device internals to the host. This allows for the host to optimize storage management with
workload-specific decisions~\cite{2017-fast-lightnvm,2012-asplos-moneta,2014-hotstorage-multistream-ssd,2009-fast-dfs}.
Zoned Namespace (ZNS) SSDs are the latest addition in these efforts, which are now standardized in the NVMe 2.0 specification~\cite{2022-nvme-spec} and are commercially available~\cite{2021-Bjorling-ZNS}. In order to better match the underlying properties of flash chips, ZNS exposes the address space with numerous \textit{zones}, where each zone requires append-only sequential writes. Zones are aligned to the erase unit of a block. With this new interface, the host storage software is now responsible for resetting a zone (i.e., trigger garbage collection) after which a zone becomes writable again from the starting address. Apart from the write restrictions, there are operational parameters such as the zone capacity, the maximum number of active zones limits, and the append limits, which the host software must be aware of.
\begin{figure}[!t]
\centering
\includegraphics[width=0.49\textwidth]{figs/ZNS_configurations.pdf}
\caption{Integration of conventional block devices into the host software stack (a) compared to the three levels of integration for ZNS SSDs (b)-(d) into the software stack.}
\label{fig:ZNS_configurations}
\end{figure}
The new interface of these devices necessitates changes to the host storage stack. However, there is more than one way these devices can be integrated within systems. In a classical setup as shown in Figure~\ref{fig:ZNS_configurations}(a), at the bottom is a block device with a file system on top of it, and an application running on top of the file system. Integrating ZNS devices into this storage stack can be done in three different configurations. Firstly, integration at the block-device level (Figure~\ref{fig:ZNS_configurations}(b)), while keeping the rest of the stack above the same. An example of this setup is the \textit{dm-zap} zoned device mapper project within the Linux Kernel~\cite{2022-dmzap-git}. This way of integration is the least intrusive one and requires the minimum amount of changes to anything running on top of the block device. Secondly, integration at the file system level (Figure~\ref{fig:ZNS_configurations}(c)). For this integration a file system is made aware of the zoned device characteristics such as zone capacity, number of active zones limits, and append limits. Example of such a project is the added ZNS support in f2fs~\cite{2021-Bjorling-ZNS}. With such integration the knowledge and required changes for ZNS devices are pushed higher in the stack, from block-device level to the file system level. Lastly, ZNS-aware application integration (Figure~\ref{fig:ZNS_configurations}(d)). In this case, there are ZNS-specific application-level changes at the very top of the storage stack. By pushing the customization higher up in the stack, the expectation is to deliver better performance together with the best case application-specific customization and integration with ZNS devices. An example of such an integration is the ZenFS file system module for RocksDB and MySQL~\cite{2021-Bjorling-ZNS,2022-zenfs-git}.
With such configuration possibilities, it is not immediately clear which integration one should choose for their workload. In this research work, we aim to systematically understand the impact of the ZNS integration in the host storage system. This work is largely inspired by related work that has provided unwritten contracts of storage devices for Optane based SSDs~\cite{2019-Wu-Unwritten_Contract_Optane} and flash based SSDs~\cite{2017-He-SSD-Unwritten-Contract} with guidelines for developers to optimize storage performance. Before we can synthesize actionable design guidelines for storage stack developers, in this work, we first start with systematic benchmarking in the presence of the OS I/O scheduler. In particular, we make the following contributions:
\begin{itemize}
\item We provide information on the newly standardized NVMe ZNS devices, how these devices work, how they are integrated into the host storage stack, and how existing applications are modified to support ZNS devices.
\item We measure the block-level ZNS device performance, comparing it to conventional block devices in terms of achievable IOPs and bandwidth, and benchmark the possible scheduler configurations for ZNS devices, depicting their implications and limitations.
\item We present pitfalls and failed experiments during this evaluation in an effort for others to learn from and to avoid the obstacles we encountered.
\item We provide a set of initial guidelines for optimizing ZNS integration into systems, and propose several future work ideas to further explore ZNS integration implications and expand our initial set of guidelines.
\item All collected datasets and benchmarking scripts are made publicly available at \url{https://github.com/nicktehrany/ZNS-Study}. The appendix provides more detailed setup and benchmarking information.
\end{itemize}
The remainder of the paper is organized as follows. Section~\ref{sec:background} provides background information on ZNS devices, and their integration into systems. Next, Sections~\ref{sec:exp_setup} explains the experimental setup, followed by the first round of unsuccessful experiments in Section~\ref{sec:unsuccessful_exps}. Based on this we provide an adapted experimental setup in Section~\ref{sec:adapted_setup}, and Section~\ref{sec:evaluation} presents the various benchmarks. Lastly, Section~\ref{sec:related} provides the related work, followed by future work ideas in Section~\ref{sec:future_work}, and Section~\ref{sec:conclusion} concludes the paper.
\section{Related Work}\label{sec:related}
While ZNS has just recently been standardized~\cite{2021-Bjorling-ZNS}, there have been several initial evaluations and discussions of ZNS devices. Bjorling et al.~\cite{2021-Bjorling-ZNS} present modifications made to RocksDB and f2fs to support ZNS devices, and showcase the performance gains for these devices. Stavrinos et al.~\cite{2021-Stavrinos-Blockhead} provide an initial discussion on the benefits of ZNS devices and possible improvements for applications on them. Shin et al.~\cite{shin2020exploring} show a performance study of ZNS devices, depicting the need for large request sizes for achieving increased on-device parallelism. Similar to the results in our study, where the conventional namespace required larger block sizes ($\geq$ 16KiB) to reach peak device bandwidth. Han et al.~\cite{han2021zns+} provide a discussion on the ZNS interface, and propose an improved interface particularly optimized for log-structured file systems with segment compaction. However, there currently is no work that systematically studies the possible ways to integrate ZNS devices into the host software stack. We are the first to present a start at such a study.
As the ZBD model was originally introduced for SMR devices, there have been several performance evaluations of SMR devices and their integration into systems. Wu et al.~\cite{wu2017performance} showcase an extensive evaluation of host-aware SMR drives, which similarly to ZNS device expose device characteristics to the host. In particular, the authors focus on evaluating performance characteristics of the zoned interface. Additionally, Wu et al.~\cite{wu2016evaluating} provide a performance study on implications of different properties of host-aware SMR devices, including performance implications under the number of open zones.
While not focusing on ZNS devices, past work presented similar evaluations for conventional SSDs, where He et al.~\cite{2017-He-SSD-Unwritten-Contract} provide an unwritten contract for flash-based SSDs, depicting numerous guidelines on performance improvements for such devices. Similarly, Wu et al.~\cite{2019-Wu-Unwritten_Contract_Optane} present such an unwritten contract for Optane SSDs. Both of these unwritten contracts were inspiration for us to provide a set of developer guidelines for the new ZNS devices. Yang et al.~\cite{2014-yang-dont_stack_log_on_log} characterize performance implications of building log-structured applications for flash-based SSDs, showcasing the negated benefits of optimizing application data structures for flash, caused by the device characteristics. Such an evaluation showcases application-level integration, which presents insightful results that should be reproduced on ZNS devices to further expand the developer guidelines we provide.
\section{Unsuccessful Experiments}\label{sec:unsuccessful_exps}
Designing of experiments to evaluate the performance of the varying levels of integration proved challenging, as initial experiments did not provide insightful results. We provide the iterations of experimental design and why experiments failed in an effort for others evaluating ZNS performance to avoid these pitfalls. Section~\ref{sec:failed_setup} provides the configurations of the various benchmark, followed by Section~\ref{sec:pitfalls_to_avoid} describing the failures of these benchmarks and pointing out possible causes for this. Lastly, we give additional lessons learned during this evaluation in Section~\ref{sec:lessons_learned}.
\subsection{Benchmark Setup}\label{sec:failed_setup}
We run several benchmarks to evaluate different performance aspects of ZNS devices. While each of the evaluations relies on db\_bench and RocksDB, they have slightly different benchmarking configurations. Below we describe the workload parameters for the different benchmarks.
\subsubsection{Integration Level}
We first benchmark the different possible integration levels, as shown in Figure~\ref{fig:ZNS_configurations}. Benchmarks initially fill the database in random and sequential key order, followed by reading from the database in random and sequential key order. We additionally run an overwrite benchmark, which overwrites existing keys in random order, and an updaterandom workload that modifies values of random keys. The overwrite benchmark and the updaterandom differ in the way values are accessed and modified. Overwrite issues asynchronous writes to the key, whereas updaterandom uses a read-modify-write approach. Keys are 16B each, values are configured to be 100B, and we disable any data compression. As mentioned, ZNS devices require direct I/O, we therefore set appropriate db\_bench flags to issue direct reads and use direct I/O for flushing and compaction.
\subsubsection{ZenFS Benchmark}\label{sec:zenfs_exp}
Next, to verify correctness of our setup we attempt to repeat an experiment depicted in~\cite{2021-Bjorling-ZNS}, comparing db\_bench performance on a configuration with f2fs to a configuration with ZenFS. The focus of this benchmark is write intensive workloads, as this is meant to trigger increased garbage collection and showcase gains of managing ZNS at the application-level with ZenFS. The benchmark is configured to run fillrandom and overwrite with a key size of 100B and value size of 800B. We additionally use data compression to compress data down to 400B. The original paper uses the entire device for its benchmark, however we scale it to the maximum possible that successfully fits into the namespace, which is equivalent to 50 million keys. Lastly, we set the target file size of SST files to be equal to the zone capacity, and again utilize appropriate flags for direct I/O.
\subsubsection{Multi-Tenancy}
Lastly, we run an experiment to evaluate how multiple concurrently running namespaces affect the performance of one another. For this we mount f2fs on the 100GiB zoned namespace and create an additional 100GiB namespace on which ZenFS with a db\_bench benchmark is running. We compare the performance of running the ZenFS namespace alone, without any interference from another namespace, to running the f2fs namespace concurrently. The ZenFS namespace runs the same workload as describe in the previous benchmark (Section~\ref{sec:zenfs_exp}). The goal being that the f2fs namespace creates substantial device traffic through write I/Os, especially during garbage collection from the overwrite benchmark, and thus show the performance impact on the ZenFS namespace.
\subsection{Pitfalls to Avoid}\label{sec:pitfalls_to_avoid}
Results of all experiments showed little to no performance difference in their benchmarks. Especially the ZenFS benchmark (Section~\ref{sec:zenfs_exp}), where the original paper showed substantial performance gains with ZenFS, in particular on overwrite benchmarks where GC is being triggered heavily. We failed to reproduce these exact results and only had minor performance gains from ZenFS. The multi-tenant evaluation showed very similar results, which appear contrary to prior expectations. That is if one namespace fully utilizes the device, then another namespace attempting to use the same device will have some performance implications, as they would now be sharing the device resources.
As the prior experiments proved ineffective in their evaluation, we propose the assumption that for performance
differences to appear on the ZNS device, it has to be largely utilized, such that LBA mappings are fully setup and more
garbage collection is triggered. If the device is not largely utilized, LBA mappings are not fully setup and the device
is able to provide peak performance without showing effects of garbage collection, as there is a large amount of free
space it can utilize. Additionally, the device bandwidth has to be utilized to the extent that it competes with the
garbage collection happening in the background. We therefore believe that with our setup we failed to produce enough
device utilization in bandwidth and space, and thus evaluations showed that there are no performance differences. While
we did not evaluate all configurations under increased garbage collection and device utilization, we believe it to have
an effect on performance and thus suggest its evaluation as future work (discussed in detail in
Section~\ref{sec:future_work}). Per suggestions of Western Digital, for significant performance advantages to appear for
ZNS devices, utilization of available storage capacity should be $>50\%$ (preferably $80\%+$) and bandwidth utilization
of $>30\%$ of the device bandwidth, such that the write workload competes with ongoing garbage collection. However, we
have not evaluated these specific configurations and thus leave it as future work.
\subsection{Lessons Learned}\label{sec:lessons_learned}
In addition to unsuccessful experiments we encountered several obstacles that were not immediately obvious to debug. Again, we provide our experiences in order for others to avoid these pitfalls. Firstly, by default the ZNS devices do not set a scheduler, neither do the applications such as f2fs or ZenFS, nor is there an error on an invalid scheduler being set. Thus setting up of the applications and formatting the ZNS device completes successfully, while as soon as writes are issued to the device I/O errors appear. Therefore, it is important to ensure the correct scheduler is always set, that is the \textit{mq-deadline} scheduler, and every namespace requires it to be set individually after creation. The majority of applications utilize multiple outstanding I/Os per zone, thus the \textit{mq-deadline} scheduler is required, as it will hold back I/Os such that only one outstanding I/O is submitted to the device at any point in time. If the application issues a single I/O synchronously, the scheduler could be left at the default configuration set to \textit{none} (default setting in Linux 5.12.0), however here again the application must enforce the sequential write constraint.
Secondly, device mapper support is not there yet. A device mapper implements a host-side FTL that makes the sequential write required zones randomly writable by exposing the zoned device as a conventional block device. It controls data placement, maintains data mappings, and runs garbage collection, just as the FTL on traditional flash storage. An existing implementation, such as \textit{dm-zoned}~\cite{2016-dmzoned-git} is ZBC and ZAC compliant but not compliant to the new concepts of zone capacity from the ZNS specification. The \textit{dm-zap}~\cite{2022-dmzap-git} device mapper aims to be ZNS compliant, however it is still a prototype and not fully functional with ZNS devices yet. As a result, we are currently not able to evaluate performance of one level of integration (Figure~\ref{fig:ZNS_configurations}(b)), requiring a future evaluation when the device mapper support is functional.
\section{Background}\label{sec:background}
Applications and file systems rely on the Linux block layer to provide interfaces and abstractions for accessing the underlying storage media. Originally designed to match the hardware characteristics of HDDs the block layer presents the storage as a linear address space, allowing for sequential and random writes. Flash storage however has different write constraints due to its architecture. Relying on the FTL to hide the device management idiosyncrasies however leads to negative performance impacts due to the unpredictable performance from the device garbage collection~\cite{2015-Kim-SLO_complying_ssds,2014-yang-dont_stack_log_on_log}, large tail latency it causes~\cite{2013-Dean-tail_at_scale}, and increased write amplification~\cite{2014-Desnoyers-Analytic_Models_SSD}. The increased write amplification additionally reduces the device lifetime, since flash cells on SSDs have limited program/erase cycles.
Furthermore, garbage collection requires the device to maintain a certain amount of free space, called the \textit{overprovisioning space}, such that the FTL is able to move valid pages. Most commonly used overprovisioning takes between 10-28\% of the device capacity. One of the possible FTL design uses a fully-associative mapping of host logical block addresses (LBAs) to physical addresses~\cite{2009-Gupta-DFTL} in order to provide the LBAs of the page(s) that contain valid data. Such a design requires significant resources in order to store all mappings.
\subsection{Zoned Storage}\label{sec:zoned_storage}
The arrival of ZNS SSDs eliminates the need for on device garbage collection done by the FTL, pushing this responsibility to the host. This provides the host with more opportunity for optimized data placement, through mechanisms such as data grouping, and makes garbage collection overheads predictable. The concept of exposing storage as zones is not new, as it was already introduced when Shingled Magnetic Recording (SMR) HDDs~\cite{Feldman2013ShingledMR,Gibson2011PrinciplesOO,Suresh2012ShingledMR} appeared, which also enforce a sequential write constraint. The zoned storage model was established with the addition of Zoned Block Device (ZBD) support in the Linux Kernel 4.10.0~\cite{2021-ZNS-ZBD_docs}, in an effort to avoid the mismatch between the block layer and the sequential write constraint on devices.
The standards defining the management of SMR HDDs in the zoned storage model came through the Zoned Device ATA Command Set (ZAC)~\cite{2015-ZAC} and the Zoned Block Command (ZBC)~\cite{2014-ZBC} specifications. Since zones require sequential writing, the address of the current write is managed with a \textit{write pointer}. The write pointer is incremented to the LBA of the next write only after a successful write. In order to manage zones, each zone has a state associated to it. These are to identify the condition of a zone, which can be any of the following; \textit{EMPTY} to indicate a zone is empty, \textit{OPEN} which is required for a zone to allow writes, \textit{FULL} to indicate the write pointer is at the zone capacity, \textit{CLOSED} which is used to release resources for the zone (e.g., write buffers on the ZNS device) without resetting a zone, this additionally does not allow writes to continue in the zone until it is transitioned to \textit{OPEN} again, \textit{OFFLINE} which makes all data in the zone inaccessible until the zone is reset, and \textit{READ-ONLY}. The command sets provide the proper mechanisms to transition zones between any of the states.
While the majority of available space for both SMR and ZNS devices is utilized by sequential write required zones, they can also expose a limited amount of randomly writable area. This is mainly intended for metadata as this space only occupies a very small percentage of the device capacity. For example, the ZNS device used in this evaluation could expose 4 zones as randomly writable, equivalent to approximately 4GiB, compared to the total device size of 7.2TiB.
\begin{figure}[]
\centering
\includegraphics[width=0.48\textwidth]{figs/ZNS_HW.pdf}
\caption{Layout of a ZNS SSD, depicting zone capacity, write pointer, and zone states associated to each zone. Adapted from~\cite{2021-Bjorling-ZNS}.}
\label{fig:ZNS_HW}
\end{figure}
The newly introduced ZNS SSDs are standardized through the NVMe specification~\cite{2022-nvme-spec}, which builds on the foundations established with ZBD support. While the zoned storage model aims to provide a unified software stack for all zoned devices (SMR and ZNS devices), the NVMe specification introduces several new concepts particular to ZNS devices. Firstly, it defines a \textit{zone capacity} for each zone, stating the usable capacity of a zone, which is less than or equal to the size of the zone. Figure~\ref{fig:ZNS_HW} shows an example layout of zones on a ZNS SSD and each zone's associated state. Zone capacity is kept separate from the zone size such that the capacity can be aligned to the erase unit of the underlying flash media, and such that the zone size can be kept as a power of two value. This is required for easier conversions between LBAs and zone offsets.
Secondly, the \textit{active zones} limit specifies the maximum number of zones that can be active (in \textit{OPEN} or
\textit{CLOSED} state) at any point in time. As the SSD requires to allocate resources for each active zone, such as the
write buffers, it enforces a maximum on the active zones. Lastly, the NVMe specification introduces the \textit{zone
append} command~\cite{bjorling2020zoneappend}, providing the option for the host to maintain multiple outstanding I/Os
in a zone. The ZNS controller writes the data at the write pointer, and returns the LBA of the write to the host.
Therefore, making append especially beneficial if a large number of small writes are issued.
If applications do not utilize the append command, they are required to ensure correct ordering among I/Os such that writes happen at the correct LBA, equal to the write pointer of the zone. ZNS devices additionally require the use of direct I/O, bypassing the page cache. This enforces to align with the sequential write constraint of zones, such that pages from the page cache are not written at out-of-order LBAs.
\subsection{ZNS I/O Scheduling}
Adhering to the sequential write requirement with ZNS devices under multiple outstanding I/O requests requires an appropriate scheduler to be set. It is responsible for ensuring writes are submitted at consecutive LBAs on the device~\cite{2021-ZNS-documentation}. However, requests can additionally be reordered on the device~\cite{2022-nvme-spec}, making the host responsible for ensuring command ordering. For this the \textit{mq-deadline} scheduler has to be enabled. It enforces that just a single write I/O is submitted and holds all subsequent I/Os until completion of the submitted I/O. This allows to submit numerous asynchronous write requests while adhering to the sequential write requirement and enforcing correct command ordering.
Additionally, the scheduler set to \textit{none} can also be used with ZNS devices, bypassing the Linux Kernel I/O scheduler, however this does not enforce sequential write ordering or command ordering, as I/O requests are directly issued to the device. Hence, if this scheduler is set writes have to be issued synchronously and at the correct LBA. As ZNS devices only enforce sequential write ordering, reading can be done with both schedulers asynchronously under any number of outstanding I/Os, and random or sequential accesses.
\subsection{ZNS Application Integration}
With the zoned storage model providing a unified software stack for SMR and ZNS devices and support for SMR having been in numerous applications for some time, required changes for added support of ZNS devices was minimal. We focus primarily on f2fs (with f2fs-tools~\footnote{f2fs-tools provides the mkfs.f2fs functionality to format the storage device in order to mount the f2fs file system. ZNS support was added in version 1.14.0. Available at \url{https://git.kernel.org/pub/scm/linux/kernel/git/jaegeuk/f2fs-tools.git/about}})~\cite{2015-Changman-f2fs}, and ZenFS (commit \textit{5ca1df7})~\cite{2021-Bjorling-ZNS}, a RocksDB storage backend for zoned storage devices.
\noindent \textbf{f2fs:} f2fs had existing support for the ZBC/ZAC specification~\cite{2016-Axboe-f2fs_ZBC_patch}, making the changes for supporting ZNS devices minimal~\cite{2021-Bjorling-ZNS}. The changes include adding the zone capacity and limiting the maximum number of active zones. f2fs manages the storage as a number of segments (typically 2MiB), of which one or more are contained in a section. Sections are the erase unit of f2fs, and segments in a section are written sequentially. The segments are aligned to the zone size, such that they do not span across zones. Since ZNS devices have a zone capacity, which is possibly smaller than the zone size, an additional segment type \textit{unusable} was added in order identify segments outside the usable zone capacity. Partially usable segments are also supported with the \textit{partial} segment type, in order to fully utilize the entire zone capacity if a segment is not aligned to zone capacity.
The maximum active zones was already implemented by limiting the maximum number of open segments at any point in time. By default, this is set to 6, however if the device supports less active zones, f2fs will decrease this at file system creation time. While f2fs supports ZNS devices, it requires an additional randomly writable block device for metadata, which is updated in-place, as well as caching of writes prior to writing to the zoned device.
\noindent \textbf{ZenFS:} ZenFS provides the file system plugin for RocksDB to utilize zoned block devices. RocksDB is an LSM-tree based persistent key-value store~\cite{2017-Dong-Optimizing-RocksDB,2022-Rocksdb-src} optimized for flash based SSDs. It works by maintaining tables at different levels in the LSM tree, of which the first level is in memory and all other levels are on the storage device. Writes initially go into the table in the first level, called the \textit{memtable}, which gets flushed to the next level periodically or when it is full. Flushing will merge the flushed table with one from the next level, such that keys are ordered and do not overlap. This process is called \textit{compaction}. Tables at lower levels than the memtable are referred to as Sorted String Tables (SSTs). SSTs are immutable, written sequentially, and erased as a single unit, hence making it a flash friendly architecture~\cite{2021-Bjorling-ZNS}.
With zoned storage devices the RocksDB data files need to be aligned to the zone capacity for most efficient device utilization. ZenFS maps RocksDB data files to a number of \textit{extents}, which are contiguous regions that are written sequentially. Extents are written to a single zone, such that they do not span across multiple zones, and multiple extents can be written into one zone, depending on the extent size and zone capacity. Selection of extent placement into zones relies on the provided lifetime hints that RocksDB gives with its data files. ZenFS places an extent into a zone where the to be written extent's lifetime is smaller than the largest lifetime of the other extents in the zone, such that it is not unnecessarily delaying the resetting of a zone. ZenFS resets a zone when all the files that have extents in that particular zone have been invalidated.
While RocksDB provides the option to set the maximum size for data files, data files will not have precisely this size due to compaction resulting in varying sized data files. ZenFS manages this by setting a configurable utilization percentage for the zones, which it fills up to this percentage, leaving space if files are larger than specified. While ZenFS requires at least 3 zones to run, of which one is for journaling, another is the metadata, and the last is a data zone, if the device supports more active zones, the active zones can be increased by setting a larger number of concurrent compactions in RocksDB. This can be up to the value of maximum active zones (minus the metadata and journaling zone), however performance gains for more than 12 active zones on particular ZNS devices are insignificant~\cite{2021-Bjorling-ZNS}.
\section{Conclusion}\label{sec:conclusion}
The newly standardized ZNS device present a unique new addition to the host storage stack. Pushing the garbage collection responsibility up in the stack to the host allows for more optimal data placement, providing predictable garbage collection overheads, compared to overheads from conventional flash storage. We provide one of the first systematic studies analyzing the performance implications of ZNS integration, and present an initial set of development guidelines for ZNS devices.
While we mainly focus on the block-level performance of ZNS devices, we additionally provide our unsuccessful experiments and pitfalls to avoid, and furthermore propose numerous future work ideas to evaluate ZNS device integration further and extend the guidelines provided in this work. Main findings in this evaluation show that sequential reads on ZNS devices achieve almost double the peak bandwidth of writes, and larger I/Os ($\ge$ 16KiB) are required for fully saturating the device bandwidth. Additionally, the selection of scheduler for ZNS devices can provide workload dependent performance gains.
\section{Block-Level Device Performance}\label{sec:evaluation}
Focusing on the block-level performance of ZNS devices, we design several benchmarks using the fio benchmarking tool~\cite{fio-src}. In particular, we evaluate the following aspects of ZNS performance:
\begin{itemize}
\item \textbf{ZNS block I/O performance for the conventional namespace (\cref{sec:block-level_ZNS_IO_Conv_ns}).} We establish the baseline performance of block I/O on the ZNS device for its conventional namespace, which is exposed as a small randomly writable space. We measure the achievable throughput and compare it to performance of conventional SSDs. Main findings show that, for achieving peak write bandwidth of the device larger block sizes are required.
\item \textbf{ZNS block I/O performance for the zoned namespace (\cref{sec:block-level_ZNS_IO_Zoned_ns}).} We measure the performance of the ZNS device, benchmarking its zoned namespace. Specifically, we identify the performance of the \textit{mq-deadline} and \textit{none} scheduler under various read and write workloads. Results show that sequential write performance is higher with the \textit{mq-deadline} scheduler, and read performance achieves lower median and tail latency with the scheduler set to \textit{none}.
\end{itemize}
\subsection{Conventional Device Performance}\label{sec:block-level_ZNS_IO_Conv_ns}
To measure the block-level I/O performance of the conventional namespace we run several fio workloads over the namespace and compare its performance to that of the Optane and Samsung SSDs.
\begin{figure*}[!htb]
\centering
\subfloat[\label{fig:ZNS_conv_iops}]{
\begin{tikzpicture}
\node[anchor=south west, inner sep=0] at (2,0) {\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme2n1_ZNS_conv_throughput.pdf}};
\draw[black,thick] (9.5,5.7) -- (9.8,5.7) -- (9.8,4.5) -- (9.5,4.5);
\node[font=\fontsize{8pt}{8pt}\color{black!90},anchor=center,text centered,align=center] at (10.3,5.1) {reads};
\draw[black,thick] (9.5,1.9) -- (9.8,1.9) -- (9.8,1.4) -- (9.5,1.4);
\node[font=\fontsize{8pt}{8pt}\color{black!90},anchor=center,text centered,align=center] at (10.35,1.65) {writes};
\end{tikzpicture}}\hfill
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme2n1_ZNS_conv_scaled_bandwidth.pdf}\label{fig:ZNS_scaled_bw}}
\vspace{-0.3cm}
\caption{Performance evaluation of the conventional namespace on the ZNS device with (a) the peak throughput under various fio read and write workloads, with an increasing I/O queue depth (1-1024) and 4KiB block size, and (b) the maximum achievable bandwidth with an I/O queue depth of 4 and an increasing block size (4KiB-128KiB).}
\end{figure*}
\noindent \textbf{Device throughput:} First, we measure the performance of the Optane and Samsung SSDs. For this, we run a fio benchmark that issues 4KiB read and write I/Os (I/O size is commonly referred to as the block size throughout this section). Specifically, we run the following benchmarks; sequential write, random write, sequential read, random read, sequential overwrite, and random overwrite. The overwrite benchmarks are achieved by fully writing the entire namespace and running a sequential and random write benchmark on the full namespace. Benchmarks are repeated with varying I/O queue depths, indicating the number of outstanding I/Os to maintain~\cite{2017-fio-documentation}. To avoid performance impact of NUMA effects on the results, we pin each workload to the NUMA node where the respective device is attached.
Figures~\ref{fig:samsung_iops} and~\ref{fig:optane_iops} show the performance of the benchmarks for the Samsung SSD and the Optane based SSD, respectively. Both devices show a stable peak performance of 300KIOPs for small queue depths of 4, except for random reading on the Samsung SSD, which requires 16 outstanding I/Os to reach peak IOPs. Next, we run the same benchmarks on the conventional namespace exposed by the ZNS device. Figure~\ref{fig:ZNS_conv_iops} shows that the ZNS device only reaches a peak of 296KIOPs for read benchmarks at deeper queue depths of 8 and 64 for sequential and random reading, respectively. Write benchmarks reach peak performance at a shallow queue depth of 2, however performance is only 19\% of the peak device throughput of 296 KIOPs.
\noindent \textbf{ZNS device bandwidth:} As write performance for the conventional namespace is 81\% below the peak throughput of 296KIOPs, we additionally measure the achievable bandwidth for the ZNS device for larger block sizes. For this, we increase the block size to power of 2 values from 4KiB to 128KiB, and maintain a lower queue depth of 4. The resulting performance is depicted in Figure~\ref{fig:ZNS_scaled_bw}, showing an increase to a peak write bandwidth of 1GiB for block sizes from 16KiB and larger. Note, the throughput in Figure~\ref{fig:ZNS_conv_iops} reached peak performance of 296 KIOPS on sequential reading with a block size of 4KiB and a queue depth of 4, which is equivalent to $296\text{KIOPs}*4\text{KiB}=1.13\text{GiB}$. However, with an increasing block size the bandwidth increases to a peak of 2GiB for sequential reads. Unlike the sequential read performance, the write performance only reaches a peak bandwidth of 1GiB.
\noindent \textbf{Recommendations:} Based on this evaluation we can identify that for the particular ZNS device evaluated \textbf{(i)} sequential reading achieves a 94.2\% larger peak bandwidth than write performance at block size $\geq$ 16KiB, (\textbf{ii}) peak throughput of 296KIOPs for sequential reading is reached at lower queue depth of 4, while random reading requires deeper queues $\geq 64$ to achieve the same throughput, and \textbf{(iii)} for achieving peak write bandwidth of the device larger block sizes ($\geq$ 16KiB) are required.
\subsection{Zoned Device Performance}\label{sec:block-level_ZNS_IO_Zoned_ns}
These benchmarks focus purely on the zoned namespace performance, and quantify the overheads of using \textit{mq-deadline} and \textit{none} schedulers with ZNS devices. The \textit{mq-deadline} scheduler can utilize a higher I/O queue depth ($>1$), as it holds back I/Os and only submits a single I/O at a time, and with \textit{none} the host needs to ensure the I/O queue depth is equal to one.
\noindent \textbf{Read performance:} First, we measure the performance of sequential and random reading with both schedulers. Recall that ZNS does not enforce reading constraints, and thus both schedulers can have any number of outstanding read requests, with sequential or random accesses. The sequential read benchmark is configured to issue 4KiB read I/Os in a single zone, under both schedulers, and an increasing I/O queue depth, ranging from 1-14. Results presented in Figure~\ref{fig:ZNS_concur_read_seq_iodepth} show that the scheduler set to \textit{none} achieves a 9.95\% lower median and 9.66\% lower tail latency at an I/O queue depth of 14. This is due to the added overhead of having the \textit{mq-deadline} scheduler compared to \textit{none} bypassing the Linux I/O scheduler.
Next, we benchmark random read performance. However, as sequential reading in a single zoned showed that bypassing the Linux I/O scheduler provides lower median and tail latency, we measure random reading by utilizing multiple zones for the \textit{none} scheduler. Specifically, \textit{mq-deadline} is set up with the same configuration as with sequential reading, issuing 4KiB I/Os in a single zone with an increasing I/O queue depth, while \textit{none} is set to issue a single I/O to a zone with an increasing number of concurrent threads (also ranging from 1-14, up to the maximum number of active zones). Thus, both schedulers have a particular number of outstanding I/Os (x-axis). Results shown in Figure~\ref{fig:ZNS_concur_read_rand} show that up to 4 outstanding I/Os \textit{mq-deadline} has a higher median latency, ranging between 1.23-4.79\% higher than median latency of \textit{none}. However, for more outstanding I/Os ($> 4$) both schedulers similar performance.
\begin{figure*}[!t]
\centering
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme2n2_concur_read_seq_iodepth.pdf}\label{fig:ZNS_concur_read_seq_iodepth}}\hfill
\subfloat[]{\includegraphics[width=0.45\textwidth]{graphs/IO_Performance/nvme2n2_concur_read_rand.pdf}\label{fig:ZNS_concur_read_rand}}
\vspace{-0.3cm}
\caption{Latency of (a) issuing 4KiB sequential read I/Os in a single zone and increasing I/O queue depth (1-14) with \textit{mq-deadline} and \textit{none} schedulers, and (b) issuing 4KiB random read I/Os in a single zone with \textit{mq-deadline} and a single 4KiB random read I/O in each zone with increasing concurrent threads for the \textit{none} scheduler, giving both schedulers a certain number of outstanding random read I/Os (x-axis).}
\end{figure*}
\begin{figure*}[!htb]
\centering
\subfloat[]{\includegraphics[width=0.48\textwidth]{graphs/IO_Performance/nvme2n2_concur_write_seq.pdf}\label{fig:ZNS_concur_write_seq}}\hfill
\subfloat[]{\includegraphics[width=0.48\textwidth]{graphs/IO_Performance/nvme2n2_concur_write_seq_iodepth.pdf}\label{fig:ZNS_concur_write_seq_iodepth}}
\vspace{-0.3cm}
\caption{Latency of (a) concurrently issuing 4KiB sequential write I/Os over an increasing number of active zones (and threads) and an I/O queue depth of 1 under \textit{mq-deadline} and \textit{none} scheduler, and (b) issuing 4KiB sequential write I/Os with increasing I/O queue depth (1-14) for \textit{mq-deadline} in a single zone, and I/O queue depth of 1 and increasing active zones (1-14) and concurrent threads with \textit{none} scheduler, giving both schedulers a certain number of outstanding write I/O requests (x-axis).}
\end{figure*}
\noindent \textbf{Write performance:} Next, we measure the performance of the ZNS device under write workloads with both schedulers. ZNS devices enforce write constraints, therefore only \textit{mq-deadline} can utilize I/O queue depths $> 1$. We first benchmark the performance of both schedulers by issuing a single 4KiB sequential write I/O in a zone with an increasing number of concurrent threads split across available zones on the device. The number of concurrent threads ranges from 1-14, equivalent to the maximum number of active zones on the device. Figure~\ref{fig:ZNS_concur_write_seq} shows that the resulting performance of both schedulers is nearly identical over all numbers of outstanding I/O requests.
Next, we measure the performance of \textit{mq-deadline} issuing I/Os in a single zone and increasing the I/O queue depth, rather than splitting individual I/Os concurrently across zones. The benchmark with the \textit{none} scheduler is the same as for the prior write benchmark, namely issuing 4KiB I/Os concurrently with an increasing number of threads split across the active zones. This allows both benchmarks to have a specific number of outstanding I/O requests (x-axis). Figure~\ref{fig:ZNS_concur_write_seq_iodepth} shows that the scheduler set to \textit{mq-deadline} achieves a 72.74\% lower median and 83.27\% lower tail latency. The lower latency for \textit{mq-deadline} as the number of outstanding I/Os increases is due to the merging of I/O requests into larger I/Os, as all the I/Os are at consecutive LBAs. This allows it to issue overall less I/Os than with \textit{none} scheduling in this configuration.
\noindent \textbf{Recommendations:} With this evaluation we can identify that \textbf{(i)} random read heavy workloads should avoid the Linux I/O scheduler by setting it to \textit{none}, providing up to 9.95\% lower median latency, and \textbf{(ii)} multiple outstanding write I/Os should utilize the \textit{mq-deadline} scheduler to merge I/Os in a single zone, rather than splitting I/Os concurrently over multiple zones.
\section{Experimental Setup}\label{sec:exp_setup}
\begin{table*}[]
\centering
\begin{tabular}{||c|c|c|c||}
\hline
& Optane SSD & Samsung SSD & ZNS SSD \\ \hline \hline
Model & INTEL SSDPE21D280GA & Samsung SSD 980 PRO & WZS4C8T4TDSP303 \\
Media Size & 260.8GiB & 1.8TiB & 7.2TiB \\
Usable Capacity & 260.8GiB & 1.8TiB & 3.8TiB \\
Sector Size & 512B & 512B & 512B \\
Zone Size & - & - & 2048MiB \\
Zone Capacity & - & - & 1077MiB \\
Number of Zones & - & - & 3688 \\
\hline
\end{tabular}
\caption{SSD architecture of the three utilized devices during experimentation. ZNS information depicts the zoned namespace on the ZNS device.}
\vspace{-0.4cm}
\label{tab:SSD_architecture}
\end{table*}
For the experiments we utilize a ZNS device, whose details and properties are depicted in Table~\ref{tab:SSD_architecture}. The initial goal of this evaluation was to evaluate all possible integrations of ZNS devices. For this we establish the following configuration:
\noindent \textbf{f2fs.} The f2fs (Figure~\ref{fig:ZNS_configurations}(c)) parameters are mostly kept at its default options, with the only change being the enforcing of 10\% overprovisioning. Since f2fs requires a randomly writable device for its metadata, we expose 4 of the zones on the ZNS device as randomly writable space, corresponding to the maximum amount that the ZNS device can expose as randomly writable space. This space is then used by f2fs for metadata and write caching. However, this requires the zoned space of f2fs (where the actual file system data will be) to align with the size of the randomly writable space, i.e., the randomly writable space has to be large enough to fit all the metadata for the file system. Therefore, the resulting largest possible size that successfully formats the f2fs file system on the zoned space is 100GiB. As a result, we create a 100GiB namespace from the available zoned capacity for the f2fs file system, which we utilize for all experiments. We do not use an additional larger randomly writable device, as we aim to avoid performance implications of multiple devices, which would make it difficult to differentiate between performance effects from the ZNS device and the additional block device.
\noindent \textbf{ZenFS.} ZenFS (Figure~\ref{fig:ZNS_configurations}(d)) requires an auxiliary path for its metadata to store LOG and LOCK files for RocksDB at runtime. With this it additionally allows to backup and recover a file system through its command line options, however we do not utilize this option in our evaluation. For the auxiliary path we use the 4GiB randomly writable space exposed by the ZNS device and create a f2fs file system on it which is mounted for solely the ZenFS auxiliary path to be placed on.
As the largest zoned space that successfully formats f2fs is 100GiB, we utilize a 100GiB namespace for all experiments, alongside the 4GiB randomly writable namespace, and all remaining capacity is left in an unused namespace. Throughout the evaluation we refer to the 4GiB randomly writable space exposed by the ZNS device as the \textit{conventional namespace}, and the namespace containing the zoned storage on the ZNS device is referred to as the \textit{zoned namespace}. Lastly, since the ZNS specification was integrated in Linux Kernel 5.9.0+, we use a later Kernel version 5.12.0.
\section{Future Work}\label{sec:future_work}
With ZNS devices having just been introduced, they leave a plethora of avenues to explore. In particular, as we showcased in Figure~\ref{fig:ZNS_configurations}, there are numerous possibilities of integrating ZNS devices into the host software stack. In this evaluation we focus mainly on the block-level ZNS performance and provide several initial guidelines for developers. Expansion of these is left as future work by exploring the additional levels of integration. Specifically this includes evaluating the following aspects of ZNS devices:
\begin{itemize}
\item What is the performance of the varying levels of integration for ZNS devices in terms of achievable IOPs, latency, transactions/sec, and additional instructions required? Under sequential and random, read and write workloads, are there performance implications of a specific integration, and what rules can be established when building applications for a particular integration?
\item How is garbage collection influenced by the different levels of integration? Does building application specific garbage collection policies provide superior performance over other levels of integration? In particular how does an almost fully utilized device (e.g., 95\% utilization) affect garbage collection performance at the different levels?
\item Do multiple applications running on the same ZNS device interfere with each other? This includes a shared device with multiple namespaces, shared block-level interface with for example multiple concurrently running file systems, and lastly a shared file system on ZNS with multiple concurrent applications. Does in each case an application's garbage collection impact the performance of concurrently running applications?
\end{itemize}
As we evaluated some of these aspects and failed to produce insightful results, we propose to evaluate them by taking into account our shortcomings and considering the assumptions we provide in Section~\ref{sec:pitfalls_to_avoid}. An additional exploration that became apparent during this study was that there is currently no enforcing on the number of active zones at a time. The device only allows a maximum number of zones to be active at any point in time, however there is no managing of how active zones are split across namespaces on the device, or across applications running on the same namespace. Especially, as the device supports a larger number of namespaces to be created than active zones that can be open, a zone manager is required to assign zones across namespaces and applications, and provide fair resource sharing across namespaces and applications, enforcing that the maximum number is not exceeded, even if there are more concurrent applications running.
Lastly, we suggest the exploration of file system improvements for f2fs, and other ZNS specific file systems, with grouping of files by creation time, death time, or owner as was suggested in~\cite{2021-Stavrinos-Blockhead} and similarly evaluated for conventional SSDs in~\cite{2017-He-SSD-Unwritten-Contract}. This would provide the possibility for optimizing garbage collection and improving the device performance at the file system integration level.
\section{Introduction}
The introduction of flash storage provided significant changes in the storage hierarchy. Achieving as low as single
digit $\mu$-second latency, several GB/s of bandwidth, and millions of I/O operations per second
(IOPS)~\cite{2022-samsung-zand,2022-intel-p}, they offer significant performance gains over prior storage technologies,
such as Hard Disk Drives (HDDs). Flash storage is organized in pages (typically 16KiB in
size)~\cite{2008-Agrawal-Design-Tradeoff-SSD}, representing the unit of read and write accesses, of which multiple pages
are combined into a block (typically multiple MiB in size). Blocks are further packed in planes and dies to manage data
and control connectivity to the host. Flash pages do not support in-place updates. As a result, pages have to be erased
prior to being written again. However, erase operations require substantially more time than read and write
operations~\cite{2009-Gupta-DFTL}. Therefore, erase operations are done at block granularity to amortize the erase
overhead. Additionally, flash storage requires pages within a block to be written sequentially.
Flash storage therefore includes complex firmware, called the Flash Translation Layer (FTL), to provide the seemingly
in-place updates of data and hide the sequential write constraints of devices by exposing a sector/page-addressable
SSD~\cite{2008-Agrawal-Design-Tradeoff-SSD}. Furthermore, a crucial task of the FTL is to run
\textit{garbage collection} (GC), in order to erase blocks with invalid pages and free up space. For this, the FTL reads out valid pages of
data from a block and relocates the data to a free block, followed by erasing of the original block. Garbage collection
is triggered periodically, or when the device is running low on free space to write data.
The resulting interface exposed by conventional flash storage allows it to mimic the behavior of HDDs, thus requiring
no changes in the host storage software to access the underlying flash storage. However, recent research results made evident that hiding the flash management complexities
from the host leads to suboptimal data placement, unpredictable performance overheads, and shortens the lifetime of
flash devices~\cite{2017-He-SSD-Unwritten-Contract}. Therefore, researchers have proposed to open the flash storage
interface and expose device internals to the host. This allows for the host to optimize storage management with
workload-specific decisions~\cite{2017-fast-lightnvm,2012-asplos-moneta,2014-hotstorage-multistream-ssd,2009-fast-dfs}.
Zoned Namespace (ZNS) SSDs are the latest addition in these efforts, which are now standardized in the NVMe 2.0 specification~\cite{2022-nvme-spec} and are commercially available~\cite{2021-Bjorling-ZNS}. In order to better match the underlying properties of flash chips, ZNS exposes the address space with numerous \textit{zones}, where each zone requires append-only sequential writes. Zones are aligned to the erase unit of a block. With this new interface, the host storage software is now responsible for resetting a zone (i.e., trigger garbage collection) after which a zone becomes writable again from the starting address. Apart from the write restrictions, there are operational parameters such as the zone capacity, the maximum number of active zones limits, and the append limits, which the host software must be aware of.
\begin{figure}[!t]
\centering
\includegraphics[width=0.49\textwidth]{figs/ZNS_configurations.pdf}
\caption{Integration of conventional block devices into the host software stack (a) compared to the three levels of integration for ZNS SSDs (b)-(d) into the software stack.}
\label{fig:ZNS_configurations}
\end{figure}
The new interface of these devices necessitates changes to the host storage stack. However, there is more than one way these devices can be integrated within systems. In a classical setup as shown in Figure~\ref{fig:ZNS_configurations}(a), at the bottom is a block device with a file system on top of it, and an application running on top of the file system. Integrating ZNS devices into this storage stack can be done in three different configurations. Firstly, integration at the block-device level (Figure~\ref{fig:ZNS_configurations}(b)), while keeping the rest of the stack above the same. An example of this setup is the \textit{dm-zap} zoned device mapper project within the Linux Kernel~\cite{2022-dmzap-git}. This way of integration is the least intrusive one and requires the minimum amount of changes to anything running on top of the block device. Secondly, integration at the file system level (Figure~\ref{fig:ZNS_configurations}(c)). For this integration a file system is made aware of the zoned device characteristics such as zone capacity, number of active zones limits, and append limits. Example of such a project is the added ZNS support in f2fs~\cite{2021-Bjorling-ZNS}. With such integration the knowledge and required changes for ZNS devices are pushed higher in the stack, from block-device level to the file system level. Lastly, ZNS-aware application integration (Figure~\ref{fig:ZNS_configurations}(d)). In this case, there are ZNS-specific application-level changes at the very top of the storage stack. By pushing the customization higher up in the stack, the expectation is to deliver better performance together with the best case application-specific customization and integration with ZNS devices. An example of such an integration is the ZenFS file system module for RocksDB and MySQL~\cite{2021-Bjorling-ZNS,2022-zenfs-git}.
With such configuration possibilities, it is not immediately clear which integration one should choose for their workload. In this research work, we aim to systematically understand the impact of the ZNS integration in the host storage system. This work is largely inspired by related work that has provided unwritten contracts of storage devices for Optane based SSDs~\cite{2019-Wu-Unwritten_Contract_Optane} and flash based SSDs~\cite{2017-He-SSD-Unwritten-Contract} with guidelines for developers to optimize storage performance. Before we can synthesize actionable design guidelines for storage stack developers, in this work, we first start with systematic benchmarking in the presence of the OS I/O scheduler. In particular, we make the following contributions:
\begin{itemize}
\item We provide information on the newly standardized NVMe ZNS devices, how these devices work, how they are integrated into the host storage stack, and how existing applications are modified to support ZNS devices.
\item We measure the block-level ZNS device performance, comparing it to conventional block devices in terms of achievable IOPs and bandwidth, and benchmark the possible scheduler configurations for ZNS devices, depicting their implications and limitations.
\item We present pitfalls and failed experiments during this evaluation in an effort for others to learn from and to avoid the obstacles we encountered.
\item We provide a set of initial guidelines for optimizing ZNS integration into systems, and propose several future work ideas to further explore ZNS integration implications and expand our initial set of guidelines.
\item All collected datasets and benchmarking scripts are made publicly available at \url{https://github.com/nicktehrany/ZNS-Study}. The appendix provides more detailed setup and benchmarking information.
\end{itemize}
The remainder of the paper is organized as follows. Section~\ref{sec:background} provides background information on ZNS devices, and their integration into systems. Next, Sections~\ref{sec:exp_setup} explains the experimental setup, followed by the first round of unsuccessful experiments in Section~\ref{sec:unsuccessful_exps}. Based on this we provide an adapted experimental setup in Section~\ref{sec:adapted_setup}, and Section~\ref{sec:evaluation} presents the various benchmarks. Lastly, Section~\ref{sec:related} provides the related work, followed by future work ideas in Section~\ref{sec:future_work}, and Section~\ref{sec:conclusion} concludes the paper.
\section{Footnotes, Verbatim, and Citations}
\section*{Acknowledgments}
This work is generously supported by Western Digital (WD) donations. Matias Bjørling and the ZNS team at Western
Digital provided many helpful and explanatory comments during the course of this study. We also thank Hans Holmberg for
providing comments and feedback on the report.
Animesh Trivedi is supported by the NWO grant number OCENW.XS3.030, Project Zero: Imagining a Brave CPU-free World!
\section*{Availability}
All the collected data during this evaluation, scripts for running benchmarks, as well as plotting results are made publicly available at \url{https://github.com/nicktehrany/ZNS-Study}. Instructions and commands for usage of ZNS devices and reproducing of this evaluation are additionally provided in the Appendix.
\bibliographystyle{plain}
\section{Related Work}\label{sec:related}
While ZNS has just recently been standardized~\cite{2021-Bjorling-ZNS}, there have been several initial evaluations and discussions of ZNS devices. Bjorling et al.~\cite{2021-Bjorling-ZNS} present modifications made to RocksDB and f2fs to support ZNS devices, and showcase the performance gains for these devices. Stavrinos et al.~\cite{2021-Stavrinos-Blockhead} provide an initial discussion on the benefits of ZNS devices and possible improvements for applications on them. Shin et al.~\cite{shin2020exploring} show a performance study of ZNS devices, depicting the need for large request sizes for achieving increased on-device parallelism. Similar to the results in our study, where the conventional namespace required larger block sizes ($\geq$ 16KiB) to reach peak device bandwidth. Han et al.~\cite{han2021zns+} provide a discussion on the ZNS interface, and propose an improved interface particularly optimized for log-structured file systems with segment compaction. However, there currently is no work that systematically studies the possible ways to integrate ZNS devices into the host software stack. We are the first to present a start at such a study.
As the ZBD model was originally introduced for SMR devices, there have been several performance evaluations of SMR devices and their integration into systems. Wu et al.~\cite{wu2017performance} showcase an extensive evaluation of host-aware SMR drives, which similarly to ZNS device expose device characteristics to the host. In particular, the authors focus on evaluating performance characteristics of the zoned interface. Additionally, Wu et al.~\cite{wu2016evaluating} provide a performance study on implications of different properties of host-aware SMR devices, including performance implications under the number of open zones.
While not focusing on ZNS devices, past work presented similar evaluations for conventional SSDs, where He et al.~\cite{2017-He-SSD-Unwritten-Contract} provide an unwritten contract for flash-based SSDs, depicting numerous guidelines on performance improvements for such devices. Similarly, Wu et al.~\cite{2019-Wu-Unwritten_Contract_Optane} present such an unwritten contract for Optane SSDs. Both of these unwritten contracts were inspiration for us to provide a set of developer guidelines for the new ZNS devices. Yang et al.~\cite{2014-yang-dont_stack_log_on_log} characterize performance implications of building log-structured applications for flash-based SSDs, showcasing the negated benefits of optimizing application data structures for flash, caused by the device characteristics. Such an evaluation showcases application-level integration, which presents insightful results that should be reproduced on ZNS devices to further expand the developer guidelines we provide.
\section{Unsuccessful Experiments}\label{sec:unsuccessful_exps}
Designing of experiments to evaluate the performance of the varying levels of integration proved challenging, as initial experiments did not provide insightful results. We provide the iterations of experimental design and why experiments failed in an effort for others evaluating ZNS performance to avoid these pitfalls. Section~\ref{sec:failed_setup} provides the configurations of the various benchmark, followed by Section~\ref{sec:pitfalls_to_avoid} describing the failures of these benchmarks and pointing out possible causes for this. Lastly, we give additional lessons learned during this evaluation in Section~\ref{sec:lessons_learned}.
\subsection{Benchmark Setup}\label{sec:failed_setup}
We run several benchmarks to evaluate different performance aspects of ZNS devices. While each of the evaluations relies on db\_bench and RocksDB, they have slightly different benchmarking configurations. Below we describe the workload parameters for the different benchmarks.
\subsubsection{Integration Level}
We first benchmark the different possible integration levels, as shown in Figure~\ref{fig:ZNS_configurations}. Benchmarks initially fill the database in random and sequential key order, followed by reading from the database in random and sequential key order. We additionally run an overwrite benchmark, which overwrites existing keys in random order, and an updaterandom workload that modifies values of random keys. The overwrite benchmark and the updaterandom differ in the way values are accessed and modified. Overwrite issues asynchronous writes to the key, whereas updaterandom uses a read-modify-write approach. Keys are 16B each, values are configured to be 100B, and we disable any data compression. As mentioned, ZNS devices require direct I/O, we therefore set appropriate db\_bench flags to issue direct reads and use direct I/O for flushing and compaction.
\subsubsection{ZenFS Benchmark}\label{sec:zenfs_exp}
Next, to verify correctness of our setup we attempt to repeat an experiment depicted in~\cite{2021-Bjorling-ZNS}, comparing db\_bench performance on a configuration with f2fs to a configuration with ZenFS. The focus of this benchmark is write intensive workloads, as this is meant to trigger increased garbage collection and showcase gains of managing ZNS at the application-level with ZenFS. The benchmark is configured to run fillrandom and overwrite with a key size of 100B and value size of 800B. We additionally use data compression to compress data down to 400B. The original paper uses the entire device for its benchmark, however we scale it to the maximum possible that successfully fits into the namespace, which is equivalent to 50 million keys. Lastly, we set the target file size of SST files to be equal to the zone capacity, and again utilize appropriate flags for direct I/O.
\subsubsection{Multi-Tenancy}
Lastly, we run an experiment to evaluate how multiple concurrently running namespaces affect the performance of one another. For this we mount f2fs on the 100GiB zoned namespace and create an additional 100GiB namespace on which ZenFS with a db\_bench benchmark is running. We compare the performance of running the ZenFS namespace alone, without any interference from another namespace, to running the f2fs namespace concurrently. The ZenFS namespace runs the same workload as describe in the previous benchmark (Section~\ref{sec:zenfs_exp}). The goal being that the f2fs namespace creates substantial device traffic through write I/Os, especially during garbage collection from the overwrite benchmark, and thus show the performance impact on the ZenFS namespace.
\subsection{Pitfalls to Avoid}\label{sec:pitfalls_to_avoid}
Results of all experiments showed little to no performance difference in their benchmarks. Especially the ZenFS benchmark (Section~\ref{sec:zenfs_exp}), where the original paper showed substantial performance gains with ZenFS, in particular on overwrite benchmarks where GC is being triggered heavily. We failed to reproduce these exact results and only had minor performance gains from ZenFS. The multi-tenant evaluation showed very similar results, which appear contrary to prior expectations. That is if one namespace fully utilizes the device, then another namespace attempting to use the same device will have some performance implications, as they would now be sharing the device resources.
As the prior experiments proved ineffective in their evaluation, we propose the assumption that for performance
differences to appear on the ZNS device, it has to be largely utilized, such that LBA mappings are fully setup and more
garbage collection is triggered. If the device is not largely utilized, LBA mappings are not fully setup and the device
is able to provide peak performance without showing effects of garbage collection, as there is a large amount of free
space it can utilize. Additionally, the device bandwidth has to be utilized to the extent that it competes with the
garbage collection happening in the background. We therefore believe that with our setup we failed to produce enough
device utilization in bandwidth and space, and thus evaluations showed that there are no performance differences. While
we did not evaluate all configurations under increased garbage collection and device utilization, we believe it to have
an effect on performance and thus suggest its evaluation as future work (discussed in detail in
Section~\ref{sec:future_work}). Per suggestions of Western Digital, for significant performance advantages to appear for
ZNS devices, utilization of available storage capacity should be $>50\%$ (preferably $80\%+$) and bandwidth utilization
of $>30\%$ of the device bandwidth, such that the write workload competes with ongoing garbage collection. However, we
have not evaluated these specific configurations and thus leave it as future work.
\subsection{Lessons Learned}\label{sec:lessons_learned}
In addition to unsuccessful experiments we encountered several obstacles that were not immediately obvious to debug. Again, we provide our experiences in order for others to avoid these pitfalls. Firstly, by default the ZNS devices do not set a scheduler, neither do the applications such as f2fs or ZenFS, nor is there an error on an invalid scheduler being set. Thus setting up of the applications and formatting the ZNS device completes successfully, while as soon as writes are issued to the device I/O errors appear. Therefore, it is important to ensure the correct scheduler is always set, that is the \textit{mq-deadline} scheduler, and every namespace requires it to be set individually after creation. The majority of applications utilize multiple outstanding I/Os per zone, thus the \textit{mq-deadline} scheduler is required, as it will hold back I/Os such that only one outstanding I/O is submitted to the device at any point in time. If the application issues a single I/O synchronously, the scheduler could be left at the default configuration set to \textit{none} (default setting in Linux 5.12.0), however here again the application must enforce the sequential write constraint.
Secondly, device mapper support is not there yet. A device mapper implements a host-side FTL that makes the sequential write required zones randomly writable by exposing the zoned device as a conventional block device. It controls data placement, maintains data mappings, and runs garbage collection, just as the FTL on traditional flash storage. An existing implementation, such as \textit{dm-zoned}~\cite{2016-dmzoned-git} is ZBC and ZAC compliant but not compliant to the new concepts of zone capacity from the ZNS specification. The \textit{dm-zap}~\cite{2022-dmzap-git} device mapper aims to be ZNS compliant, however it is still a prototype and not fully functional with ZNS devices yet. As a result, we are currently not able to evaluate performance of one level of integration (Figure~\ref{fig:ZNS_configurations}(b)), requiring a future evaluation when the device mapper support is functional.
| {'timestamp': '2022-06-06T02:13:28', 'yymm': '2206', 'arxiv_id': '2206.01547', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01547'} | arxiv |
\subsection{AlphaStar cost estimation}
\label{app:alphastar}
We estimate the cost of AlphaStar~\citep{vinyals2019grandmaster} based on the following description in the paper:
``In StarCraft, each player chooses one of three races — Terran, Protoss or Zerg — each with distinct mechanics. We trained the league using three main agents (one for each StarCraft race), three main exploiter agents (one for each race), and six league exploiter agents (two for each race). Each agent was trained using 32 third-generation tensor processing units (TPUv3) over 44 days.''
This corresponds to a total of 12 agents (= 3 main + 3 exploiter + 6 league) trained for a total of 1056 TPU hours = 44 days * 24 hours/day on 32 TPU v3 chips. As per current pricing\footnote{\url{https://cloud.google.com/tpu/pricing}}, TPUv3~(v3-8) cost $\$8$ per hour. Based on this, we estimate the cost of replicating AlphaStar results for an independent researcher would be at $1056 * 12 * 32 * \$8 = \$3, 244, 032$. Please note that we are only considering the cost of replication and not accounting for other costs such as hyperparameter tuning and evaluation.
\subsection{Open-source code and checkpoints}
\label{app:opensource}
We will open-source our code for ALE experiments at \href{https://agarwl.github.io/reincarnating_rl}{agarwl.github.io/reincarnating\_rl}. Since the model checkpoints for ALE require a large amount of memory, we have released them in the public GCP bucket \href{https://console.cloud.google.com/storage/browser/rl_checkpoints}{gs://rl\_checkpoints}\footnote{\url{https://console.cloud.google.com/storage/browser/rl_checkpoints}}, which can be easily downloaded using \href{https://cloud.google.com/storage/docs/gsutil}{gsutil}.
\subsection{Compute resources for PVRL experiments}
\label{app:compute}
For experiments in \secref{sec:value_policy}, we used a P100 GPU. For obtaining the teacher policy, the cost of running the tabula rasa DQN for 400M frames for 10 games on 3 seeds each roughly amounts to 7 days x 30 = 210 days of compute on a P100 GPU. For each of the PVRL methods, we trained on 10 games with 3 runs each for 10M frames, which roughly translates to 4-5 hours. For offline pretraining, we train methods for 1 million gradient steps with a batch size of 32, which roughly amounts to 6-7 hours~(this could be further sped up by using large-batch sizes). We list the number of configurations we evaluated for each method below.
\begin{itemize}[topsep=0pt, partopsep=0pt, parsep=0pt, itemsep=3pt, leftmargin=20pt]
\item Rehearsal: We tried 5 values of teacher data ratio $\rho$ $\times$ 4 $n$-step values, amounting to a total of 20 configurations.
\item JSRL: We tried 4 values of teacher roll-in steps $\alpha$ $\times$ 2 values of decay parameter $\beta$ $\times$ 2 values of $n$-step, amounting to 16 configurations.
\item RL Pretraining: We tried 2 values of $\lambda$ $\times$ 4 values of $n$-step, amounting to 8 configurations.
\item Kickstarting: We report results for 4 values of $n$-step for a specific temperature and distillation loss coefficient. For hyperparameter tuning, we evaluated 2 temperature values and 2 loss coefficients with a specific $n$-step. Overall, this corresponds to a total of 8 configurations.
\item DQfD: We report results for 4 values of $n$-step $\times$ 2 values of margin loss coefficients $\times$ 2 values of margin parameters, amounting to 16 configurations.
\item QDagger: We report results for 4 $n$-step values for a specific temperature and distillation loss coefficient. For hyperparameter tuning, we evaluated 2 different temperature and loss coefficients with a specific $n$-step, akin to kickstarting. Overall, this amounts to 8 configurations.
\end{itemize}
Based on the above, we evaluated a total of 60 (=$20+16+16+8$) configurations without pretraining while 32 configurations with pretraining. Each of these configurations was evaluated for 30 seeds. This amounts to a total compute time of 300-375 days for runs without pretraining on offline data while 400-480 days of GPU compute for runs involving pretraining, resulting in a total compute time of around 700 - 855 days on a P100 GPU.
\subsection{PVRL: Experimental details}
\label{app:more_details}
\begin{figure}[t]
\centering
\includegraphics[width=0.65\linewidth]{figures/teacher_data_ratio_iqm.pdf}
\vspace{-0.1cm}
\caption{\textbf{Rehearsal} for PVRL. The plots show IQM teacher normalized scores after training for 10M frames, aggregated across 10 Atari games with 3 seeds each. Each point in the above plots correspond to a distinct experiment setting evaluated using 30 seeds. Shaded regions show 95\% CIs~\citep{agarwal2021deep}.}
\label{fig:rehearsal_pretrain}
\vspace{-0.15cm}
\end{figure}
\begin{figure}[t]
\centering
\includegraphics[width=0.5\linewidth]{figures/n_step_legend.pdf}
\includegraphics[width=0.495\linewidth]{figures/offline_pretrain_c0.3_without_leg.pdf}
\includegraphics[width=0.495\linewidth]{figures/offline_pretrain_c1.0_without_leg.pdf}
\caption{\textbf{RL pretraining} using CQL~\citep{kumar2020conservative}, followed by fine-tuning with \textbf{Left}. CQL coefficient $0.3$, and \textbf{Right}. CQL coefficient 1.0. The plots shows IQM teacher normalized scores over the course of training, computed across 30 seeds, aggregated across 10 Atari games. Online fine-tuning degrades performance with $1$-step returns, which is more pronounced with higher CQL loss coefficient.}
\label{fig:app_pretrain}
\vspace{-0.35cm}
\end{figure}
\textbf{Atari 2600 Games}: The subset of games in the paper includes games from the original Atari training set used by \citet{bellemare2013arcade}~(Asterix, Beam Rider, Seaquest and Space Invaders) as well as validation games used by \citet{mnih2015human}~(Breakout, Enduro, River Raid), except the games which are nearly solved by DQN, such as Freeway and Pong. We do not use any hard exploration games as a DQN teacher does not provide a meaningful teacher policy for such games. The remaining three games were chosen to test the student agent in environments with challenging characteristics such as requiring planning as opposed to being reactive~({\em e.g.,}\xspace Ms Pacman, Q$^*$Bert), and sparse-reward games that require long-term predictions~(Bowling). Furthermore, most of these games can be significantly improved over the teacher DQN performance, which is sub-human on half of the games~(Ms Pacman, Q$^*$Bert, Bowling, Seaquest and Beam Rider). Refer to Table~\ref{tab:scores} for per-game teacher scores.
\begin{table*}[t]
\small
\caption{\textbf{Common hyperparameters} used by PVRL experiments using a DQN student agent on ALE in \Secref{sec:value_policy}. These hyperparameters are based on the ones used by the Jax implementation of DQN in Dopamine~\citep{castro2018dopamine}.}
\centering
\begin{tabular}{lrr}
\toprule
Hyperparameter & \multicolumn{2}{r}{Setting} \\
\midrule
Sticky actions && Yes \\
Sticky action probability && 0.25\\
Grey-scaling && True \\
Observation down-sampling && (84, 84) \\
Frames stacked && 4 \\
Frame skip~(Action repetitions) && 4 \\
Reward clipping && [-1, 1] \\
Terminal condition && Game Over \\
Max frames per episode && 108K \\
Discount factor && 0.99 \\
Mini-batch size && 32 \\
Target network update period & \multicolumn{2}{r}{every 2000 updates} \\
Min replay history && 20000 steps \\
Environment steps per training iteration && 250K \\
Update period every && 4 environment steps \\
Training $\epsilon$ && 0.01 \\
Training $\epsilon$-decay steps && 50K \\
Evaluation $\epsilon$ && 0.001 \\
Evaluation steps per iteration && 125K \\
$Q$-network: channels && 32, 64, 64 \\
$Q$-network: filter size && $8\times8$, $4\times4$, $3\times3$\\
$Q$-network: stride && 4, 2, 1\\
$Q$-network: hidden units && 512 \\
Hardware && P100 GPU \\
Offline gradient steps per iteration && 100K \\
Offline training iterations && 10 \\
Offline learning rate && $0.0001$ \\
\bottomrule
\end{tabular}
\vspace{-0.25cm}
\label{table:hyperparams_atari}
\end{table*}
\begin{table}
\centering
\caption{Average scores for the random agent, human agent and the DQN (Adam) trained for 400 million frames (based on 5 runs). For teacher normalized scores reported in the paper, the random agent is assigned a score of 0 while the DQN (Adam) agent is assigned a score of 1. Normalization using teacher allow us to compare the performance of student agents relative to the teacher and avoid high performing outliers~(such as Breakout and Space Invaders) in terms of human normalized scores.}
\vspace{0.2cm}
\begin{tabular}{cccc}
\toprule
Game & Human & DQN @400M & Random \\
\midrule
Asterix & 8503.3 & 13682.6 & 210.0 \\
Beam Rider & 16926.5 & 6608.4 & 363.9 \\
Bowling & 160.7 & 33.9 & 23.1 \\
Breakout & 30.5 & 234.2 & 1.7 \\
Enduro & 860.5 & 1142.0 & 0.0 \\
Ms Pacman & 6951.6 & 4366.2 & 307.3 \\
Q$*$bert & 13455.0 & 11437.3 & 163.9 \\
River Raid & 17118.0 & 17061.9 & 1338.5 \\
Seaquest & 42054.7 & 14228.2 & 68.4 \\
Space Invaders & 1668.7 & 7613.6 & 148.0 \\
\bottomrule
\end{tabular}\label{tab:scores}
\vspace{-0.25cm}
\end{table}
\textbf{Common hyperparameters}. We list the hyperparameters shared by all PVRL methods in \autoref{table:hyperparams_atari}. For all methods, we swept over $n$-step returns in $\{1, 3, 5, 10\}$ except for DQfD~\citep{hester2018deep}, which originally used $10$-step returns, where we only tried $3$-step and $10$-step returns and JSRL for which we tried only $1$-step and $3$-step returns. For PVRL methods without any pretraining phase, we use a learning rate of $6.25e^{-5}$ ~(JSRL, Rehearsal), following the hyperparameter configuration for Dopamine~\citep{castro2018dopamine}. For methods that pretrain on offline data, we sweep over \{$6.25e^{-5}$, $1e^{-5}$\} and found the learning rate of $1e-5$ to perform better in our early experimentation and use it for our main results. We discuss the method specific hyperparameters below. For obtaining the teacher policy using value-based agent, we use the $\mathrm{softmax}(Q_T(s, \cdot)/\tau)$ over the teacher's Q-function $Q_T$ and use the same temperature coefficient $\tau$ for both the student and teacher policy.
\begin{itemize}
\item \textbf{Rehearsal}: We tried 5 different values of the teacher data ratio~($\rho$) in $\{0, 1/256, 1/64, 1/16, 1/4\}$. The loss, ${\mathcal{L}}_{Rehearsal}$, can be written as: ${\mathcal{L}}_{Rehearsal} = \rho {\mathcal{L}}_{TD}({\mathcal{D}}_T) + (1-\rho) {\mathcal{L}}_{TD}({\mathcal{D}}_S)$.
As can be seen from the results in \autoref{fig:rehearsal_pretrain}, we find a small value of teacher data ratio~($\rho=1/16$) with $3$-step returns to be the best performing configuration.
\item \textbf{JSRL}. As shown in \autoref{fig:dqfd_qdagger}~(left), we swept over the maximum number of teacher roll in steps of $\alpha$ in $\{0, 100, 1000, 5000\}$, and the decay parameter $\beta$, which governs how fast we decay the roll-in steps, in $\{0.8, 1.0\}$. Note that $\beta=1.0$ corresponds to JSRL-Random, which was found to be competitive in performance to JSRL~\citep{uchendu2022jump}.
\item \textbf{RL Pretraining}: We use CQL, which optimizes the following loss:
\begin{equation}
{\mathcal{L}}_{Pretrain} = {\mathcal{L}}_{TD}({\mathcal{D}}_T) + \lambda \mathbb{E}_{s,a\sim {\mathcal{D}}_T} \left[\log\big(\sum_{a'} Q(s, a')\big) - Q(s,a) \right] \label{eq:cql_loss}
\end{equation}
The choice of CQL is motivated by its simplicity as well as recent findings that offline RL methods that do not estimate the behavior policy are more suited for online fine-tuning~\citep{nair2020awac}. We tried two different values of CQL coefficient $\lambda$~($0.3$ and $1.0$), as shown in \autoref{fig:app_pretrain}, and report the results for the better performing coefficient~($\lambda = 0.3$) in the main paper.
\item \textbf{Kickstarting}. Kickstarting~\citep{schmitt2018kickstarting} uses the same loss as QDagger~(\autoref{eq:qdagger}), but as discussed in the main paper, kickstarting does not have any pretraining phase on offline data. For the temperature hyperparameter $\tau$
for obtaining the policy $\pi(\cdot | s) = \mathrm{softmax}(Q(s, \cdot)/\tau)$, we tried $0.1$ and $1.0$. Similarly, we swept over two initial values for distillation loss coefficient~($\lambda_0$), namely $1.0$ and $3.0$. For experiments with the DQN student, we found the coefficient $3.0$ and temperature $0.1$ to perform the best.
\item \textbf{DQfD}. Following \citet{hester2018deep}, DQfD uses the following loss for training:
\begin{equation}
{\mathcal{L}}_{DQfD}({\mathcal{D}}) ={\mathcal{L}}_{TD}({\mathcal{D}}) + \eta_t \mathbb{E}_{s \sim {\mathcal{D}}}\left[\max_{a} \left( Q(s, a) + f(a_T(s), a)\right) - Q(s, a_T(s))\right]\label{eq:margin_loss}
\end{equation}
where $\eta_t$ corresponds to the margin loss coefficient, $a_T(s)= \mathrm{argmax}_{a} \pi_T(a|s)$ and $f(a_T, a)$ is a margin function that is 0 when $a = a_T$ and a positive margin $m$ otherwise. We swept over the values $\{1.0, 3.0\}$ for both the margin parameter $m$ and initial values $\eta_0$ of the margin loss coefficient $\eta_t$. For the DQN student, we report the results for the better performing margin coefficients in the main paper.
\item \textbf{QDagger}. Akin to kickstarting, we swept over the values of temperature $\tau$ in $\{0.1, 1.0\}$ and distillation coefficient $\lambda_0$ in $\{1.0, 3.0\}$. For ALE experiments, we decay the distillation loss coefficient every training iteration~(1M environment frames) using the fraction of expected returns obtained by the student policy $\pi$ compared to the teacher policy $\pi_T$, that is, $\lambda_t = \mathbf{1}_{t<t_0} \max(1 - G^\pi/G^\pi_T, 0)$. For fair comparisons with other methods, we use the same strategy for decaying the distillation loss coefficient $\lambda_t$ for Kickstarting and the margin loss coefficient $\eta_t$ for DQfD.
\end{itemize}
\subsection{Reincarnating RL as a workflow: Additional details}
\label{app:wf_additional_results}
\begin{figure}[t]
\begin{minipage}{.49\textwidth}
\centering
\vspace*{-0.3cm}
\includegraphics[width=0.98\linewidth]{figures/appendix_figures/impala_tr.pdf}
\vspace*{-0.15cm}
\caption{\textbf{Tabula rasa Impala-CNN Rainbow}. Results for different learning rates for the tabula rasa Impala-CNN Rainbow agent. Learning rate of $3e-5$ performs the best. The plots show IQM normalized scores
aggregated scores 10 Atari games with 3 seeds, while the shaded regions show 95\% bootstrap CIs.
}\label{fig:impala_tr}
\end{minipage}~~
\begin{minipage}{.49\textwidth}
\centering
\includegraphics[width=\linewidth]{figures/appendix_figures/dqn_ft_20_tau.pdf}
\vspace*{-0.4cm}
\caption{\textbf{Effect of QDagger\ temperature} $\tau$ on the performance of reincarnated Impala CNN-Rainbow in \autoref{fig:reincarnation_wf}. A lower temperature coefficient~(0.1) results in better performance in the offline pretraining phase but converges to similar performance in the online phase. }\label{fig:tau_effect_ft_dqn}
\vspace{-0.5cm}
\end{minipage}
\end{figure}
\begin{figure}[t]
\centering
\includegraphics[width=0.49\linewidth]{figures/appendix_figures/dqn_20_tau.pdf}
\hfill
\includegraphics[width=0.49\linewidth]{figures/appendix_figures/dqn_400_tau.pdf}
\vspace*{-0.15cm}
\caption{\textbf{Effect of QDagger\ temperature} $\tau$ on the performance of reincarnating Impala CNN-Rainbow from \textbf{Left}. DQN (Adam) @ 20M, and \textbf{Right}. DQN (Adam) @ 400M. Notably, the better performing temperature $\tau$ is dependent on the teacher policy. Lower $\tau$ results in cloning a more ``spikier" teacher policy. With a reasonably good teacher policy~(DQN @ 400M), $\tau$ value of $0.1$ performs better than $1.0$ while with a more suboptimal teacher policy~(DQN @ 20M), the higher temperature coefficient of $1.0$ performs better than $0.1$. }\label{fig:tau_effect}
\vspace{-0.3cm}
\end{figure}
\textbf{Revisting ALE}. We used the final model checkpoints of Nature DQN~\citep{mnih2015human} from \citet{agarwal2020optimistic}, which was trained for 200M frames using the hyperparameters in Dopamine~\citep{castro2018dopamine}. The fine-tuned DQN~(Adam) in panel 2 in \autoref{fig:reincarnation_wf} uses $3$-step returns. For the tabula rasa Impala-CNN Rainbow, we use similar hyperparameters to Dopamine Rainbow except for learning rate~($lr$), for which we ran a sweep over $\{1e-4, 1e-5, 3e-5 \}$, shown in \figref{fig:impala_tr}, and use the best performing $lr$ of $3e-5$. For the reincarnated Impala-CNN Rainbow in Panel 3, we use a QDagger\ distillation coefficient of $1.0$ and sweep over temperature parameter $\tau$ in $\{0.1, 1.0\}$, as shown in \figref{fig:tau_effect_ft_dqn}. Consistent with our other fine-tuning results on ALE, in Panel 3, using a reduced $lr$ of $3e-6$ for fine-tuning the already fine-tuned DQN agent results in better performance, compared to using an $lr$ of $1e-5$, as used by fine-tuned DQN.
\begin{figure}[t]
\begin{minipage}{.49\textwidth}
\centering
\includegraphics[width=\linewidth]{figures/appendix_figures/td3_finetune.pdf}
\vspace*{-0.4cm}
\caption{\textbf{Fine-tuning TD3}. Results for fine-tuning a trained Acme TD3 agent with different learning rates. All the different learning rates exhibit similar performance trends including severe degradation after prolonged training.}\label{fig:td3_ft}
\end{minipage}~~
\begin{minipage}{.49\textwidth}
\centering
\includegraphics[width=\linewidth]{figures/appendix_figures/d4pg_distillation_coeff.pdf}
\vspace*{-0.4cm}
\caption{\textbf{Effect of varying initial QDagger\ distillation coefficient} $\lambda_0$ on the performance of reincarnated D4PG. Higher coefficient~(0.3) results in faster transfer but converges to similar performance to the runs with lower coefficient~(0.1).}\label{fig:lambda_effect}
\end{minipage}
\vspace{-0.7cm}
\end{figure}
\textbf{Humanoid:Run}. For tabula rasa TD3~\citep{fujimoto2018addressing}, we used a learning rate~($lr$) of $3e-4$ for both the policy and critic, which are represented using a MLP with 2 hidden layers of size (256, 256). For other hyperparameters, we used the default values in Acme's TD3 implementation. For fine-tuning TD3, we use the last 500K environment steps from the TD3's replay buffer and use the same hyperparameters as tabula rasa TD3 except for $lr$. Specifically, we swept over the $lr$ in $\{1e-4, 3e-4, 3e-05\}$, shown in \autoref{fig:td3_ft}, and find that all $lr$s exhibit performance degradation with prolonged training.
For the tabula rasa D4PG~\citep{barth2018distributed}, we use MLP networks with 3 hidden layers of size $(256, 256, 256)$ for the policy and $(512, 512, 256)$ for the critic. We used $3e-4$ as the learning rate and a sigma value of $0.2$ that sets the variance of the Gaussian noise to the behavior policy. Other hyperparameters use the default values for D4PG implementation in Acme. For reincarnating D4PG using QDagger, we minimize a distillation loss between the D4PG's actor policy and the teacher policy from TD3 jointly with the actor-critic losses. For QDagger\ specific hyperparameters, we pretrain using 200K gradient updates as well as decay $\lambda_t$ to 0 over a period of 200K gradient updates during the online training phase. Additionally, we sweep over distillation coefficient $\lambda_0$ in $\{0.1, 0.3\}$, as shown in \autoref{fig:lambda_effect}. Note that both TD3 and D4PG use $5$-step returns by default in Acme.
\textbf{BLE}. For BLE, we set most hyperparameters for our distributed RL agents based on configuration of the BLE Quantile agent, which can be found at \href{https://github.com/google/balloon-learning-environment/blob/master/balloon_learning_environment/agents/configs/quantile.gin}{agents/configs/quantile.gin}. The network architecture used by QR-DQN and Perciatelli is an MLP with 7 hidden layers of size 600 each with ReLU activations and approximate the distribution using 51 fixed quantiles. For the DenseNet architecture~\citep{huang2017densely} employed by IQN and R2D6, we use 7 hidden layers of size 512 each~(for TPU-efficiency), which contains significantly more parameters than the Perciatelli MLP. Additionally, R2D6 uses a LSTM layer of size 512 on top of the DenseNet encoder with QR-DQN loss, while IQN samples 128 quantiles for minimizing the implicit quantile regression loss.
For tabula rasa agents, we swept over the $lr$ in $\{2e-6, 6e-6, 1e-5\}$ and found $1e-5$ to be the best performing $lr$. However, for fine-tuning Perciatelli, we found that a lower $lr$ of $1e-6$ performs better. For reincarnated R2D6 and IQN, we use a $lr$ of $1e-5$ and $6e-6$ respectively during the online phase while $2 \times lr$ in the offline pretraining phase. We set distillation temperature $\tau$ to be equal to $1.0$ and linearly decay the QDagger\ distillation coefficient $\lambda_t$ over a fixed number of learner steps~(1M for R2D6 and 160000 for IQN). Furthermore, we swept over the initial value of $\lambda_t$~($\lambda_0$) in $\{0.3, 1.0\}$ and found 1.0 to be better for R2D6 while 0.3 for IQN.
\section*{Societal Impacts}
\vspace{-0.1cm}
This paper calls for statistical sophistication in deep RL research by accounting for statistical uncertainty in reported results. However, statistical sophistication can introduce new forms of statistical abuses and monitoring the literature for such abuses should be an ongoing priority for the research community.
Moving towards reliable evaluation and reproducible research is an ongoing process and this paper only partly addresses it by providing tools for more reliable evaluation. That said, while accounting for uncertainty in results is not a panacea, it provides a strong foundation for trustworthy results on which the community can build upon, with increased confidence. In terms of broader societal impact of this work, we do not see any foreseeable strongly negative impacts. However, this paper could positively impact society by constituting a step forwards in rigorous few-run evaluation regime, which reduces computational burden on researchers and is ``greener'' than evaluating a large number of runs.
\vspace{-0.1cm}
\section*{Acknowledgments}
\vspace{-0.1cm}
We thank Xavier Bouthillier, Dumitru Erhan, Marlos C. Machado, David Ha, Fabio Viola, Fernando Diaz, Stephanie Chan, Jacob Buckman, Danijar Hafner and anonymous NeurIPS' reviewers for providing valuable feedback for an earlier draft of this work. We also acknowledge Matteo Hessel, David Silver, Tom Schaul, Csaba Szepesvári, Hado van Hasselt, Rosanne Liu, Simon Kornblith, Aviral Kumar, George Tucker, Kevin Murphy, Ankit Anand, Aravind Srinivas, Matthew Botvinick, Clare Lyle, Kimin Lee, Misha Laskin, Ankesh Anand, Joelle Pineau and Braham Synder for helpful discussions. We also thank all the authors who provided individual runs for their corresponding publications. We are also grateful for general support from Google Research teams in Montréal and elsewhere.
\section{Introduction}
\vspace{-0.1cm}
\input{intro}
\vspace{-0.25cm}
\section{Preliminaries}\label{sec:back}
\vspace{-0.25cm}
\input{background}
\vspace{-0.3cm}
\section{Related work}\label{sec:related}
\vspace{-0.25cm}
\input{related_work}
\vspace{-0.38cm}
\section{Case Study: Policy to Value Reincarnating RL}
\label{sec:value_policy}
\vspace{-0.3cm}
\input{persistent_rl}
\vspace{-0.4cm}
\section{Reincarnating RL as a research workflow}
\label{sec:workflow_experiments}
\vspace{-0.3cm}
\input{main_experiments}
\vspace{-0.38cm}
\section{Considerations in Reincarnating RL}
\label{sec:considerations}
\vspace{-0.28cm}
\input{ablation_experiments}
\vspace*{-0.3cm}
\section{Conclusion}
\vspace*{-0.3cm}
\label{sec:conc}
\input{discussion}
\vspace{-0.15cm}
\section*{Societal Impacts}
\vspace{-0.15cm}
\input{broader_impact}
\vspace{-0.15cm}
\section*{Acknowledgments}
\vspace{-0.15cm}
We would like to thank David Ha, Evgenii Nikishin, Karol Hausman, Bobak Shahriari, Richard Song, and Alex Irpan for their valuable feedback on this work.
We also acknowledge Dale Schuurmans, Aleksandra Faust, George Tucker, Rebecca Roelofs, Eugene Brevdo, Pierluca D'Oro, Nathan Rahn, Adrien Ali Taiga, Bogdan Mazoure, Jacob Buckman and Aviral Kumar for useful discussions.
\vspace{-0.1cm}
\section*{Author Contributions}
\vspace{-0.1cm}
\textbf{Rishabh Agarwal} led the project, defined the scope of the work to focus on policy to value reincarnation, came up with a successful algorithm for PVRL, and performed the literature survey. He designed, implemented and ran most of the experiments on ALE, Humanoid-run and BLE, and wrote the paper.
\textbf{Max Schwarzer} was the main collaborator and helped run DQfD experiments on ALE and as well as setting up some agents for the BLE codebase with Acme, was involved in project discussions and edited the paper. Work done while a student researcher at Google.
\textbf{Pablo Samuel Castro} advised the project and was involved in project discussions, helped in setting up the BLE environment and implemented the initial Acme agents, and helped with paper editing.
\textbf{Aaron Courville} advised the project, helped with project direction and provided feedback on writing.
\textbf{Marc Bellemare} advised the project and suggested the idea of reusing existing agent checkpoints into our workflow, and provided feedback on writing.
{\small
\subsection{PVRL }
\begin{figure}[t]
\centering
\includegraphics[width=0.8\textwidth]{figures/legend_all_reincarnation.pdf}
\includegraphics[width=0.5\textwidth]{figures/reincarnation_all_comparison.pdf}~~~
\includegraphics[width=0.49\textwidth]{figures/perf_profile_all.pdf}
\caption{\textbf{Comparing PVRL algorithms} for reincarnating a student DQN agent given a teacher policy (with normalized score of 1), obtained from a DQN agent trained for 400M frames~(Section~\ref{sec:value_policy}). Tabula rasa $3$-step DQN student~($-\cdot$ line) obtains an IQM teacher normalized score around 0.39.
Shaded regions show 95\% bootstrap CIs. \textbf{Left}. Sample efficiency curves based on IQM normalized scores, aggregated across 10 games and 3 runs, over the course of training. Among all algorithms, only QDagger~(\Secref{sec:qdagger}) surpasses teacher performance within 10 million frames. \textbf{Right}. Performance profiles~\citep{agarwal2021deep} showing the distribution of normalized scores across all 30 runs at the end of training (higher is better). The area under an algorithm's profile corresponds to its mean performance while $\tau$ value where the profile intersects $y=0.5$ shows its median performance. QDagger\ stochastically dominates other algorithms and outperforms the teacher in 75\% of runs.}
\label{fig:all_reincarnation_comparison}
\vspace*{-0.7cm}
\end{figure}
\begin{itemize}[topsep=0pt, partopsep=0pt, parsep=0pt, itemsep=3.1pt, leftmargin=20pt]
\item {\textbf{Rehearsal}}: Since the student, in principle, can learn using any off-policy data, we can replay teacher data ${\mathcal{D}}_T$ along with the student's own interactions during training. Following \citet{paine2019making}, the student minimizes the TD loss on mini-batches that contain $\rho$\% of the samples from ${\mathcal{D}}_T$ and the rest from the student's replay ${\mathcal{D}}_S$~(different $\rho$ and $n$-step values in \figref{fig:rehearsal_pretrain}).
\item {\textbf{JSRL}}~(\autoref{fig:jsrl_kickstarting}, left): JSRL~\citep{uchendu2022jump} uses an interactive teacher policy as a ``guide'' to improve exploration and rolls in with the guide for a random number of environment steps.
To evaluate JSRL, we vary the maximum number of roll-in steps, $\alpha$, that can be taken by the teacher and sample a random number of roll-in steps between $[0, \alpha]$ every episode. As the student improves, we decay the steps taken by the teacher every iteration~(1M frames) by a factor of $\beta$
\item {\textbf{RL Pretraining}}: Given access to teacher data ${\mathcal{D}}_T$, we can pre-train the student using offline RL. To do so, we use CQL~\citep{kumar2020conservative}, a widely used offline RL algorithm, which jointly minimizes the TD and behavior cloning on logged transitions in ${\mathcal{D}}_T$~(Equation~\ref{eq:cql_loss}). Following pretraining, we fine-tune the learned Q-network using TD loss on the student's replay ${\mathcal{D}}_S$.
\item {\textbf{Kickstarting}}~(\autoref{fig:jsrl_kickstarting}, right): Akin to kickstarting~\citep{schmitt2018kickstarting}, we jointly optimize the TD loss with an on-policy distillation loss on the student's self-collected data in ${\mathcal{D}}_S$. The distillation loss uses the cross-entropy between teacher's policy $\pi_T$ and the student policy $\pi(\cdot | s) = \mathrm{softmax}(Q(s, \cdot)/\tau)$, where $\tau$ corresponds to temperature. To wean off the teacher, we decay the distillation coefficient as training progresses. Note that kickstarting does not pretrain on teacher data.
\item {\textbf{DQfD}}~(\autoref{fig:dqfd_qdagger}, left): Following DQfD~\citep{hessel2018rainbow}, we initially pretrain the student on teacher data $D_T$ using a combination of TD loss with a large margin classification loss to imitate the teacher actions~(Equation~\ref{eq:margin_loss}). After pretraining, we train the student on its replay data ${\mathcal{D}}_S$, again using a combination of TD and margin loss. While DQfD minimizes the margin loss throughout training, we decay the margin loss coefficient during the online phase, akin to kickstarting.
\end{itemize}
\textbf{Results}. Rehearsal, with best-performing teacher data ratio~($\rho=1/16$), is marginally better than tabula rasa DQN but significantly underperforms the teacher~(\autoref{fig:all_reincarnation_comparison}, {\color{teal} teal}), which seems related to the difficulty of standard value-based methods to learn from off-policy teacher data~\citep{ostrovski2021difficulty}. JSRL does not improve performance compared to tabula rasa DQN and even hurts performance with a large number of teacher roll-in steps~(\autoref{fig:jsrl_kickstarting}, right). The ineffectiveness of JSRL on ALE is likely due to the state-distribution mismatch between the student and the teacher, as the student may never visit the states visited by the teacher and as a result, doesn't learn to correct for its previous mistakes~\citep{chang2015learning}.
Pretraining with offline RL on logged teacher data recovers around 50\% of the teacher's performance and fine-tuning this pretrained Q-function online marginally improves performance~(\autoref{fig:all_reincarnation_comparison}, {\color{pinksherbet} pink}). However, fine-tuning degrades performance with $1$-step returns, which is more pronounced with higher values of CQL loss coefficient~(\figref{fig:app_pretrain}). We also find that kickstarting exhibits performance degradation~(\autoref{fig:jsrl_kickstarting}, right), which is severe with $1$-step returns, once we wean off the teacher policy. Akin to kickstarting, we again observe a severe performance collapse when weaning off the the teacher dependence in DQfD~(\autoref{fig:dqfd_qdagger}, left), even when using $n$-step returns. We hypothesize that this performance degradation is caused by the inconsistency between Q-values trained using a combination of imitation learning and TD losses, as opposed to only minimizing the TD loss. Further investigation of this phenomenon is left for future work. We also find that using intermediate values of $n$-step returns, such as $n=3$ (also used by Rainbow~\citep{hessel2018rainbow}), quickly recovers after the performance drop from weaning while larger $n$-step values impede learning, possibly due to stale target Q-values. See \citet{fedus2020revisiting} for a discussion about benefits of $n$-step returns.
\begin{figure}[t!]
\centering
\includegraphics[width=0.46\linewidth]{figures/jsrl_atari.pdf}
\includegraphics[width=0.46\linewidth]{figures/kickstarting_loss_iqm.pdf}
\vspace{-0.1cm}
\caption{\textbf{Left}. \textbf{JSRL}. The plot shows teacher normalized scores with 95\% CIs, after training for 10M frames, aggregated using IQM across 10 Atari games with 3 seeds each. Each point corresponds to a different experiment, evaluated using 30 seeds, with specific values of JSRL parameters~($\alpha$, $\beta$) and $n$-step returns.
\textbf{Right}. \textbf{Kickstarting}, with different $n$-step returns. The plots show IQM scores over the coures of training. Kickstarting exhibits performance degradation, which is severe with $1$-step, and is unable to surpass teacher's performance.}
\label{fig:jsrl_kickstarting}
\vspace{-0.3cm}
\end{figure}
\begin{figure}[t!]
\centering
\includegraphics[width=0.46\linewidth]{figures/dqfd_online_result.pdf}
\includegraphics[width=0.46\linewidth]{figures/q_dagger.pdf}
\vspace{-0.1cm}
\caption{\textbf{Left}. \textbf{DQfD}. Here, $m$ is the margin loss parameter, which is the loss penalty when the student's action is different from the teacher. \textbf{Right}. \textbf{QDagger}, with different $n$-step returns. In both, the $1^{st}$ vertical line separates pretraining phase from online phase while the $2^{nd}$ one indicates completely weaning off the teacher.}
\label{fig:dqfd_qdagger}
\vspace{-0.35cm}
\end{figure}
\vspace{-0.25cm}
\subsection{QDagger: A simple PVRL baseline}
\label{sec:qdagger}
\vspace{-0.1cm}
To address the limitations of prior approaches, we propose QDagger, a simple method for PVRL that combines Dagger~\citep{ross2011reduction}, an interactive imitation learning algorithm, with $n$-step Q-learning~(\autoref{fig:dqfd_qdagger}, right). Specifically, we first pre-train the student on teacher data ${\mathcal{D}}_T$ by minimizing ${\mathcal{L}}_{QDagger}({\mathcal{D}}_T)$, which combines distillation loss with the TD loss, weighted by a constant $\lambda$. This pretraining phase helps the student to mimic the teacher's state distribution, akin to the behavior cloning phase in Dagger. After pretraining, we minimize ${\mathcal{L}}_{QDagger}({\mathcal{D}}_S)$ on the student's replay ${\mathcal{D}}_S$, akin to kickstarting, where the teacher ``corrects'' the mistakes on the states visited by the student. As opposed to minimizing the Dagger loss indefinitely, QDagger\ decays the distillation loss coefficient $\lambda_t$~($\lambda_0=\lambda$) as training progresses, to satisfy the weaning desiderata for PVRL. Weaning allows QDagger\ to deviate from the suboptimal teacher policy $\pi_T$, as opposed to being perpetually constrained to stay close to $\pi_T$~(\autoref{fig:reincarnate_vs_distill}). We find that both decaying $\lambda_t$ linearly over training steps or using an affine function of the ratio of student and teacher performance worked well~(Appendix~\ref{app:more_details}).
Assuming the student policy $\pi(\cdot | s) = \mathrm{softmax}(Q(s, \cdot)/\tau)$, the QDagger\ loss is given by:
\begin{equation}
{\mathcal{L}}_{QDagger}({\mathcal{D}}) ={\mathcal{L}}_{TD}({\mathcal{D}}) + \lambda_{t} \mathbb{E}_{s\sim {\mathcal{D}}} \Big[\sum\limits_a \pi_T(a | s) \log \pi(a|s) \Big]
\label{eq:qdagger}
\end{equation}
\autoref{fig:all_reincarnation_comparison} shows that QDagger\ outperforms prior methods and surpasses the teacher. We remark that DQfD can be viewed as a QDagger\ ablation that uses a margin loss instead of a distillation loss, while kickstarting as another ablation that does not pretrain on teacher data. Equipped with QDagger, we show how to incorporate PVRL into our workflow and demonstrate its benefits over tabula rasa RL.
\subsection{Related work}
\vspace{-0.2cm}
\label{sec:related_reoriented}
\input{related_work_reoriented}
\vspace{-0.3cm}
\subsection{Case Study: Policy to Value Reincarnating RL}
\vspace{-0.2cm}
\label{sec:value_policy_reoriented}
\input{persistent_rl_reoriented}
\vspace{-0.2cm}
\subsection{QDagger: A simple PVRL baseline}
\label{sec:qdagger_reoriented}
\input{qdagger_reoriented} | {'timestamp': '2022-06-06T02:16:13', 'yymm': '2206', 'arxiv_id': '2206.01626', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01626'} | arxiv |
\section{Introduction}
\label{sec:introduction}
\input{subfiles/01_introduction}
\section{Related Work}
\label{sec:related_work}
\input{subfiles/02_related_work}
\section{Methodology}
\label{sec:methodology}
\input{subfiles/03_methodology}
\section{Model and Implementation}
\label{sec:model_and_implementation}
\input{subfiles/04_model_and_implementation}
\section{Experiments}
\label{sec:experiments}
\input{subfiles/05_experiments}
\section{Conclusion}
\label{sec:conclusion}
\input{subfiles/06_conclusion}
\subsection{Modeling Compressible Fluids}
\label{sec:PINN}
We consider the problem of modeling non-steady compressible fluids, i.e. fluids with a spatially and temporally evolving density $\rho(t, \bs x)$ and velocity $\bs v(t, \bs x)$.
For the sake of notational brevity, we will denote these by $\rho$ and $\bs v$ in the following.
Our particular interest lies in the prediction of particle movement and thus density $\rho$.
Given noisy observations of the density $\rho^{(i)}$, and potentially other quantities such as the velocity or pressure, we want to predict the density $\rho$.
Commonly, the PDE serves as a physics-based regularizer of the network by enforcing PDE loss $L_f$ in Eq.~(\ref{eq:PINN_pde_loss}) during standard PINN training.
For this, $L_f$ is evaluated on a set of collocation points that are, for example, uniformly distributed on a bounded region.
However, the limitations of this approach become apparent when considering an advection problem defined by the following PDE:
\begin{equation}
\label{eq:advection}
\partial_t \rho + \bs v\cdot (\nabla\rho)= 0.
\end{equation}
Figure \ref{fig:advection} illustrates a one-dimensional case on the domain $[0,T]\times \Omega$, with $\Omega = \mathbb{R}$, and a known constant velocity $v\propto1$.
We measure the density $\rho^{(i)}$ at different (spatially fixed) points in time and space $\{(t^{(i)}, \bs x^{(i)})\}$, on which a neural network $\rho_{\Theta}(t, \bs x)$ is trained.
For optimizing the standard PDE loss $L_f$ as given in Eq.~\eqref{eq:PINN_pde_loss}, we would require a bounded region $\Omega_{\mathcal{B}}:=[a,b] \subset \Omega$ with $a<b$ and $a,b \in \mathbb{R}$.
This, in turn, leads to two issues:
\begin{enumerate}
\item Our region of interest, the moving density, is concentrated on a small subset of $\Omega$.
Enforcing Eq.~\eqref{eq:advection} in areas with low-density has little regularizing effect on $\rho_\Theta$.
\item
In order to define appropriate boundaries of $\Omega_{\mathcal{B}}$, we require prior knowledge about the solution which depends on the time frame, velocity, and the underlying PDE.
Otherwise, the main bulk of density might move out of the considered area $\Omega_{\mathcal{B}}$.
\end{enumerate}
We note that for issue (1.), the dynamics of fluids are assumed to be mainly caused by local interactions of particles, which is the case for commonly considered dynamics of gases, liquids or active particles \citep{hoover2003links, toner1995long}.
Furthermore, the naive solution of selecting an arbitrary large area with $a\ll b$ for resolving (2.) would amplify the sparsity in (1.).
\begin{figure}
\centering
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=0.9\linewidth]{images/sketches/advection_initial_time_V2.png}
\caption{}
\label{fig:advection_gt_t0}
\end{subfigure}%
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=0.9\linewidth]{images/sketches/advection_uniform_V2.png}
\caption{}
\label{fig:advection_unif}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=0.9\linewidth]{images/sketches/advection_final_time_V2.png}
\caption{}
\label{fig:advection_gt_T}
\end{subfigure}%
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=0.9\linewidth]{images/sketches/advection_mcmc.png}
\caption{}
\label{fig:advection_mcmc}
\end{subfigure}
\caption{Linear advection experiment in one dimension: (a) ground truth at time $t_1$ and (c) time $t_2$, (b) density prediction with uniform collocation points and (d) Particle density based collocation points for $t\in\{t_1, t_2\}$. Cross points represent sampled collocation points at $t_1$ and $t_2$ with two different red shades.}
\label{fig:advection}
\end{figure}
Therefore, a proper resolution to these issues should be able to (i) focus on areas that have a relevant regularizing effect on the prediction of $\rho_\Theta$ and (ii) adapt to the fluid movements without being restricted to a predefined mesh.
Let us assume that we had access to the positions of each of the $N$ total particles via the function $\bs x_j(t)$, with $j\in \{0,1,\dots,N\}$.
We would then propose to use the following loss over these positions within the considered time frame $[0, T]$:
\begin{equation}
\label{eq:L_PD_sum}
{L}_{\text{pd}}(\Theta)=\frac{1}{T} \int_{t=0}^{T} \frac{1}{N}\sum_{j=0}^{N} \Big|\Big|f_\Theta\Big(t, \bs x_{j}(t)\Big)\Big|\Big|_2^2 \ \ dt.
\end{equation}
It can be seen that the average in Eq.~\eqref{eq:L_PD_sum} is a sample-based estimator of an expected PDE loss.
Namely, the expectation over the occupation probability of particles in the whole time frame, denoted by the molecular distribution $\Psi(t, \bs x) = \Psi(t) \Psi(\bs x| t)$ introduced in section \ref{sec:related_work}:
\begin{equation}
L_{\text{pd}}(\Theta) \approx \int_{t=0}^T \Psi(t) \int_{\Omega} \Psi(\bs x | t)\Big[||f_\Theta(t, \bs x_{j}(t))||_2^2 \Big] \ \ dt,
\end{equation}
where $\Psi(t) \propto 1$ due to the conservation of mass.
As the particle density corresponds directly to the occupation probability of a molecule $\Psi(t, \bs x)$ with a changed normalization constant,
we can estimate $L_{pd}$ via samples drawn from the normalized particle density or, similarly, from the normalized mass density when assuming a homogeneous fluid.
\subsection{Particle-Density PINNs}
\label{subsec:pdPINNs}
In summary, we propose to draw collocation points from the normalized density:
\begin{equation}
(t_i, \bs{x}_i) \sim \rho_N(t, \bs{x}) =
\tfrac{1}{Z}
\rho(t, \bs x).
\end{equation}
However, as the true density is unknow
, we instead rely on the learned density ${\rho}_{\Theta}(t, {\bs x})$ as a proxy provided by the neural network.
We denote the associated normalized PDF by $q_{\Theta}(t, {\bs x}) = \frac{1}{Z'} {\rho}_{\Theta}(t, {\bs x})$ with support on $[0, T] \times \Omega$.
The PDE loss is then defined as the expectation w.r.t.~$q$:
\begin{equation}
\label{eq:PINN_pde_loss_density}
{L}_{pd}(\Theta) = \mathbb{E}_{q_{\Theta}(t, \bs x)}\Big[ ||{f}_\Theta(t, \bs x)||_2^2 \Big] = \int_{t=0}^T q_{\Theta}(t) \int_{\Omega}
q_{\Theta}({\bs x | t})||{f}_\Theta(\bs x,t)||_2^2 \ d\bs x \ dt.
\end{equation}
In order to approximate this integral, samples need to be drawn from $q_\Theta(t, \bs x)$.
This can be done in a principled way by using dynamic Monte Carlo methods, despite the fact that the normalization constant $Z$ is unknown.
Such a sampling procedure additionally eliminates the need for $\Omega$ to be a bounded domain in settings where such boundaries are not available.
In contrast, methods based on the mesh-based loss in Eq.~\eqref{eq:PINN_pde_loss} are not directly applicable to unbounded domains such as $\Omega = \mathbb{R}^d$,
and potentially arbitrary boundaries have to be introduced.
Although motivated in the context of an advection problem, the proposed approach is generally applicable to compressible fluid dynamics settings and more general settings as we elaborate on below.
\paragraph{Further particle-based PDEs.}
The advection equation (\ref{eq:advection})
can be seen as a special case of mass conservation (assuming $\nabla \cdot \bs v = 0 $) which is one of the fundamental physical principles expressed as a \textit{continuity equation}.
The continuity equation relates temporal changes of the fluid density $\rho$ to spatial changes of the flux density $\rho \bs v$ through
\begin{equation}
\label{eq:continuity_equation_masscons}
\partial_t \rho + \nabla \cdot (\rho \bs v)= 0.
\end{equation}
Most famously, it belongs to a broader set of problems considering viscous flows, which are described by the Navier-Stokes equations.
An even more general setting, for which conservation laws such as the conservation of momentum do not hold, considers the modeling of self-propelled, active particles,
for which Toner and Tu \citep{toner1995long,tu1998sound,toner1998flocks,toner2012reanalysis} introduced hydrodynamic equations.
Our method is generally applicable in settings where (i) a non-negative scalar field (with a finite integral) of interest can be interpreted as a particle density,
and (ii) the local interactions of these particles give rise to the considered PDEs.
In the \textit{heat equation}, for instance, it is well-established that the diffusion of the temperature coincides with the diffusion of particles according to Fick's second law.
The diffusion of the temperature $T$ within a homogeneous medium is described by a parabolic PDE defined as
\begin{equation}
\label{eq:heat_equation}
\partial_t T - \alpha \nabla^2 T = 0,
\end{equation}
where $\alpha$ is the thermal diffusivity and $\nabla^2$ is the Laplacian operator.
For $T \coloneqq \rho$, the diffusion equation of particles is obtained, substituting the thermal diffusivity with the mass diffusivity.
Other possible applications involve Maxwell's equations for conservation of charge in electrodynamics.
\subsection{Particle Simulation of a Compressible Fluid}
\label{subsec:exp_compressible_fluid}
As a challenging prediction task, a non-steady compressible fluid in three dimensions is simulated by propagating fluid parcels through a pre-defined velocity field. In other words, we simulate a fluid from the Lagrangian perspective with the conservation of mass as the underlying PDE (see Eq.~\eqref{eq:continuity_equation_masscons}).
The paths of the roughly 240'000 parcels are solved for with a basic backward Euler scheme.
The particle density and velocity are obtained by counting the number of parcels within a voxel, and by averaging the individual velocities.
For the training observations provided to the network, we introduce a set of spatially fixed sensors (or \textit{radars}) which count the number of fluid parcels that are present within a radius $r$ at a given time.
The birds-eye view of the setting is shown in Figure \ref{fig:exp3d_birdeye}, where circles indicate the area covered by the radars.
Along the $z$-axis, the simulated sensor distinguishes over 21 contiguous altitude layers.
Another disjoint set of sensors is provided for the validation set while the test performance is evaluated on a grid.
Figure \ref{fig:exp3d_zaxis} shows the 3D simulated data projected along the $z$-axis and over time, which gives a complementary illustration with respect to the birds-eye view.
For details regarding the data set and the velocity field we refer to the Appendix section \ref{appendix:particle_simulation}.
The full code for the data generation, as well as the data sets themselves, is provided in the supplementary material.
We consider two different types of (common) application settings with increasing difficulty and dimensionality: (i) the 2D setting obtained by projecting onto the $xy$-plane, and (ii) the full 3D setting.
In both settings we look at the dynamics over the time frame $t\in[0, 3]$
and learn both the density and the velocity using two SIREN \citep{sitzmann2020implicit} networks $\rho_{\Theta_1}(t, \bs x)$ and $\bs v_{\Theta_2}(t, \bs x)$.
Within the experiments, the compared settings always correspond to similar architectures, hyperparameters, and optimizers.
In all
settings, the PDE used for regularizing the networks is the continuity equation for the conservation of mass (see Eq.~\eqref{eq:continuity_equation_masscons}).
\begin{figure}[ht!]
\centering
\begin{subfigure}{.49\textwidth}
\centering
\includegraphics[width=.88\linewidth]{images/exp2d/exp2d_nsamples.png}
\caption{}
\label{fig:exp2d_r2_results}
\end{subfigure}%
\begin{subfigure}{.49\textwidth}
\centering
\includegraphics[width=.88\linewidth]{images/exp3d/exp3d_nsamples.png}
\caption{}
\label{fig:exp3d_r2_results}
\end{subfigure}%
\caption{Explained variance of $\sqrt{\rho}$ evaluated on the test set, for different number of collocation points in the (a) 2D and (b) 3D experiment.
}
\end{figure}
\subsubsection{Projection on $xy$-plane}
In the 2D setting, the density and velocity are measured by $15^2$ sensors on the $xy$-plane within the area $[-4, 4]^2$ at 21 equidistant timesteps.
For each method, we perform a hyper-parameter search over different PDE-weights $w_2$ (see Eq.~\eqref{eq:PINN_argmin}) and select the one with the highest average validation R$^2$. Figure \ref{fig:exp2d_r2_results} shows the test R$^2$ performance for different numbers of collocation points and 11 different seeds, the distribution of which are visualized with the box plots.
Results clearly show that the proposed pdPINN outperforms competing methods across all number of collocation points.
Furthermore, we observe that the performance gap shrinks as the collocation points increase, eventually converging to the same limiting value.
This is expected, since in the high-sample limit the sample strategy becomes irrelevant and all methods should provide equivalent results.
However, what is relevant is that the proposed pdPINN model achieves significantly better results with significantly fewer collocation points.
We further took into consideration how the PDE-weight $w_2$ affects the performance as a function of the number of collocation points and verified we still obtain results consistent with Figure \ref{fig:exp2d_r2_results}.
We point the reader to the Appendix section \ref{appendix:particle_simulation} for a more detailed view of these results.
\begin{figure}[ht!]
\centering
\includegraphics[width=.8\linewidth]{images/exp3d/exp3d_proj1d_ot_vs_pdpinn_landscape.png}
\caption{3D setting predictions (obtained with 2048 collocation points) are summed over $xy$ grid cells to obtain $z$-axis projection over time. The OT-RAR method shows disconnected density predictions that violate mass conservation.}
\label{fig:exp3d_proj1d}
\end{figure}
\subsubsection{Full Three-Dimensional Setting}
In the 3D setting, the density and velocity are again measured by $15^2$ sensors on the $xy$-plane, but within the smaller area $[-3, 3]^2$ at 11 equidistant timesteps and 21 equidistant altitude layers.
Compared to the 2D setting, we have a spatially denser set of sensors, but fewer time steps.
Qualitative results are reported in Figure \ref{fig:exp3d_proj1d}, displaying the density predictions over time and projected over the $z$-axis.
This is obtained by summing over the $xy$ grid cells and allows us to visualize that the OT-RAR predictions clearly violate mass conservation.
Conversely, the pdPINN model accurately predicts the density while also faithfully enforcing the continuity equation.
In Figure \ref{fig:exp3d_r2_results} we quantitatively evaluate the performance of the different methods for different numbers of collocation points, with the method-specific PDE-weight $w_2$ being selected as in the 2D setting.
Also in the 3D setting, quantitative results show that the proposed pdPINN approach outperforms baseline methods across all number of collocation points.
As expected, in this higher-dimensional (3D and time) setting the difference in performances is even more pronounced.
Already with very few collocation points (512) pdPINNs achieve results comparable with those obtained with orders of magnitude more points (32768).
We verified that, even when getting close to the memory limit of a NVIDIA Titan X GPU, other sampling strategies at best achieve comparable results with pdPINNs.
Lastly, results from the 2D and 3D experiments suggest that the strength of the proposed method would be even more considerable for higher-dimensional settings.
\subsection{Heat Equation}
We further consider a 2D diffusion problem, namely the heat equation introduced in section \ref{subsec:pdPINNs}, where randomly distributed sensors provide measurements of the temperature.
We focus on a general setting with the initial conditions being zero temperature everywhere except for a specified region, as shown in Figure \ref{fig:heateq_gt}, and we let the system evolve in the time range $t\in[0,0.2]$.
The networks are only provided sensor measurements of the temperature.
For details regarding the training and test data we refer to the Appendix section \ref{appendix:heat}.
During the warm-up phase of the pdPINN, collocation points are sampled uniformly, and afterwards $90\%$ of the samples are drawn from the particle density distribution, which is proportional to the modeled temperature.
Collocation points are re-sampled every 500 epochs.
Differently from previous experiments, the employed architecture is a fully-connected two-layer neural network with 32 hidden units and tanh activations.
Density predictions for PINNs with uniform sampling and pdPINNs are illustrated in Figure \ref{fig:heateq_uniform} and \ref{fig:heateq_mcmc}, respectively, and compared with the ground truth in Figure \ref{fig:heateq_gt}.
We can clearly observe that the uniform sampling strategy does not allow putting enough focus on the relevant parts of the domain, i.e. regions with high temperature, and that it visibly fails to reconstruct the temperature profile.
In contrast, the pdPINN approach allows sampling in the region of higher density and reliably predicts the true temperature at all times.
We also evaluate quantitatively the performance of the two approaches in terms of the R$^2$ test error over the predicted temperature.
Consistent with previous 2D and 3D compressible fluids experiments, we show that the proposed pdPINNs outperform PINNs with uniform sampling strategy.
As in previous settings, we show that with few samples the regularization enforced by the PDE loss is not strong enough, leading to comparable results in both approaches.
However, as the number of sample increases, the PDE loss enforced with MCMC samples quickly and steadily outperforms uniform sampling.
We also verified that in the limit of high samples the two sampling strategies converge, as expected.
Further details regarding the quantitative results are discussed in the Appendix section \ref{appendix:heat}.
\begin{figure}[ht!]
\centering
\begin{subfigure}{.31\textwidth}
\centering
\includegraphics[width=.85\linewidth]{images/exp_heatequation/true_temperature.png}
\caption{}
\label{fig:heateq_gt}
\end{subfigure}%
\begin{subfigure}{.31\textwidth}
\centering
\includegraphics[width=.85\linewidth]{images/exp_heatequation/predicted_temperature_unif.png}
\caption{}
\label{fig:heateq_uniform}
\end{subfigure}
\begin{subfigure}{.37\textwidth}
\centering
\includegraphics[width=.89\linewidth]{images/exp_heatequation/predicted_temperature_mcmc.png}
\caption{}
\label{fig:heateq_mcmc}
\end{subfigure}
\caption{Temperature predictions of the heat equation experiment (trained with 128 collocation points) at time $t\sim0.044$.
(a) ground truth (b) uniform sampling, and (c) pdPINN.}
\end{figure}
\subsection{Bounded convolution of the network}
\subsection{Background Sampling for pdPINNs}
\label{appendix:background}
At initialization, the network prediction $\rho_\Theta$ is random and thus does not carry any useful information, i.e. sampling from this density would be meaningless.
Therefore, we start training the pdPINNs with a warm-up phase in which samples are obtained from a pre-specified background distribution:
\begin{equation}
\bs x \sim p_{bg}(t, \bs x)=p(t)p_{bg}(\bs x | t)
\end{equation}
with $p(t) = \mathcal{U}(0, T)$.
To avoid introducing a mesh, we could rely on the previously estimated Gaussian distribution introduced in Section \ref{sec:model_and_implementation}, i.e. $p_{bg}(\bs x|t) = p_{\text{gauss}}(\bs x)$.
As a second alternative, approach we consider random linear combinations of the convex hull of $\{x^{(i)}\}_{i=1}^N$ spanned by $c$ data points summarized as rows of matrix $Z\in \mathbb{R}^{c\times d}$. This leads to $\bs x = {\bs m}Z$ with weight $\bs m\in \mathbb{R}^c$ which can be drawn from a Dirichlet distribution, i.e. $\bs m \sim Dir(\bs \alpha=1)$.
Of course, a uniform sampling mechanism on a defined region is also suitable
and the definitive choice strongly depends on the data and PDE at hand.
We initially draw all samples from the background distribution, and then slowly increase the proportion of samples obtained from the particle density, as we found that leaving some background samples slightly helps in the training.
\subsection{Implementation of RAR and OT-RAR}
\label{appendix:implementation}
For our comparison, we considered the adaptive refinement methods \textit{RAR} and \textit{OT-RAR}, proposed by \citet{lu2021deepxde} and \citet[preprint]{tadiparthi2021optimal}.
Both methods rely on consecutive refinements of a fixed grid in the initial proposal.
The number of collocation points is steadily increased and collocation points once added will not be removed.
To allow for a more fair comparison, we adapt both methods to use a limited budget of points, and in addition we regularly resample them.
This leads to a slightly modified version of the methods which is similar in spirit.
For learning the linear mapping proposed by \citet{tadiparthi2021optimal}, we rely on the PyOT \citep{flamary2021pot} implementation of \citet{knott1984optimal}.
The pseudo-code for sampling a set of collocation points is given in Algorithm \ref{alg:rar} and Algorithm \ref{alg:ot-rar}.
The required input $f_\Theta$ refers to the PDE approximated by the network, as discussed in Section \ref{sec:introduction}.
For more specific details on the methods we refer to the original papers.
\begin{algorithm}
\caption{Adapted RAR}\label{alg:rar}
\begin{algorithmic}
\Require $f_\Theta$, uniform distribution $\mathcal{U}_{\mathcal{B}}$,\\ \hspace{7mm} number of col. points $k$,\ previous col. points $X_{\text{prev}}$.
\\
\State $X_{\text{prop}} \hspace{1.2mm} \gets [\bs x_1,\bs x_2, \dots, \bs x_k]^T$ with $\bs x_i \sim \mathcal{U}_{\mathcal{B}}$ \Comment{Sample proposals}
\State $X_\text{comb} \hspace{0.3mm} \gets$ concat($X_{\text{prev}}$, $X_{\text{prop}}$) \Comment{Concatenate old and new points}
\State $X_{\text{new}} \hspace{1.7mm} \gets \text{topk}(X_\text{comb},\ ||f_\Theta(X_\text{comb})||_2^2,\ k)$ \Comment{Keep top $k$ proposed points based on $f_{\Theta}$}
\\
\Ensure $X_{\text{new}}$
\end{algorithmic}
\end{algorithm}
\begin{algorithm}
\caption{Adapted OT-RAR}
\label{alg:ot-rar}
\begin{algorithmic}
\Require $f_\Theta$, uniform distribution $\mathcal{U}_{\mathcal{B}}$, \\ \hspace{7mm} number of col. points $k$, \\ \hspace{8mm}number of points for empirical distribution $j<2k$, \\ \hspace{7mm} previous col. points $X_{\text{prev}}$.
\\
\State $X_{\text{prop}} \hspace{2mm} \gets [\bs x_1,\bs x_2, \dots, \bs x_k]^T$ with $\bs x_i \sim \mathcal{U}_{\mathcal{B}}$ \Comment{Sample proposals}
\State $X_\text{comb} \hspace{1.1mm} \gets$ concat($X_{\text{prev}}$, $X_{\text{prop}}$) \Comment{Concatenate old and new points}
\\
\State $X_{\text{target}} \hspace{1.1mm} \gets \text{topk}(X_\text{comb},\ ||f_\Theta(X_\text{comb})||_2^2,\ j)$ \Comment{$j$ samples for target empirical distribution}
\State $X_{\text{source}} \hspace{0.3mm} \gets [\bs x_1,\bs x_2, \dots, \bs x_{j}]^T$ with $\bs x_i \sim \mathcal{U}_{\mathcal{B}}$ \Comment{$j$ samples for source empirical distribution}
\\
\State $M_\text{OT} \hspace{2.9mm} \gets \text{LinOT}(X_{\text{source}}, X_{\text{target}})$ \Comment{Obtain linear operator that maps to target distribution}
\\
\State $X_{\text{new}} \hspace{2.5mm} \gets [\bs x_1,\bs x_2, \dots, \bs x_k]^T$ with $\bs x_i \sim \mathcal{U}_{\mathcal{B}}$ \Comment{Sample uniformly}
\State $X_{\text{map}} \hspace{2.3mm} \gets M_\text{OT}(X_{\text{new}}) $ \Comment{Map samples to target distribution}
\\
\Ensure $X_{\text{map}}$
\end{algorithmic}
\end{algorithm}
\subsection{Experiments: Compressible Fluid}
\label{appendix:particle_simulation}
In the supplement, we provide code in Python for the data generation and for the pdPINN model. Below we provide the details for all the experiments we conducted.
Furthermore, we provide short videos showing the predicted density movements for each different approach.
More details on this can be found in the \texttt{README.html}
provided in the supplementary files.
The model is implemented using PyTorch \citep{pytorch}, with a custom Python implementation of the Metropolis-Hastings MCMC sampler relying on NumPy, SciPy, and Numba \citep{numpy, scipy, numba}.
All experiments were run on \textit{Nvidia GeForce GTX Titan X GPUs} with 12 GB VRAM.
A total of 6 GPUs were available, which were used to parallelize multiple runs.
In most settings, training in each experiment took less than 10 minutes.
The only exceptions were settings with a large amount of collocation points, with the bottleneck being the non-optimized bare-bones implementation of the Metropolis-Hastings sampler.
\subsubsection{Data Generation}
The velocity field in the $xy$-plane was generated from a scalar potential field $\Phi: \mathbb{R}^2 \rightarrow \mathbb{R}$ and the z-component of a vector potential $a: \mathbb{R}^2 \rightarrow \mathbb{R}$.
Through the Helmholtz decomposition%
\footnote{This is the 2D formulation of the Helmholtz decomposition, where the vector potential has non-zero components only along the $z$-axis as in $\bs a_{\text{3d}} = [0,0,a]^T$. The full decomposition is commonly written as $\bs v_{\text{3d}} = -\nabla \Phi_{\text{3d}} + \nabla \times \bs a_{\text{3d}}$.}
we can construct the velocity field $\bs v_{\text{xy}}: \mathbb{R}^2 \rightarrow \mathbb{R}^2$:
\begin{equation}
\bs v_{\text{xy}}\Bigg(\begin{bmatrix}x \\ y\end{bmatrix}\Bigg) = - \nabla \Phi + \begin{bmatrix}{\delta a}/{\delta y} \\ -{\delta a}/{\delta x}\end{bmatrix}.
\end{equation}
For both experiments the following fields were used:
\begin{align}
\Phi\Bigg(\begin{bmatrix}x \\ y\end{bmatrix}\Bigg) &= - \frac{1}{2}(x-2) \cdot (y-2),
\\
a\Bigg(\begin{bmatrix}x \\ y\end{bmatrix}\Bigg) &= - \frac{1}{5} \exp\Bigg( - \Big( \frac{2}{3}x\Big)^2 - \Big(\frac{2}{3}y\Big)^2 \Bigg).
\end{align}
The derivatives were obtained using the symbolic differentiation library SymPy \citep{sympy}.
To add a nonsteady component, the resulting velocity field is modulated in amplitude as a function of time $t\in [0, 3]$:
\begin{equation}
\bs v_{\text{xyt}}\Bigg(t, \begin{bmatrix}x \\ y\end{bmatrix}\Bigg) = \bs v_{\text{xy}}\Bigg(\begin{bmatrix}x \\ y\end{bmatrix}\Bigg) \left( \frac{3}{2} \left|\sin\left( \frac{2}{3} \pi t \right)\right| + 0.05\right).
\end{equation}
The $z$ (altitude) component of the velocity only depends on time and is given by:
\begin{equation}
v_z(t) = 1.6\cdot\sin\left( \frac{4}{3} \pi t \right).
\end{equation}
For the initial distribution of the fluid, the parcel positions were drawn from Gaussian mixtures.
For $t\in[0,3]$, these parcels were simulated using the above constructed velocity field.
The \textit{measurements} at the sensors were obtained by counting the number of parcels within a given radius over multiple timesteps.
The density corresponds to the mass divided by the sensor area, and the velocity is an average over all the parcel velocities.
For the training data additional zero-mean isotropic Gaussian noise is added to all measurements.
\subsubsection{Architecture and Training}
In both experiments, the networks for density $\rho_{\Theta_1}$ and velocity $v_{\Theta_2}$ prediction (parameterized by ${\Theta_1}$ and ${\Theta_2}$, respectively) are fully-connected layers with sinusoidal activation functions, as proposed by \citet{sitzmann2020implicit}.
The number of layers and units for each setting is shown in Table \ref{table:architecture}.
The sine frequency hyperparameter required in the SIREN architecture was tuned by hand according to the validation loss of the baseline model (i.e. without a PDE loss), leading to a sine-frequency of $12$ for the 2D setting, and $5$ for the 3D setting.
We note that the proposed default value of $30$ in \citet{sitzmann2020implicit} heavily overfits our relatively low-frequency data and we thus recommend an adjustment of this hyperparameter for usage in PINNs.
For training the network, the ADAM optimizer ~\citep{kingma2016adam} with a learning rate of $8\times 10^{-4}$ (2D Setting) or $10^{-4}$ (3D Setting) was used.
The learning rate was multiplied by a factor of $0.99$ each epoch.
All models were trained for 300 (3D setting) or 500 (2D setting) epochs.
The 2D setting was trained using full-batch gradient descent, whereas for the 3D setting we used a mini-batch size of $6931$.
In all experiments we trained and evaluated on 10 different random seeds.
\begin{table}[h]
\caption{Architecture for Particle Simulation Experiments.}
\label{table:architecture}
\centering
\begin{tabular}{llllll}
\toprule
Experiment & Input & Output Variable & \# Hidden Layers & \# Hidden Units \\
\midrule
2D & $[0, T]\times \mathbb{R}^2$ & Density\ $\rho_{\Theta_1} \in \mathbb{R}_+$ & 2 & 256 \\
& & Velocity $\bs v_{\Theta_2} \in \mathbb{R}^2$ & 1& 64 \\
\midrule
3D & $[0, T]\times \mathbb{R}^3$ & Density\ $\rho_{\Theta_1}\in \mathbb{R}_+$ & 6 & 256 \\
& & Velocity $\bs v_{\Theta_2} \in \mathbb{R}^3$ & 3 & 256 \\
\bottomrule
\end{tabular}
\end{table}
\subsubsection{Results for varying PDE Weights}
As mentioned in Section \ref{subsec:exp_compressible_fluid}, the weight of the PDE loss term has to be adjusted depending on the number of collocation points and the chosen loss term.
For a low number of collocation points, a high weight for the PDE loss will disturb the training, resulting in worse performance than the baseline without additional regularization.
The more collocation points are used, the higher the weight can be without leading to negative effects.
Consequently, one would ideally have to optimize the weight depending on the number of collocation points.
Figures \ref{app:fig:exp2d_n_samples_all_weights_boxplot} and \ref{app:fig:exp3d_n_samples_all_weights_boxplot} show this behaviour for the 2D and 3D setting of the compressible fluid experiment.
The colors indicate different weights for the respective method, with the color gradient (blue $\rightarrow$ red) indicating the increase of the weight.
It is important to note, that the colors between different methods should not be interpreted as similar weights.
Each method relies on a different loss, making a comparison of the weights for this loss meaningless.
We can see in both settings, that \textit{pdPINN} performs favourably, especially when using only few collocation points.
To emphasize the advantage provided by pdPINNs, Figure \ref{app:fig:exp3d_8k_vs_65k} compares the proposed pdPINN with only $8192$ collocation points with the uniform sampler using $65536$ (i.e. a factor of $8$), which is for our implementation close to the hardware limit of the used GPU with 12GB VRAM (depending on the used network architecture and mini-batch size).
In both cases, we selected the PDE weight $w_2$ based on the maximum validation R$^2$.
As a sidenote, the deviation of pdPINN at 128 collocation points is caused by a single outlier out of the 10 different random seeds.
\begin{figure}[ht!]
\centering
\includegraphics[width=.99\linewidth]{images/exp2d/exp2d_n_samples_all_weights.png}
\caption{2D compressible fluid experiment: Average test R$^2$ of predicted $\sqrt{\rho}$.
The colors indicate different PDE weights $w_2$ within each method.
The bars correspond to $95\%$ confidence intervals for the mean estimation based on $1000$ bootstrap samples.
}
\label{app:fig:exp2d_n_samples_all_weights_boxplot}
\end{figure}
\begin{figure}[ht!]
\centering
\includegraphics[width=.99\linewidth]{images/exp3d/exp3d_n_samples_all_weights.png}
\caption{3D compressible fluid experiment: Average test R$^2$ of predicted $\sqrt{\rho}$.
The colors indicate different PDE weights $w_2$ within each method.
The bars correspond to $95\%$ confidence intervals for the mean estimation based on $1000$ bootstrap samples. }
\label{app:fig:exp3d_n_samples_all_weights_boxplot}
\end{figure}
\begin{figure}[ht!]
\centering
\includegraphics[width=.3\linewidth]{images/exp3d/uniform_vs_mcmc_64k_vs_8k.png}
\caption{3D compressible fluid experiment: Boxplot of Test R$^2$ of predicted $\sqrt{\rho}$ comparing pdPINN and uniform sampling with a factor 8 difference for the number of collocation points.
For each method, the used PDE weight was selected based on the highest validation R$^2$. }
\label{app:fig:exp3d_8k_vs_65k}
\end{figure}
\subsection{Experiments: Heat Equation}
\label{appendix:heat}
The dataset for the heat equation experiment was generated by numerically solving the heat equation through the finite difference method, precisely the Forward Time, Centered Space (FTCS) approximation~\citep{Recktenwald2004FiniteDifferenceAT}.
We used Dirichlet boundary conditions in form of zero temperature around a squared shape far away from the relevant domain.
These boundary conditions are not provided to the PINNs for a slightly more difficult setting.
Overall, the dataset is composed of 1000 training points, 1'971'120 test points and 492'780 validation points.
We made sure training points contained enough information about the initial condition, i.e. we selected a sufficient amount of points around the initial source of non-zero temperature.
In contrast, validation and test points are taken uniformly in time and space.
The implementation is in PyTorch \citep{pytorch}, using the ADAM optimizer ~\citep{kingma2016adam} combined with an exponential learning rate scheduler which multiplies the learning rate by a factor of $0.9999$ at each epoch, starting with a rate of $10^{-4}$ and decreasing it until reaching a minimum value of $10^{-5}$.
Training was terminated through early-stopping, as soon as the validation R$^2$ didn't improve for more than 3000 epochs.
Figure \ref{fig:expheat_r2_results_weights} illustrates the test R$^2$ of the predicted $T$ averaged over 20 different seeds.
Error bars correspond to $95\%$ confidence interval for the mean estimation, based on 1000 bootstrap samples, while colors indicate the different PDE weights $w_2$ explored.
When the PDE loss is enforced with few samples (16) the regularization is not strong enough, which is to be expected.
Hence PINNs and pdPINNs show similar results in this regime.
However, as the number of samples increases (32-64-128-256), the PDE loss enforced by the proposed pdPINNs quickly outperforms uniform sampling.
Lastly, for a sufficiently large number of samples (512-1024) we see no significant difference within the two sampling procedures, as in such a low-dimensional domain the uniform sampling fully explores the considered area.
This, again, is in line with the observed results of the other experiments.
\begin{figure}[ht!]
\centering
\includegraphics[width=1\linewidth]{images/exp_heatequation/exp_heateq_nsamples_all_weights.png}
\caption{Test R$^2$ of predicted $T$ in the heat equation experiment as a function of different number of collocation points.
Results are averaged over 20 different seeds and the resulting error bars correspond to $95\%$ confidence interval for the mean estimation, based on 1000 bootstrap samples.
Different colors indicate different PDE weights $w_2$.
}
\label{fig:expheat_r2_results_weights}
\end{figure}
\section{Introduction}
\label{sec:introduction}
\input{subfiles/01_introduction}
\section{Related Work}
\label{sec:related_work}
\input{subfiles/02_related_work}
\section{Methodology}
\label{sec:methodology}
\input{subfiles/03_methodology}
\section{Model and Implementation}
\label{sec:model_and_implementation}
\input{subfiles/04_model_and_implementation}
\section{Experiments}
\label{sec:experiments}
\input{subfiles/05_experiments}
\section{Conclusion}
\label{sec:conclusion}
\input{subfiles/06_conclusion}
\subsection{Modeling Compressible Fluids}
\label{sec:PINN}
We consider the problem of modeling non-steady compressible fluids, i.e. fluids with a spatially and temporally evolving density $\rho(t, \bs x)$ and velocity $\bs v(t, \bs x)$.
For the sake of notational brevity, we will denote these by $\rho$ and $\bs v$ in the following.
Our particular interest lies in the prediction of particle movement and thus density $\rho$.
Given noisy observations of the density $\rho^{(i)}$, and potentially other quantities such as the velocity or pressure, we want to predict the density $\rho$.
Commonly, the PDE serves as a physics-based regularizer of the network by enforcing PDE loss $L_f$ in Eq.~(\ref{eq:PINN_pde_loss}) during standard PINN training.
For this, $L_f$ is evaluated on a set of collocation points that are, for example, uniformly distributed on a bounded region.
However, the limitations of this approach become apparent when considering an advection problem defined by the following PDE:
\begin{equation}
\label{eq:advection}
\partial_t \rho + \bs v\cdot (\nabla\rho)= 0.
\end{equation}
Figure \ref{fig:advection} illustrates a one-dimensional case on the domain $[0,T]\times \Omega$, with $\Omega = \mathbb{R}$, and a known constant velocity $v\propto1$.
We measure the density $\rho^{(i)}$ at different (spatially fixed) points in time and space $\{(t^{(i)}, \bs x^{(i)})\}$, on which a neural network $\rho_{\Theta}(t, \bs x)$ is trained.
For optimizing the standard PDE loss $L_f$ as given in Eq.~\eqref{eq:PINN_pde_loss}, we would require a bounded region $\Omega_{\mathcal{B}}:=[a,b] \subset \Omega$ with $a<b$ and $a,b \in \mathbb{R}$.
This, in turn, leads to two issues:
\begin{enumerate}
\item Our region of interest, the moving density, is concentrated on a small subset of $\Omega$.
Enforcing Eq.~\eqref{eq:advection} in areas with low-density has little regularizing effect on $\rho_\Theta$.
\item
In order to define appropriate boundaries of $\Omega_{\mathcal{B}}$, we require prior knowledge about the solution which depends on the time frame, velocity, and the underlying PDE.
Otherwise, the main bulk of density might move out of the considered area $\Omega_{\mathcal{B}}$.
\end{enumerate}
We note that for issue (1.), the dynamics of fluids are assumed to be mainly caused by local interactions of particles, which is the case for commonly considered dynamics of gases, liquids or active particles \citep{hoover2003links, toner1995long}.
Furthermore, the naive solution of selecting an arbitrary large area with $a\ll b$ for resolving (2.) would amplify the sparsity in (1.).
\begin{figure}
\centering
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=0.9\linewidth]{images/sketches/advection_initial_time_V2.png}
\caption{}
\label{fig:advection_gt_t0}
\end{subfigure}%
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=0.9\linewidth]{images/sketches/advection_uniform_V2.png}
\caption{}
\label{fig:advection_unif}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=0.9\linewidth]{images/sketches/advection_final_time_V2.png}
\caption{}
\label{fig:advection_gt_T}
\end{subfigure}%
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=0.9\linewidth]{images/sketches/advection_mcmc.png}
\caption{}
\label{fig:advection_mcmc}
\end{subfigure}
\caption{Linear advection experiment in one dimension: (a) ground truth at time $t_1$ and (c) time $t_2$, (b) density prediction with uniform collocation points and (d) Particle density based collocation points for $t\in\{t_1, t_2\}$. Cross points represent sampled collocation points at $t_1$ and $t_2$ with two different red shades.}
\label{fig:advection}
\end{figure}
Therefore, a proper resolution to these issues should be able to (i) focus on areas that have a relevant regularizing effect on the prediction of $\rho_\Theta$ and (ii) adapt to the fluid movements without being restricted to a predefined mesh.
Let us assume that we had access to the positions of each of the $N$ total particles via the function $\bs x_j(t)$, with $j\in \{0,1,\dots,N\}$.
We would then propose to use the following loss over these positions within the considered time frame $[0, T]$:
\begin{equation}
\label{eq:L_PD_sum}
{L}_{\text{pd}}(\Theta)=\frac{1}{T} \int_{t=0}^{T} \frac{1}{N}\sum_{j=0}^{N} \Big|\Big|f_\Theta\Big(t, \bs x_{j}(t)\Big)\Big|\Big|_2^2 \ \ dt.
\end{equation}
It can be seen that the average in Eq.~\eqref{eq:L_PD_sum} is a sample-based estimator of an expected PDE loss.
Namely, the expectation over the occupation probability of particles in the whole time frame, denoted by the molecular distribution $\Psi(t, \bs x) = \Psi(t) \Psi(\bs x| t)$ introduced in section \ref{sec:related_work}:
\begin{equation}
L_{\text{pd}}(\Theta) \approx \int_{t=0}^T \Psi(t) \int_{\Omega} \Psi(\bs x | t)\Big[||f_\Theta(t, \bs x_{j}(t))||_2^2 \Big] \ \ dt,
\end{equation}
where $\Psi(t) \propto 1$ due to the conservation of mass.
As the particle density corresponds directly to the occupation probability of a molecule $\Psi(t, \bs x)$ with a changed normalization constant,
we can estimate $L_{pd}$ via samples drawn from the normalized particle density or, similarly, from the normalized mass density when assuming a homogeneous fluid.
\subsection{Particle-Density PINNs}
\label{subsec:pdPINNs}
In summary, we propose to draw collocation points from the normalized density:
\begin{equation}
(t_i, \bs{x}_i) \sim \rho_N(t, \bs{x}) =
\tfrac{1}{Z}
\rho(t, \bs x).
\end{equation}
However, as the true density is unknow
, we instead rely on the learned density ${\rho}_{\Theta}(t, {\bs x})$ as a proxy provided by the neural network.
We denote the associated normalized PDF by $q_{\Theta}(t, {\bs x}) = \frac{1}{Z'} {\rho}_{\Theta}(t, {\bs x})$ with support on $[0, T] \times \Omega$.
The PDE loss is then defined as the expectation w.r.t.~$q$:
\begin{equation}
\label{eq:PINN_pde_loss_density}
{L}_{pd}(\Theta) = \mathbb{E}_{q_{\Theta}(t, \bs x)}\Big[ ||{f}_\Theta(t, \bs x)||_2^2 \Big] = \int_{t=0}^T q_{\Theta}(t) \int_{\Omega}
q_{\Theta}({\bs x | t})||{f}_\Theta(\bs x,t)||_2^2 \ d\bs x \ dt.
\end{equation}
In order to approximate this integral, samples need to be drawn from $q_\Theta(t, \bs x)$.
This can be done in a principled way by using dynamic Monte Carlo methods, despite the fact that the normalization constant $Z$ is unknown.
Such a sampling procedure additionally eliminates the need for $\Omega$ to be a bounded domain in settings where such boundaries are not available.
In contrast, methods based on the mesh-based loss in Eq.~\eqref{eq:PINN_pde_loss} are not directly applicable to unbounded domains such as $\Omega = \mathbb{R}^d$,
and potentially arbitrary boundaries have to be introduced.
Although motivated in the context of an advection problem, the proposed approach is generally applicable to compressible fluid dynamics settings and more general settings as we elaborate on below.
\paragraph{Further particle-based PDEs.}
The advection equation (\ref{eq:advection})
can be seen as a special case of mass conservation (assuming $\nabla \cdot \bs v = 0 $) which is one of the fundamental physical principles expressed as a \textit{continuity equation}.
The continuity equation relates temporal changes of the fluid density $\rho$ to spatial changes of the flux density $\rho \bs v$ through
\begin{equation}
\label{eq:continuity_equation_masscons}
\partial_t \rho + \nabla \cdot (\rho \bs v)= 0.
\end{equation}
Most famously, it belongs to a broader set of problems considering viscous flows, which are described by the Navier-Stokes equations.
An even more general setting, for which conservation laws such as the conservation of momentum do not hold, considers the modeling of self-propelled, active particles,
for which Toner and Tu \citep{toner1995long,tu1998sound,toner1998flocks,toner2012reanalysis} introduced hydrodynamic equations.
Our method is generally applicable in settings where (i) a non-negative scalar field (with a finite integral) of interest can be interpreted as a particle density,
and (ii) the local interactions of these particles give rise to the considered PDEs.
In the \textit{heat equation}, for instance, it is well-established that the diffusion of the temperature coincides with the diffusion of particles according to Fick's second law.
The diffusion of the temperature $T$ within a homogeneous medium is described by a parabolic PDE defined as
\begin{equation}
\label{eq:heat_equation}
\partial_t T - \alpha \nabla^2 T = 0,
\end{equation}
where $\alpha$ is the thermal diffusivity and $\nabla^2$ is the Laplacian operator.
For $T \coloneqq \rho$, the diffusion equation of particles is obtained, substituting the thermal diffusivity with the mass diffusivity.
Other possible applications involve Maxwell's equations for conservation of charge in electrodynamics.
\subsection{Particle Simulation of a Compressible Fluid}
\label{subsec:exp_compressible_fluid}
As a challenging prediction task, a non-steady compressible fluid in three dimensions is simulated by propagating fluid parcels through a pre-defined velocity field. In other words, we simulate a fluid from the Lagrangian perspective with the conservation of mass as the underlying PDE (see Eq.~\eqref{eq:continuity_equation_masscons}).
The paths of the roughly 240'000 parcels are solved for with a basic backward Euler scheme.
The particle density and velocity are obtained by counting the number of parcels within a voxel, and by averaging the individual velocities.
For the training observations provided to the network, we introduce a set of spatially fixed sensors (or \textit{radars}) which count the number of fluid parcels that are present within a radius $r$ at a given time.
The birds-eye view of the setting is shown in Figure \ref{fig:exp3d_birdeye}, where circles indicate the area covered by the radars.
Along the $z$-axis, the simulated sensor distinguishes over 21 contiguous altitude layers.
Another disjoint set of sensors is provided for the validation set while the test performance is evaluated on a grid.
Figure \ref{fig:exp3d_zaxis} shows the 3D simulated data projected along the $z$-axis and over time, which gives a complementary illustration with respect to the birds-eye view.
For details regarding the data set and the velocity field we refer to the Appendix section \ref{appendix:particle_simulation}.
The full code for the data generation, as well as the data sets themselves, is provided in the supplementary material.
We consider two different types of (common) application settings with increasing difficulty and dimensionality: (i) the 2D setting obtained by projecting onto the $xy$-plane, and (ii) the full 3D setting.
In both settings we look at the dynamics over the time frame $t\in[0, 3]$
and learn both the density and the velocity using two SIREN \citep{sitzmann2020implicit} networks $\rho_{\Theta_1}(t, \bs x)$ and $\bs v_{\Theta_2}(t, \bs x)$.
Within the experiments, the compared settings always correspond to similar architectures, hyperparameters, and optimizers.
In all
settings, the PDE used for regularizing the networks is the continuity equation for the conservation of mass (see Eq.~\eqref{eq:continuity_equation_masscons}).
\begin{figure}[ht!]
\centering
\begin{subfigure}{.49\textwidth}
\centering
\includegraphics[width=.88\linewidth]{images/exp2d/exp2d_nsamples.png}
\caption{}
\label{fig:exp2d_r2_results}
\end{subfigure}%
\begin{subfigure}{.49\textwidth}
\centering
\includegraphics[width=.88\linewidth]{images/exp3d/exp3d_nsamples.png}
\caption{}
\label{fig:exp3d_r2_results}
\end{subfigure}%
\caption{Explained variance of $\sqrt{\rho}$ evaluated on the test set, for different number of collocation points in the (a) 2D and (b) 3D experiment.
}
\end{figure}
\subsubsection{Projection on $xy$-plane}
In the 2D setting, the density and velocity are measured by $15^2$ sensors on the $xy$-plane within the area $[-4, 4]^2$ at 21 equidistant timesteps.
For each method, we perform a hyper-parameter search over different PDE-weights $w_2$ (see Eq.~\eqref{eq:PINN_argmin}) and select the one with the highest average validation R$^2$. Figure \ref{fig:exp2d_r2_results} shows the test R$^2$ performance for different numbers of collocation points and 11 different seeds, the distribution of which are visualized with the box plots.
Results clearly show that the proposed pdPINN outperforms competing methods across all number of collocation points.
Furthermore, we observe that the performance gap shrinks as the collocation points increase, eventually converging to the same limiting value.
This is expected, since in the high-sample limit the sample strategy becomes irrelevant and all methods should provide equivalent results.
However, what is relevant is that the proposed pdPINN model achieves significantly better results with significantly fewer collocation points.
We further took into consideration how the PDE-weight $w_2$ affects the performance as a function of the number of collocation points and verified we still obtain results consistent with Figure \ref{fig:exp2d_r2_results}.
We point the reader to the Appendix section \ref{appendix:particle_simulation} for a more detailed view of these results.
\begin{figure}[ht!]
\centering
\includegraphics[width=.8\linewidth]{images/exp3d/exp3d_proj1d_ot_vs_pdpinn_landscape.png}
\caption{3D setting predictions (obtained with 2048 collocation points) are summed over $xy$ grid cells to obtain $z$-axis projection over time. The OT-RAR method shows disconnected density predictions that violate mass conservation.}
\label{fig:exp3d_proj1d}
\end{figure}
\subsubsection{Full Three-Dimensional Setting}
In the 3D setting, the density and velocity are again measured by $15^2$ sensors on the $xy$-plane, but within the smaller area $[-3, 3]^2$ at 11 equidistant timesteps and 21 equidistant altitude layers.
Compared to the 2D setting, we have a spatially denser set of sensors, but fewer time steps.
Qualitative results are reported in Figure \ref{fig:exp3d_proj1d}, displaying the density predictions over time and projected over the $z$-axis.
This is obtained by summing over the $xy$ grid cells and allows us to visualize that the OT-RAR predictions clearly violate mass conservation.
Conversely, the pdPINN model accurately predicts the density while also faithfully enforcing the continuity equation.
In Figure \ref{fig:exp3d_r2_results} we quantitatively evaluate the performance of the different methods for different numbers of collocation points, with the method-specific PDE-weight $w_2$ being selected as in the 2D setting.
Also in the 3D setting, quantitative results show that the proposed pdPINN approach outperforms baseline methods across all number of collocation points.
As expected, in this higher-dimensional (3D and time) setting the difference in performances is even more pronounced.
Already with very few collocation points (512) pdPINNs achieve results comparable with those obtained with orders of magnitude more points (32768).
We verified that, even when getting close to the memory limit of a NVIDIA Titan X GPU, other sampling strategies at best achieve comparable results with pdPINNs.
Lastly, results from the 2D and 3D experiments suggest that the strength of the proposed method would be even more considerable for higher-dimensional settings.
\subsection{Heat Equation}
We further consider a 2D diffusion problem, namely the heat equation introduced in section \ref{subsec:pdPINNs}, where randomly distributed sensors provide measurements of the temperature.
We focus on a general setting with the initial conditions being zero temperature everywhere except for a specified region, as shown in Figure \ref{fig:heateq_gt}, and we let the system evolve in the time range $t\in[0,0.2]$.
The networks are only provided sensor measurements of the temperature.
For details regarding the training and test data we refer to the Appendix section \ref{appendix:heat}.
During the warm-up phase of the pdPINN, collocation points are sampled uniformly, and afterwards $90\%$ of the samples are drawn from the particle density distribution, which is proportional to the modeled temperature.
Collocation points are re-sampled every 500 epochs.
Differently from previous experiments, the employed architecture is a fully-connected two-layer neural network with 32 hidden units and tanh activations.
Density predictions for PINNs with uniform sampling and pdPINNs are illustrated in Figure \ref{fig:heateq_uniform} and \ref{fig:heateq_mcmc}, respectively, and compared with the ground truth in Figure \ref{fig:heateq_gt}.
We can clearly observe that the uniform sampling strategy does not allow putting enough focus on the relevant parts of the domain, i.e. regions with high temperature, and that it visibly fails to reconstruct the temperature profile.
In contrast, the pdPINN approach allows sampling in the region of higher density and reliably predicts the true temperature at all times.
We also evaluate quantitatively the performance of the two approaches in terms of the R$^2$ test error over the predicted temperature.
Consistent with previous 2D and 3D compressible fluids experiments, we show that the proposed pdPINNs outperform PINNs with uniform sampling strategy.
As in previous settings, we show that with few samples the regularization enforced by the PDE loss is not strong enough, leading to comparable results in both approaches.
However, as the number of sample increases, the PDE loss enforced with MCMC samples quickly and steadily outperforms uniform sampling.
We also verified that in the limit of high samples the two sampling strategies converge, as expected.
Further details regarding the quantitative results are discussed in the Appendix section \ref{appendix:heat}.
\begin{figure}[ht!]
\centering
\begin{subfigure}{.31\textwidth}
\centering
\includegraphics[width=.85\linewidth]{images/exp_heatequation/true_temperature.png}
\caption{}
\label{fig:heateq_gt}
\end{subfigure}%
\begin{subfigure}{.31\textwidth}
\centering
\includegraphics[width=.85\linewidth]{images/exp_heatequation/predicted_temperature_unif.png}
\caption{}
\label{fig:heateq_uniform}
\end{subfigure}
\begin{subfigure}{.37\textwidth}
\centering
\includegraphics[width=.89\linewidth]{images/exp_heatequation/predicted_temperature_mcmc.png}
\caption{}
\label{fig:heateq_mcmc}
\end{subfigure}
\caption{Temperature predictions of the heat equation experiment (trained with 128 collocation points) at time $t\sim0.044$.
(a) ground truth (b) uniform sampling, and (c) pdPINN.}
\end{figure}
\subsection{Bounded convolution of the network}
\subsection{Background Sampling for pdPINNs}
\label{appendix:background}
At initialization, the network prediction $\rho_\Theta$ is random and thus does not carry any useful information, i.e. sampling from this density would be meaningless.
Therefore, we start training the pdPINNs with a warm-up phase in which samples are obtained from a pre-specified background distribution:
\begin{equation}
\bs x \sim p_{bg}(t, \bs x)=p(t)p_{bg}(\bs x | t)
\end{equation}
with $p(t) = \mathcal{U}(0, T)$.
To avoid introducing a mesh, we could rely on the previously estimated Gaussian distribution introduced in Section \ref{sec:model_and_implementation}, i.e. $p_{bg}(\bs x|t) = p_{\text{gauss}}(\bs x)$.
As a second alternative, approach we consider random linear combinations of the convex hull of $\{x^{(i)}\}_{i=1}^N$ spanned by $c$ data points summarized as rows of matrix $Z\in \mathbb{R}^{c\times d}$. This leads to $\bs x = {\bs m}Z$ with weight $\bs m\in \mathbb{R}^c$ which can be drawn from a Dirichlet distribution, i.e. $\bs m \sim Dir(\bs \alpha=1)$.
Of course, a uniform sampling mechanism on a defined region is also suitable
and the definitive choice strongly depends on the data and PDE at hand.
We initially draw all samples from the background distribution, and then slowly increase the proportion of samples obtained from the particle density, as we found that leaving some background samples slightly helps in the training.
\subsection{Implementation of RAR and OT-RAR}
\label{appendix:implementation}
For our comparison, we considered the adaptive refinement methods \textit{RAR} and \textit{OT-RAR}, proposed by \citet{lu2021deepxde} and \citet[preprint]{tadiparthi2021optimal}.
Both methods rely on consecutive refinements of a fixed grid in the initial proposal.
The number of collocation points is steadily increased and collocation points once added will not be removed.
To allow for a more fair comparison, we adapt both methods to use a limited budget of points, and in addition we regularly resample them.
This leads to a slightly modified version of the methods which is similar in spirit.
For learning the linear mapping proposed by \citet{tadiparthi2021optimal}, we rely on the PyOT \citep{flamary2021pot} implementation of \citet{knott1984optimal}.
The pseudo-code for sampling a set of collocation points is given in Algorithm \ref{alg:rar} and Algorithm \ref{alg:ot-rar}.
The required input $f_\Theta$ refers to the PDE approximated by the network, as discussed in Section \ref{sec:introduction}.
For more specific details on the methods we refer to the original papers.
\begin{algorithm}
\caption{Adapted RAR}\label{alg:rar}
\begin{algorithmic}
\Require $f_\Theta$, uniform distribution $\mathcal{U}_{\mathcal{B}}$,\\ \hspace{7mm} number of col. points $k$,\ previous col. points $X_{\text{prev}}$.
\\
\State $X_{\text{prop}} \hspace{1.2mm} \gets [\bs x_1,\bs x_2, \dots, \bs x_k]^T$ with $\bs x_i \sim \mathcal{U}_{\mathcal{B}}$ \Comment{Sample proposals}
\State $X_\text{comb} \hspace{0.3mm} \gets$ concat($X_{\text{prev}}$, $X_{\text{prop}}$) \Comment{Concatenate old and new points}
\State $X_{\text{new}} \hspace{1.7mm} \gets \text{topk}(X_\text{comb},\ ||f_\Theta(X_\text{comb})||_2^2,\ k)$ \Comment{Keep top $k$ proposed points based on $f_{\Theta}$}
\\
\Ensure $X_{\text{new}}$
\end{algorithmic}
\end{algorithm}
\begin{algorithm}
\caption{Adapted OT-RAR}
\label{alg:ot-rar}
\begin{algorithmic}
\Require $f_\Theta$, uniform distribution $\mathcal{U}_{\mathcal{B}}$, \\ \hspace{7mm} number of col. points $k$, \\ \hspace{8mm}number of points for empirical distribution $j<2k$, \\ \hspace{7mm} previous col. points $X_{\text{prev}}$.
\\
\State $X_{\text{prop}} \hspace{2mm} \gets [\bs x_1,\bs x_2, \dots, \bs x_k]^T$ with $\bs x_i \sim \mathcal{U}_{\mathcal{B}}$ \Comment{Sample proposals}
\State $X_\text{comb} \hspace{1.1mm} \gets$ concat($X_{\text{prev}}$, $X_{\text{prop}}$) \Comment{Concatenate old and new points}
\\
\State $X_{\text{target}} \hspace{1.1mm} \gets \text{topk}(X_\text{comb},\ ||f_\Theta(X_\text{comb})||_2^2,\ j)$ \Comment{$j$ samples for target empirical distribution}
\State $X_{\text{source}} \hspace{0.3mm} \gets [\bs x_1,\bs x_2, \dots, \bs x_{j}]^T$ with $\bs x_i \sim \mathcal{U}_{\mathcal{B}}$ \Comment{$j$ samples for source empirical distribution}
\\
\State $M_\text{OT} \hspace{2.9mm} \gets \text{LinOT}(X_{\text{source}}, X_{\text{target}})$ \Comment{Obtain linear operator that maps to target distribution}
\\
\State $X_{\text{new}} \hspace{2.5mm} \gets [\bs x_1,\bs x_2, \dots, \bs x_k]^T$ with $\bs x_i \sim \mathcal{U}_{\mathcal{B}}$ \Comment{Sample uniformly}
\State $X_{\text{map}} \hspace{2.3mm} \gets M_\text{OT}(X_{\text{new}}) $ \Comment{Map samples to target distribution}
\\
\Ensure $X_{\text{map}}$
\end{algorithmic}
\end{algorithm}
\subsection{Experiments: Compressible Fluid}
\label{appendix:particle_simulation}
In the supplement, we provide code in Python for the data generation and for the pdPINN model. Below we provide the details for all the experiments we conducted.
Furthermore, we provide short videos showing the predicted density movements for each different approach.
More details on this can be found in the \texttt{README.html}
provided in the supplementary files.
The model is implemented using PyTorch \citep{pytorch}, with a custom Python implementation of the Metropolis-Hastings MCMC sampler relying on NumPy, SciPy, and Numba \citep{numpy, scipy, numba}.
All experiments were run on \textit{Nvidia GeForce GTX Titan X GPUs} with 12 GB VRAM.
A total of 6 GPUs were available, which were used to parallelize multiple runs.
In most settings, training in each experiment took less than 10 minutes.
The only exceptions were settings with a large amount of collocation points, with the bottleneck being the non-optimized bare-bones implementation of the Metropolis-Hastings sampler.
\subsubsection{Data Generation}
The velocity field in the $xy$-plane was generated from a scalar potential field $\Phi: \mathbb{R}^2 \rightarrow \mathbb{R}$ and the z-component of a vector potential $a: \mathbb{R}^2 \rightarrow \mathbb{R}$.
Through the Helmholtz decomposition%
\footnote{This is the 2D formulation of the Helmholtz decomposition, where the vector potential has non-zero components only along the $z$-axis as in $\bs a_{\text{3d}} = [0,0,a]^T$. The full decomposition is commonly written as $\bs v_{\text{3d}} = -\nabla \Phi_{\text{3d}} + \nabla \times \bs a_{\text{3d}}$.}
we can construct the velocity field $\bs v_{\text{xy}}: \mathbb{R}^2 \rightarrow \mathbb{R}^2$:
\begin{equation}
\bs v_{\text{xy}}\Bigg(\begin{bmatrix}x \\ y\end{bmatrix}\Bigg) = - \nabla \Phi + \begin{bmatrix}{\delta a}/{\delta y} \\ -{\delta a}/{\delta x}\end{bmatrix}.
\end{equation}
For both experiments the following fields were used:
\begin{align}
\Phi\Bigg(\begin{bmatrix}x \\ y\end{bmatrix}\Bigg) &= - \frac{1}{2}(x-2) \cdot (y-2),
\\
a\Bigg(\begin{bmatrix}x \\ y\end{bmatrix}\Bigg) &= - \frac{1}{5} \exp\Bigg( - \Big( \frac{2}{3}x\Big)^2 - \Big(\frac{2}{3}y\Big)^2 \Bigg).
\end{align}
The derivatives were obtained using the symbolic differentiation library SymPy \citep{sympy}.
To add a nonsteady component, the resulting velocity field is modulated in amplitude as a function of time $t\in [0, 3]$:
\begin{equation}
\bs v_{\text{xyt}}\Bigg(t, \begin{bmatrix}x \\ y\end{bmatrix}\Bigg) = \bs v_{\text{xy}}\Bigg(\begin{bmatrix}x \\ y\end{bmatrix}\Bigg) \left( \frac{3}{2} \left|\sin\left( \frac{2}{3} \pi t \right)\right| + 0.05\right).
\end{equation}
The $z$ (altitude) component of the velocity only depends on time and is given by:
\begin{equation}
v_z(t) = 1.6\cdot\sin\left( \frac{4}{3} \pi t \right).
\end{equation}
For the initial distribution of the fluid, the parcel positions were drawn from Gaussian mixtures.
For $t\in[0,3]$, these parcels were simulated using the above constructed velocity field.
The \textit{measurements} at the sensors were obtained by counting the number of parcels within a given radius over multiple timesteps.
The density corresponds to the mass divided by the sensor area, and the velocity is an average over all the parcel velocities.
For the training data additional zero-mean isotropic Gaussian noise is added to all measurements.
\subsubsection{Architecture and Training}
In both experiments, the networks for density $\rho_{\Theta_1}$ and velocity $v_{\Theta_2}$ prediction (parameterized by ${\Theta_1}$ and ${\Theta_2}$, respectively) are fully-connected layers with sinusoidal activation functions, as proposed by \citet{sitzmann2020implicit}.
The number of layers and units for each setting is shown in Table \ref{table:architecture}.
The sine frequency hyperparameter required in the SIREN architecture was tuned by hand according to the validation loss of the baseline model (i.e. without a PDE loss), leading to a sine-frequency of $12$ for the 2D setting, and $5$ for the 3D setting.
We note that the proposed default value of $30$ in \citet{sitzmann2020implicit} heavily overfits our relatively low-frequency data and we thus recommend an adjustment of this hyperparameter for usage in PINNs.
For training the network, the ADAM optimizer ~\citep{kingma2016adam} with a learning rate of $8\times 10^{-4}$ (2D Setting) or $10^{-4}$ (3D Setting) was used.
The learning rate was multiplied by a factor of $0.99$ each epoch.
All models were trained for 300 (3D setting) or 500 (2D setting) epochs.
The 2D setting was trained using full-batch gradient descent, whereas for the 3D setting we used a mini-batch size of $6931$.
In all experiments we trained and evaluated on 10 different random seeds.
\begin{table}[h]
\caption{Architecture for Particle Simulation Experiments.}
\label{table:architecture}
\centering
\begin{tabular}{llllll}
\toprule
Experiment & Input & Output Variable & \# Hidden Layers & \# Hidden Units \\
\midrule
2D & $[0, T]\times \mathbb{R}^2$ & Density\ $\rho_{\Theta_1} \in \mathbb{R}_+$ & 2 & 256 \\
& & Velocity $\bs v_{\Theta_2} \in \mathbb{R}^2$ & 1& 64 \\
\midrule
3D & $[0, T]\times \mathbb{R}^3$ & Density\ $\rho_{\Theta_1}\in \mathbb{R}_+$ & 6 & 256 \\
& & Velocity $\bs v_{\Theta_2} \in \mathbb{R}^3$ & 3 & 256 \\
\bottomrule
\end{tabular}
\end{table}
\subsubsection{Results for varying PDE Weights}
As mentioned in Section \ref{subsec:exp_compressible_fluid}, the weight of the PDE loss term has to be adjusted depending on the number of collocation points and the chosen loss term.
For a low number of collocation points, a high weight for the PDE loss will disturb the training, resulting in worse performance than the baseline without additional regularization.
The more collocation points are used, the higher the weight can be without leading to negative effects.
Consequently, one would ideally have to optimize the weight depending on the number of collocation points.
Figures \ref{app:fig:exp2d_n_samples_all_weights_boxplot} and \ref{app:fig:exp3d_n_samples_all_weights_boxplot} show this behaviour for the 2D and 3D setting of the compressible fluid experiment.
The colors indicate different weights for the respective method, with the color gradient (blue $\rightarrow$ red) indicating the increase of the weight.
It is important to note, that the colors between different methods should not be interpreted as similar weights.
Each method relies on a different loss, making a comparison of the weights for this loss meaningless.
We can see in both settings, that \textit{pdPINN} performs favourably, especially when using only few collocation points.
To emphasize the advantage provided by pdPINNs, Figure \ref{app:fig:exp3d_8k_vs_65k} compares the proposed pdPINN with only $8192$ collocation points with the uniform sampler using $65536$ (i.e. a factor of $8$), which is for our implementation close to the hardware limit of the used GPU with 12GB VRAM (depending on the used network architecture and mini-batch size).
In both cases, we selected the PDE weight $w_2$ based on the maximum validation R$^2$.
As a sidenote, the deviation of pdPINN at 128 collocation points is caused by a single outlier out of the 10 different random seeds.
\begin{figure}[ht!]
\centering
\includegraphics[width=.99\linewidth]{images/exp2d/exp2d_n_samples_all_weights.png}
\caption{2D compressible fluid experiment: Average test R$^2$ of predicted $\sqrt{\rho}$.
The colors indicate different PDE weights $w_2$ within each method.
The bars correspond to $95\%$ confidence intervals for the mean estimation based on $1000$ bootstrap samples.
}
\label{app:fig:exp2d_n_samples_all_weights_boxplot}
\end{figure}
\begin{figure}[ht!]
\centering
\includegraphics[width=.99\linewidth]{images/exp3d/exp3d_n_samples_all_weights.png}
\caption{3D compressible fluid experiment: Average test R$^2$ of predicted $\sqrt{\rho}$.
The colors indicate different PDE weights $w_2$ within each method.
The bars correspond to $95\%$ confidence intervals for the mean estimation based on $1000$ bootstrap samples. }
\label{app:fig:exp3d_n_samples_all_weights_boxplot}
\end{figure}
\begin{figure}[ht!]
\centering
\includegraphics[width=.3\linewidth]{images/exp3d/uniform_vs_mcmc_64k_vs_8k.png}
\caption{3D compressible fluid experiment: Boxplot of Test R$^2$ of predicted $\sqrt{\rho}$ comparing pdPINN and uniform sampling with a factor 8 difference for the number of collocation points.
For each method, the used PDE weight was selected based on the highest validation R$^2$. }
\label{app:fig:exp3d_8k_vs_65k}
\end{figure}
\subsection{Experiments: Heat Equation}
\label{appendix:heat}
The dataset for the heat equation experiment was generated by numerically solving the heat equation through the finite difference method, precisely the Forward Time, Centered Space (FTCS) approximation~\citep{Recktenwald2004FiniteDifferenceAT}.
We used Dirichlet boundary conditions in form of zero temperature around a squared shape far away from the relevant domain.
These boundary conditions are not provided to the PINNs for a slightly more difficult setting.
Overall, the dataset is composed of 1000 training points, 1'971'120 test points and 492'780 validation points.
We made sure training points contained enough information about the initial condition, i.e. we selected a sufficient amount of points around the initial source of non-zero temperature.
In contrast, validation and test points are taken uniformly in time and space.
The implementation is in PyTorch \citep{pytorch}, using the ADAM optimizer ~\citep{kingma2016adam} combined with an exponential learning rate scheduler which multiplies the learning rate by a factor of $0.9999$ at each epoch, starting with a rate of $10^{-4}$ and decreasing it until reaching a minimum value of $10^{-5}$.
Training was terminated through early-stopping, as soon as the validation R$^2$ didn't improve for more than 3000 epochs.
Figure \ref{fig:expheat_r2_results_weights} illustrates the test R$^2$ of the predicted $T$ averaged over 20 different seeds.
Error bars correspond to $95\%$ confidence interval for the mean estimation, based on 1000 bootstrap samples, while colors indicate the different PDE weights $w_2$ explored.
When the PDE loss is enforced with few samples (16) the regularization is not strong enough, which is to be expected.
Hence PINNs and pdPINNs show similar results in this regime.
However, as the number of samples increases (32-64-128-256), the PDE loss enforced by the proposed pdPINNs quickly outperforms uniform sampling.
Lastly, for a sufficiently large number of samples (512-1024) we see no significant difference within the two sampling procedures, as in such a low-dimensional domain the uniform sampling fully explores the considered area.
This, again, is in line with the observed results of the other experiments.
\begin{figure}[ht!]
\centering
\includegraphics[width=1\linewidth]{images/exp_heatequation/exp_heateq_nsamples_all_weights.png}
\caption{Test R$^2$ of predicted $T$ in the heat equation experiment as a function of different number of collocation points.
Results are averaged over 20 different seeds and the resulting error bars correspond to $95\%$ confidence interval for the mean estimation, based on 1000 bootstrap samples.
Different colors indicate different PDE weights $w_2$.
}
\label{fig:expheat_r2_results_weights}
\end{figure}
| {'timestamp': '2022-06-06T02:13:15', 'yymm': '2206', 'arxiv_id': '2206.01545', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01545'} | arxiv |
\section{Introduction}
Ego-motion estimation, aka. odometry estimation, finds a plethora of applications ranging from the localization and mapping for mobile robots to the pose tracking of wearable devices. By leveraging different navigation sensors (e.g., cameras, LiDAR, and inertial measurement unit (IMU)), last decades witnessed an upsurge of egomotion estimation systems proposed in various use cases \cite{zhang2014loam, campos2021orb, qin2018vins}. These odometry systems, however, all have intrinsic limitations under certain conditions attributed to their underlying sensing mechanism. To name a few, LiDAR data suffers from self-similar structures and environments full of airborne particles (e.g., smoke), while RGB cameras fall short in low illumination and high dynamic range scenarios. IMUs are susceptible to the drifts in large distances or a large magnitude of movement. Realizing the intrinsic limitation of individual sensors, multimodal odometry that jointly uses heterogeneous navigation sensors has received recent attention to enhance the overall robustness of an egomotion estimation. The success of such an odometry system starts from the public availability of multi-sensor datasets which enable systematic testing and community benchmark of different algorithms.
\begin{figure}
\centering
\includegraphics[width=3.3in]{fig/openfig-compressed.pdf}
\caption{A data example captured in poor illumination from our multimodal odometry dataset. In addition to the above five modalities, our dataset also includes solid-state LiDAR and IMU sensors.}
\label{openfig}
\end{figure}
\begin{table*}[!t]
\renewcommand{\arraystretch}{1.3}
\caption{Comparison of multimodal odometry datasets}
\label{table_example}
\centering
\begin{threeparttable}
\begin{tabular}{cccccccccc}
\hline
Dataset & Year & Environment & Platform & Radar & LiDAR & RGB & Stereo & Thermal & IMU\\
\hline
KAIST Day/Night\cite{choi2018kaist} & 2018 & Urban & Car & \xmark & \cmark & \cmark & \cmark & \cmark & \cmark\\
Oxford Radar RobotCar\cite{barnes2020oxford} & 2020 & Urban & Car & \cmark & \cmark & \cmark & \cmark & \xmark & \cmark\\
USVInland\cite{cheng2021we} & 2021 & Inland Water & USV & \cmark & \cmark & \cmark & \cmark & \xmark & \cmark \\
ViViD\cite{Lee2019ViViDV} & 2019 & In-/outdoor & Handheld & \xmark & \cmark & \cmark & \cmark & \cmark & \cmark \\
ColoRadar\cite{kramer2021coloradar} & 2020 & In-/outdoor & Handheld/Longboard & \cmark & \cmark & \xmark & \xmark & \xmark & \cmark \\
Weichen Dai et al.\cite{dai2020dataset} & 2020 & In-/outdoor & Handheld & \xmark & \xmark & \cmark & \cmark & \cmark & \cmark\\
Ours & 2022 & Indoor & Handheld/UGV/UAV & \cmark & \cmark & \cmark & \cmark & \cmark & \cmark\\
\hline
\end{tabular}
\end{threeparttable}
\end{table*}
While there exists quite some multimodal odometry datasets \cite{dai2020dataset, Lee2019ViViDV, kim2020mulran, choi2018kaist} in the community, these datasets are limited to the \emph{diversity} in terms of both the navigation sensors onboard and the mobile platforms carrying them. Moreover, multimodal datasets to date are found heavily skewed towards outdoor or urban scenarios, with the indoor datasets mainly dictated by the visual or visual-inertial odometry \cite{schubert2018vidataset, cortes2018advio}. Unfortunately, such a scenario skewness does not coincide with the recent breakthroughs of miniaturised sensors such as single-chip mmWave radars, solid-state sensors and portable thermal cameras. These miniaturized sensors not only become increasingly cost-effective and portable than ever, but also complement the electromagnetic (EM) spectrum covered by conventional navigation sensors. For example, compared with the cameras that only occupy the visible spectrum, mmWave radars and Long Wave Infrared (LWIR) thermal cameras operate at 77~GHz ($4\,mm$ wavelength) and 30~THz ($10\,\mu m$ wavelength) respectively. The extra EM spectrum covered by these emerging sensors can in turn, yield more sensing robustness against poor illumination, airborne particles and visual aliasing etc.
Towards a more \emph{comprehensive} multimodal dataset for odometry evaluation, this work presents a new odometry dataset constituted of the sensory data covering a wide range of electromagnetic frequencies (c.f., Fig.\ref{openfig}). To our best knowledge, this presented dataset features the widest range of mobile platforms and includes robust navigation sensors that emerged recently. Specifically, we recorded 6-Degree-of-Freedom (6DoF) motion with accurate ground truth on (i) Unmanned Aerial Vehicle (UAV), (ii) Unmanned Ground Vehicle (UGV) and (iii) handheld platforms. We equip these platforms with the emerging mmWave radars, portable thermal cameras and solid-state LiDARs, co-located with the traditional navigation modalities such as spinning LiDAR, RGB-D camera and IMUs. We hope that by making available our data from both emerging and conventional sensors, unprecedented sensor fusion approaches can be yielded on various platforms and different use cases in the wild.
The main contributions of our datasets are summarised as follows:
\begin{itemize}
\item We present an indoor odometry dataset containing the data from both emerging and traditional navigation sensors on diverse platforms. This is the first indoor dataset that simultaneously covers the mmWave and LWIR thermal spectrum.
\item We record the odometry data in 7 different categories of indoor scenes which feature dynamic illumination and various motion patterns. The whole dataset exceeds 10~km in trajectory length.
\item We provide extrinsic calibration parameters for all platforms and intrinsic parameters for all optic sensors, accompanied by several plug-and-play codes for developing multimodal odometry systems with our dataset.
\end{itemize}
\begin{figure*}
\centering
\includegraphics[width=6.5in]{fig/platform-new-compressed.pdf}
\caption{Our sensor setup for UAV, UGV and handheld platform.}
\label{rig}
\end{figure*}
\section{Related Work}
A multitude of odometry datasets have been proposed over the last decades, but most of them focus on common visual or LiDAR modalities, while ignoring the emerging radar and thermal sensors. We refer the readers interested in traditional multimodal odometry datasets to \cite{zhan2020visual,geiger2013vision}, and discuss the work related to:
\noindent \textbf{LWIR Thermal Cameras.}
Recent years have seen multiple indoor datasets utilizing the LWIR thermal spectrum. The SubT-Tunnel dataset \cite{rogers2020test} features trajectories in an underground mine from the DARPA Subterranean challenge. Since it is based on the UGV platform only, its movement is restricted to 2D. Indoor trajectories in the ViVid dataset \cite{Lee2019ViViDV} are limited to their Vicon room. This guarantees they have accurate ground truth pose and trajectory, but it also means they do not contain enough scene variety. The multi-spectral dataset \cite{dai2020dataset} is another RGB/thermal camera dataset featuring hardware time synchronization.
\noindent \textbf{mmWave Radars.}
In the meantime, datasets that include radars are mostly recorded for developing advanced driver assistance systems (ADAS). Notable examples include Oxford Radar RobotCar \cite{barnes2020oxford} and nuScenes \cite{caesar2020nuscenes} datasets. However, the radar used in \cite{barnes2020oxford} is a mechanical spinning radar while the single-chip radar used in \cite{caesar2020nuscenes} can only give point clouds in a 2D plane.
The only radar dataset comparable to ours in terms of sensors and scenes is the ColoRadar dataset \cite{kramer2021coloradar}, which features a single-chip mmWave radar, and a cascaded radar. However, the lack of RGB, thermal and Stereo modalities means it cannot support the comparison between radar algorithms and other more popular modalities in the same situation. Furthermore, due to the sparse point cloud generated by radars, our wide-fov 3-radar setup on the UGV platform provides a lot more information than the forward-facing radar setup in ColoRadar.
Unlike all the above works, to our best knowledge, our dataset is the first one that \emph{simultaneously} contain the LWIR camera and mmWave radar sensors, while featuring long trajectories in diversified indoor environments, wide-angle radar arrays, and three different platforms.
\noindent \textbf{Mobile Platforms.}
Platform-wise, different mobile platforms have different movement characteristics and impose different challenges for odomerty estimation. Compared to other indoor multi-modal datasets that mostly only use handheld platform\cite{Lee2019ViViDV, dai2020dataset}, our dataset is the only one that includes all three viable mobile agents in an indoor environment: UAV, UGV and handheld.
\section{Dataset}
\subsection{Sensor Setup}
\begin{figure*}[!t]
\centering
\includegraphics[width=1.3in]{fig/scene_glare_rgb-min.png}
\hfil
\includegraphics[width=1.3in]{fig/scene_dim_rgb-min.png}
\hfil
\includegraphics[width=1.3in]{fig/scene_dark_rgb-min.png}
\hfil
\includegraphics[width=1.3in]{fig/scene_glassy_rgb-min.png}
\hfil
\includegraphics[width=1.3in]{fig/scene_canteen_rgb-min.png}
\\
\subfloat[]{\includegraphics[width=1.3in]{fig/scene_glare_thermal-min.png}%
\label{scene-1}}
\hfil
\subfloat[]{\includegraphics[width=1.3in]{fig/scene_dim_thermal.png}%
\label{scene-2}}
\hfil
\subfloat[]{\includegraphics[width=1.3in]{fig/scene_dark_thermal-min.png}%
\label{scene-3}}
\hfil
\subfloat[]{\includegraphics[width=1.3in]{fig/scene_glassy_thermal-min.png}%
\label{scene-4}}
\hfil
\subfloat[]{\includegraphics[width=1.3in]{fig/scene_canteen_thermal-min.png}%
\label{scene-5}}
\caption{Examples of Scene Variety - top row from RGB cameras and bottom row from co-located LWIR thermal cameras. We took our sensor rigs to 4 different buildings to collect a variety of scenes. (a) to (c) show different illumination levels, from bright with glares to dimmed to complete darkness. (d) shows large quantities of reflective and transparent surfaces, while (e) shows complex 3D topology in the canteen area.}
\label{scene-variety}
\end{figure*}
\begin{table}
\centering
\caption{Sensor specs. on three platforms.}
\label{table_sensor}
\begin{tabular}{l|l}
\toprule
\multicolumn{2}{c}{\textit{Handheld}} \\
\toprule
1x RGBD Camera &
\begin{tabular}[c]{@{}l@{}}Intel RealSense D435i stereo camera \\ 20Hz 8bit 640x480 RGB image \\ 30Hz 16bit 640x480 depth image\end{tabular} \\
\hline
1x Thermal Camera &
\begin{tabular}[c]{@{}l@{}}FLIR Boson 640 thermal camera \\30Hz 16bit 640x512 thermal image\end{tabular}\\
\hline
1x LiDAR &
\begin{tabular}[c]{@{}l@{}}Velodyne VLP-16 LiDAR \\10Hz 16-channel point cloud\end{tabular}\\
\hline
1x Radar &
\begin{tabular}[c]{@{}l@{}}TI AWR1843BOOST mmWave radar \\20Hz point cloud\end{tabular}\\
\hline
1x IMU &
\begin{tabular}[c]{@{}l@{}}Xsens MTi \\100Hz inertial data and orientation\end{tabular}\\
\bottomrule
\multicolumn{2}{c}{\textit{UGV}} \\
\toprule
1x RGBD Camera &
\begin{tabular}[c]{@{}l@{}}Intel RealSense D435i stereo camera \\ 30Hz 8bit 640x480 RGB image \\ 30Hz 16bit 640x480 depth image\end{tabular}\\
\hline
1x Thermal Camera &
\begin{tabular}[c]{@{}l@{}}FLIR Boson 640 thermal camera \\ 30Hz 16bit 640x512 thermal image\end{tabular} \\
\hline
1x LiDAR & \begin{tabular}[c]{@{}l@{}}Velodyne HDL-32E LiDAR \\ 10Hz 32-channel point cloud\end{tabular}\\
\hline
3x Radar &
\begin{tabular}[c]{@{}l@{}}TI AWR1843BOOST radars at 90deg angles\\ 20Hz point cloud\end{tabular} \\
\hline
1x IMU &
\begin{tabular}[c]{@{}l@{}}Xsens MTi \\100Hz inertial data and orientation\end{tabular}\\
\bottomrule
\multicolumn{2}{c}{\textit{UAV}} \\
\toprule
1x Solid-state LiDAR &
\begin{tabular}[c]{@{}l@{}} Intel RealSense L515 Solid-state LiDAR \\15Hz 8bit 960x540 RGB image \\30Hz 16bit 640x480 depth image\end{tabular} \\
\hline
1x Thermal Camera &
\begin{tabular}[c]{@{}l@{}}FLIR Boson 640 thermal camera \\8.7Hz 8bit 640x512 thermal images \end{tabular} \\
\hline
1x Radar &
\begin{tabular}[c]{@{}l@{}}TI AWR1843BOOST mmWave radar\\ 10Hz point cloud\end{tabular} \\
\hline
1x IMU &
\begin{tabular}[c]{@{}l@{}}Xsens MTi \\100Hz inertial data and orientation\end{tabular}\\
\bottomrule
\end{tabular}
\end{table}
We collected the data from three platforms, handheld, UAV and UGV, shown in Fig. \ref{rig}. An overview of sensors and their platforms and characteristics are presented in Table. \ref{table_sensor}. The sensor kit includes Intel Realsense D435 stereo camera, RealSense L515 Solid-state LiDAR, FLIR Boson thermal camera, Velodyne VLP-16 and VLP-32, TI AWR1843 mmWave radar and Xsens MTi IMU. UGV has the most room for sensor installment, thus, we used Velodyne HDL-32E and two more radars than on the Handheld platform. On the UAV platform, we switched D435i stereo camera and Velodyne LiDAR for an Intel RealSense L515 Solid-state LiDAR due to the limited payloads of drones.
\subsection{Dataset Collection}
Indoor scenes can vary in many aspects, and such data variety impacts many models, especially learning-based ones, in terms of generalizability and transferability. In this regard, we collect the dataset under diverse environments and motion patterns. Detailed environment and motion description in each sequence is provided along-side the dataset. We give a brief summary in this section.
\subsubsection{Sequences} Our dataset collects 44 handheld sequences and 75 UGV sequences through multiple floors in 4 different buildings, providing a large variety of different visual traits, spatial characteristics and illumination conditions. Representative samples are shown in Fig.~\ref{scene-variety}. 3D complexity in our dataset like crowded rooms with densely packed chairs could provide difficulty for range sensors, while darkness, glare, high dynamic range and texture-less walls could be challenging to visual sensors. Several of the sequences include moving targets like humans. This would test a model's robustness to dynamic environments. Due to the need for ground truth from the Vicon tracking system, UAV sequences are recorded in the Vicon room only. All sequences collected from the above platforms are recorded with their 6-DoF movements.
Sequences are named after their characteristics as \emph{[Platform]\_[Scene]\_[TrajectoryShape]\_[LightingCondition]}, examples of which can be seen in Table \ref{ate_table}. For platforms, \emph{H}, \emph{G} and \emph{A} denote handheld, UGV and UAV platforms respectively. For scenes, we divide them into 7 categories: (1)\emph{vicon} denotes a single room that the platform's motion is confined to, (2)\emph{corridor} means the platform go through narrow long corridors, (3)\emph{glassy} denotes environments with large amounts of reflective surfaces, (4)\emph{atrium} denotes lightly furnished larger spaces, (5)\emph{hallway} denotes large unfurnished spaces, while (6)\emph{canteen} and (7)\emph{office} are heavily furnished spaces. For trajectories, \emph{linear} means long forward-moving trajectories, while \emph{circular} and \emph{eight} denote looped O-shape or 8-shape trajectories with plenty of loop-closure opportunities. For lighting conditions, \emph{bright} denotes normal daylight, \emph{dim} denotes the sequence includes under-exposed RGB frames, and \emph{dark} means the sequence includes pitch-black RGB frames.
\subsubsection{Motion Characteristics} For fully evaluating odometry algorithms, we included a variety of motion patterns when collecting data:
\emph{drastic turns}: The trajectory length ranges from 10 meters to 300 meters. Drastic turns as large as 180 degrees are included in many of the trajectories on all three platforms. Many of the turns make the platform face featureless walls.
\emph{human-controlled operation}: UAV motion is controlled by a human operator with stabilization assistance from the Vicon tracking system. Compared to flight fully controlled by Vicon, control inputs from the human operator are more complex and mimic a genuine trajectory performed by an exploring autonomous agent.
\subsection{Calibration}
To make the dataset applicable to various processing techniques, we provide extrinsic parameters of all sensors and intrinsic parameters of all cameras. Most extrinsic calibrations are done with RGB camera on Realsense D435 as center. A detailed record of coordinate frames and extrinsic parameters for all sensors are provided alongside the dataset.
\subsubsection{Calibrate Thermal Camera vs. RGB Camera} For extrinsic parameters between thermal camera and RGB camera, we need a calibration target that presents good contrast in RGB as well as thermal spectrum. To achieve this, we implemented the masking method of \cite{vidas2012mask}, covering a hot-running laptop with an acrylic mask with hollowed windows.
\begin{figure}[!t]
\centering
\subfloat[Original thermal image]{\includegraphics[width=1.5in]{fig/thermal-cali-1.png}%
\label{thermal-cali-original}}
\hfil
\subfloat[Undistorted thermal image]{\includegraphics[width=1.5in]{fig/thermal-cali-2.png}%
\label{thermal-cali-undistort}}
\caption{Thermal masks used to calibrate thermal cameras and their calibration results.}
\label{thermal-cali}
\end{figure}
\subsubsection{Calibrate LiDAR vs. RGB Camera} We implemented the LiDAR vs. RGB camera calibration by Geiger et al.\cite{geiger2012automatic}, using a chessboard patterned corner.
\subsubsection{Calibrate mmWave Radar vs. LiDAR} Due to strong reflection of mmWave signal by metal materials, We use a metallic corner reflector as target to calibrate extrinsic parameters between mmWave radar and LiDAR. Starting from hand measurements, we tune the extrinsic parameter between mmWave radar and LiDAR by finding the best alignment between the corner reflector's signal from the two sensors.
\subsubsection{Calibrate IMU vs. RGB Camera} Extrinsic parameters between IMU and RGB camera are obtained using kalibr tools\cite{rehder2016extending} with AprilTag target.
\subsection{Ground Truth}
For sequences that are collected in large-scale spaces with long trajectories, it's unrealistic to use motion tracking systems (e.g., Vicon) to collect ground truth motions. We follow the practices of \cite{cortes2018advio, doer2021yaw} to use more accurate odometry modalities as pseudo ground truth for modalities with much less accuracy.
For the UGV platform, we used wheel odometry as the pseudo ground truth. For handheld platform, we use trajectories generated by the SOTA LiDAR odometry, ALOAM \cite{zhang2014loam}, as pseudo ground truth. For the UAV platform, whose trajectories are confined to the Vicon lab, the ground truth comes from the Vicon tracking system, which provides mm-level accuracy 6-DoF poses in 100~Hz.
\begin{figure*}[!t]
\centering
\includegraphics[width=5.5in]{fig/rio-all.png}
\caption{Sample Trajectories of TIO and RIO results on UAV, UGV and Handheld platform. Dot denotes the starting point.}
\label{bench}
\end{figure*}
\section{Experiments}
Since the LWIR thermal and mmWave radar spectrum are our particular contribution, we will focus on evaluating our novel thermal and radar data for odometry purposes. Since there are few open-source models involving the fusion of more than one spectrum, we will be implementing radar odometry (RO), radar-inertial odometry (RIO) and thermal-inertial odometry (TIO) methods to estimate 6-DoF trajectories. To demonstrate the dataset in different use-cases, odometry using radar and thermal will each be implemented using a learning-based method and a none-learning based method.
We use two common metrics, Absolute Trajectory Error (ATE)\cite{geiger2012we} and Relative Pose Error (RPE) \cite{6385773}, to evaluate 6-DoF odometry on our dataset. We perform a train/test split on the dataset that ensures the scenes are evenly split. Along with our dataset, we provide data pre-processing, model training, and model testing codes.
\subsection{Odometry with mmWave Radar}
MilliEgo \cite{lu2020milliego} is a first-of-its-kind deep learning framework for radar-inertial odometry. It uses Convolutional Neural Network (CNN) and Recurrent Neural Network (RNN) to encode radar and IMU streams respectively, after which the 2 encoded streams are fused together using mixed-attention mechanism. The fused sensor features are temporally processed by long short-term memory (LSTM) and regressed by fully-connected (FC) layers.
We trained the network using its open-sourced configuration on our handheld, UGV and UAV platforms, generating pose predictions for each platform at 4~Hz (UGV), 5~Hz (UAV) and 6.7~Hz (handheld). The results shown in Fig. \ref{bench} and Table \ref{ate_table} demonstrate that milliEgo is able to generate good trajectories, with acceptable drift even in long trajectories. As expected, milliEgo performs better on the UGV platform than handheld and UAV platforms with the wide-fov 3-radar array on the UGV compared to only 1 radar on the other platforms.
For the non-learning based method, we implemented a Radar-ICP model, which uses iterative closest point (ICP)\cite{rusinkiewicz2001efficient} to register radar frames at fixed intervals. Adjacent point cloud frames are overlaid to reduce noise. As can be seen in Table \ref{ate_table}, the trajectories proved difficult for Radar-ICP to estimate. The high noise level in the mmWave radar's data can explain the large error in Radar-ICP, which fails to match point cloud frames with many points flickering on and off. Like milliEgo, Radar-ICP also shows better results with 3-radar setup than the 1-radar handheld and UAV platform.
\begin{table*}[!t]
\centering
\captionsetup{justification=centering,margin=2cm}
\caption{Performance of Different Methods on Test Sequences: Mean Absolute Trajectory Errors (ATE) [m] and Mean Relative Pose Error (RPE). RPE shown below is in the format of Translation[m]/Rotation[deg].}
\label{ate_table}
\begin{tabular}{lc|cc|cc|cc}
\toprule
& & \multicolumn{2}{c}{milliEgo\cite{lu2020milliego}} & \multicolumn{2}{c}{DeepTIO\cite{saputra2020deeptio}} & \multicolumn{2}{c}{ICP\cite{rusinkiewicz2001efficient}} \\
Test Sequence & Length[m] & ATE & RPE & ATE & RPE & ATE & RPE\\
\midrule
\multicolumn{2}{l}{Handheld} & \\
\midrule
H\_corridor\_circle\_bright\_5 & 141.5 & 8.72 & 0.071/2.44 & 8.29 & 0.087/4.18 & 15.82 & 0.338/13.56 \\
H\_vicon\_circle\_dark\_3 & 58.3 & 2.49 & 0.056/3.20 & 2.35 & 0.067/5.26 & 5.61 & 0.296/13.03 \\
H\_vicon\_circle\_dark\_4 & 43.1 & 1.24 & 0.064/2.88 & 5.55 & 0.072/5.13 & 3.14 & 0.278/12.69 \\
H\_viconcorridor\_circle\_bright\_3 & 104.2 & 2.70 & 0.062/2.68 & 3.36 & 0.076/4.51 & 12.45 & 0.271/12.73 \\
H\_office\_circle\_bright\_2 & 76.0 & 2.29 & 0.061/3.77 & 5.35 & 0.086/5.83 & 7.33 & 0.345/17.06 \\
H\_atrium\_linear\_bright\_3 & 146.6 & 4.37 & 0.078/2.95 & 5.54 & 0.101/4.58 & 13.09 & 0.388/11.11 \\
H\_multifloor\_linear\_1 & 318.0 & 7.91 & 0.096/3.46 & 22.54 & 0.114/5.04 & 18.98 & 0.368/11.24 \\
H\_hallway\_circle\_bright\_2 & 202.2 & 16.00 & 0.071/4.03 & 13.39 & 0.083/6.26 & 24.81 & 0.317/15.49 \\
H\_glassy\_circle\_bright\_2 & 73.6 & 7.18 & 0.077/2.33 & 3.58 & 0.082/3.52 & 8.27 & 0.314/9.96 \\
H\_canteen\_circle\_bright\_1 & 153.4 & 4.98 & 0.080/3.88 & 5.34 & 0.090/5.55 & 10.32 & 0.395/15.77 \\
H\_atrium\_circle\_bright\_1 & 146.8 & 7.47 & 0.074/3.05 & 7.24 & 0.084/4.68 & 7.88 & 0.400/15.03 \\
\midrule
\multicolumn{2}{l}{UGV} & \\
\midrule
G\_vicon\_linear\_bright\_3 & 12.0 & 1.40 & 0.027/2.26 & 0.49 & 0.013/1.39 & 1.59 & 0.108/4.21 \\
G\_vicon\_eight\_bright\_1 & 24.6 & 0.54 & 0.022/2.99 & 0.46 & 0.014/1.77 & 1.40 & 0.119/4.83 \\
G\_vicon\_circle\_bright\_6 & 16.8 & 0.47 & 0.026/3.56 & 0.50 & 0.016/1.89 & 1.95 & 0.116/4.48 \\
G\_stairwell\_linear\_bright\_1 & 62.5 & 1.90 & 0.017/1.50 & 1.24 & 0.014/0.87 & 7.71 & 0.091/3.18 \\
G\_atrium\_linear\_bright\_2 & 91.6 & 2.62 & 0.018/1.82 & 3.23 & 0.015/0.97 & 29.68 & 0.100/3.73 \\
G\_canteen\_circle\_bright\_1 & 71.0 & 1.95 & 0.019/2.19 & 2.86 & 0.017/1.27 & 5.58 & 0.102/4.16 \\
G\_hallway\_linear\_bright\_1 & 78.7 & 2.19 & 0.019/1.58 & 4.20 & 0.015/0.95 & 10.01 & 0.096/3.75 \\
G\_hallway\_linear\_bright\_3 & 66.0 & 2.07 & 0.019/1.67 & 3.98 & 0.014/0.95 & 6.93 & 0.101/3.72 \\
G\_corridor\_linear\_bright\_11 & 40.2 & 2.38 & 0.017/1.83 & 1.50 & 0.016/1.06 & 9.39 & 0.111/3.88 \\
G\_corridor\_linear\_bright\_13 & 25.1 & 1.32 & 0.018/1.32 & 1.35 & 0.013/0.78 & 3.44 & 0.092/3.55 \\
G\_vicon\_eight\_bright\_5 & 61.3 & 0.80 & 0.019/2.44 & 0.56 & 0.015/1.35 & 2.26 & 0.112/6.02 \\
G\_corridor\_linear\_bright\_18 & 39.3 & 0.77 & 0.018/1.00 & 2.28 & 0.015/0.56 & 3.11 & 0.098/3.33 \\
\midrule
\multicolumn{2}{l}{UAV} & \\
\midrule
A\_vicon2\_circle\_bright\_6 & 5.55 & 1.27 & 0.023/0.75 & 0.62 & 0.020/0.96 & 2.51 & 0.451/13.30 \\
A\_vicon2\_circle\_bright\_7 & 11.27 & 0.45 & 0.024/1.41 & 0.34 & 0.022/1.78 & 3.68 & 0.508/18.54 \\
A\_vicon2\_circle\_bright\_8 & 10.75 & 1.33 & 0.032/1.47 & 0.45 & 0.028/1.89 & 6.49 & 0.494/16.75 \\
A\_vicon2\_circle\_bright\_9 & 10.98 & 1.13 & 0.027/1.11 & 0.55 & 0.025/1.52 & 3.32 & 0.510/15.85 \\
A\_vicon2\_circle\_bright\_10 & 11.14 & 0.76 & 0.025/1.20 & 0.44 & 0.023/1.62 & 5.72 & 0.737/22.45 \\
\bottomrule
\end{tabular}
\end{table*}
\subsection{Odometry with Thermal Camera}
Existing Visual-Inertial Odometry (VIO) models can be converted to a TIO since they share the same input format.
Thus, for our non-learning TIO model, we adapted the popular visual-inertial state estimation framework VINS-Mono \cite{qin2018vins} to TINS-Mono by taking the thermal image as input. Different from the random noise pattern of RGB sensors, thermal sensors accumulate noise on fixed pixel locations (fixed-pattern noise) for a short duration, in which those noises will be typically suppressed through the camera's Non-Uniformity Correction (NUC), but could still be severe enough to affect models.
\cite{saputra2021graph}. Feature extraction techniques used by TINS-Mono could mistake those fixed noise artifacts as visual features. To mitigate this delusion, TINS-Mono requires the thermal images to go through a series of pre-processing including contrast adjustments, denoising and sharpening. As shown in Fig. \ref{vins}, the TINS-Mono is able to stably track features in most scenarios after pre-processing, but the shortage and inconsistency in visual features makes the model underestimate translation motion, and it would still understandably lose track in the presence of thermally-flat images.
\begin{figure}[!t]
\centering
\subfloat[]{\includegraphics[width=1.05in,valign=t]{fig/vins-1.png}%
\label{vins-before}}
\hfil
\subfloat[]{\includegraphics[width=1.05in,valign=t]{fig/vins-2.png}%
\label{vins-after}}
\hfil
\subfloat{\includegraphics[width=1.2in,valign=t]{fig/vins-3.pdf}%
\label{vins-track}}
\caption{TINS-Mono tracking and trajectory. (a) and (b) shows TINS-Mono feature tracking before and after our pre-processing. Red dots are features successfully matched with previous frames, while blue dots are failed matches. Noise artifacts are falsely extracted as features in (a). The trajectory shows TINS-Mono severely underestimates translation motion.}
\label{vins}
\end{figure}
DeepTIO \cite{saputra2020deeptio} is a deep learning thermal-inertial odometry method aimed at alleviating the lack of visual features in thermal images. It benefits from a hallucination network that aims to hallucinate upon the thermal images such that it can produce similar visual features as the ones extracted from RGB cameras. In a word, it is equivalent to fusing together 3 modalities: (hallucinated) visual, thermal, and IMU.
We trained the network on handheld, UAV and UGV platform with exactly the same configuration, giving out pose predictions at a rate of 6~Hz (on handheld and UGV) and 4.3~Hz (on UAV). Before training, a pre-trained VINet \cite{clark2017vinet} was used to first generate the visual features from the RGB stream. In the first stage of training, the hallucination network was trained to generate similar features from thermal stream. In the second stage, the rest of the network was trained while the hallucination layers were frozen. The estimated trajectories for DeepTIO are shown in Fig.\ref{bench} and the quantitative results are presented in Table. \ref{ate_table}. Notably, DeepTIO doesn't show noticeable drop in performance in pitch-dark sequences where Visual-Inertial models would completely fail. The better performance of DeepTIO on the UGV than on the handheld may be a result of the unstable motion and faster speed of the handheld devices, making feature tracking slightly more challenging. A customized and tailored network configuration might be required to generate a better trajectory in this challenging scenario.
To summarize our experiments, the evaluated methods show that sensible odometry results can be generated from our dataset using LWIR and mmWave spectrum, but their performance still leaves much to be desired on our challenging dataset. With the two non-learning methods, Radar-ICP and TINS-Mono, we demonstrated the common challenges of the LWIR thermal and mmWave modalities: the high level of noise and the sparsity of features. Comparing results of non-learning and learning based methods, it appears learning based methods consistently outperform non-learning based one across three platforms, while also avoiding manual tuning of model parameters. Platform-wise, handheld and UAV platforms prove to be more challenging than UGV due to their complex 6-DoF movements. We hope that our diverse and challenging dataset would facilitate multi-modal and multi-platform odometry research in the future.
\section{Conclusion}
This paper presents the OdomBeyondVision dataset. By including the traditional navigation sensors and the emerging single-chip mmWave radar and LWIR cameras, our odometry dataset features a wide sensor coverage across both visible and invisible spectrums.
We collected the odometry data with multiple different mobile platforms in a variety of indoor scenes and illumination, aiming to bridge existing gaps and further diversify odometry datasets in the community.
We demonstrated the use of the dataset in exemplar odometry systems and released their implementations for plug-and-play usage. Owing to the increasing interest in localization and navigation research, our plan in the near future is to provide better dataset services with more benchmarking results.
| {'timestamp': '2022-06-06T02:14:59', 'yymm': '2206', 'arxiv_id': '2206.01589', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01589'} | arxiv |
\section{Introduction}
Learning graph representations for relational data structures has been gaining increasing attention in the machine learning community~\cite{chami2021ml,hamilton2017representation}. A graph is able to model real-world, complex systems by representing entities as nodes and interactions between them as edges.
Since the information in graphs is often incomplete, e.g., missing node attributes or edges, relevant graph-related tasks for attaining new knowledge include node classification and link prediction.
A variety of graph neural network (GNN) models have been developed~\cite{kipf2016semi, velivckovic2017graph, klicpera2019predict}, which learn node and edge embeddings in a low-dimensional vector space. Subsequently, these embeddings can be used to solve downstream tasks like node classification.
Usually, the focus here lies on maximizing the accuracy -- the proportion of nodes that are classified correctly.
GNNs achieve good performance with respect to accuracy but are also black boxes and lack interpretability.
Most machine learning models output confidence scores associated with the predictions, and the concept of calibration captures the idea that the score should reflect the ground-truth probability of the prediction's correctness. For example, if 100 instances have a score of 0.6 for a specific class $k$, then 60 instances are expected to actually be of class $k$.
A real-world application is autonomous driving, where the model should not only be aware that the object in front of the car is more likely to be a plastic bag than a pedestrian but also know how much more likely it is. A score distribution of 0.99 for plastic bag and 0.01 for pedestrian or 0.51 for plastic bag and 0.49 for pedestrian could have a huge influence on the next action of the car.
Generally, calibrated scores lead to a better interpretation of the results and increase the trustworthiness of machine learning models, which is especially important in safety-critical domains.
The calibration of deep neural networks has been addressed in several works~\cite{guo2017calibration,thulasidasan2019mixup,tomani2021trustworthy,muller2019does}. The calibration of GNNs, however, has not been sufficiently explored yet, and existing calibration methods do not exploit the graph structure. Due to the different architectures of GNNs compared to neural networks, GNNs might exhibit different calibration characteristics.
In this work, we are interested in the following research questions:
\textbf{R1.}
How are GNNs calibrated for the node classification task, and are existing calibration methods sufficient to calibrate GNNs?
\textbf{R2.}
How do model capacity (width and depth) and graph density influence the calibration?
\textbf{R3.}
Can a calibration error term be added to the loss function in a straightforward way to improve the calibration without hurting the accuracy?
\textbf{R4.}
Can the incorporation of topological information improve calibration?
To better understand the calibration properties of GNNs, we conduct an empirical analysis of several GNN models in a node classification setting.
Based on our experimental finding that the nodes in the graph express different levels of over- and underconfidence, we propose a topology-aware calibration method that takes the neighboring nodes into account.
Our contributions are summarized as follows:
\begin{itemize}
\item We inspect the calibration of five representative GNN models on three benchmark citation datasets for node classification.
\item We analyze the influence of model capacity, graph density, and a new loss function on the calibration of GNNs.
\item We propose a calibration method that takes the graph topology into account and yields improved calibration compared to state-of-the-art post-processing calibration methods.
\end{itemize}
In Section~\ref{sec:background}, we define the necessary concepts and summarize related work. The existing GNNs and calibration methods used in this work are also described briefly. An experimental study on the calibration of GNNs is presented in Section~\ref{sec:experiments} ($\rightarrow$ \textbf{R1}, \textbf{R2}, \textbf{R3}). In Section~\ref{sec:ratio} ($\rightarrow$ \textbf{R1}, \textbf{R4}), we propose a topology-aware calibration method and show experimental results compared to state-of-the-art calibration baselines. The results are discussed in Section~\ref{sec:discussion}.
\section{Background}
\label{sec:background}
\subsection{Definitions}
\subsubsection{Node classification on graphs}
An undirected graph is defined as $G = (\mathcal{V} ,\mathcal{E})$, where $\mathcal{V}$ is the set of nodes and $\mathcal{E}$ the set of edges. An edge $e = \{i,j\} \in \mathcal{E}$ connects the two nodes $i$ and $j$ in the graph.
The information about the edges can be encoded in an adjacency matrix $\mathbf{A} \in \left \{0, 1\right \}^{\left|\mathcal{V}\right| \times \left|\mathcal{V}\right|}$. With $\mathbf{A}_{ij}$ being the entry in the $i$-th row and $j$-th column of $\mathbf{A}$, we define $\mathbf{A}_{ij} = 1$ if $\{i,j\} \in \mathcal{E}$ and $\mathbf{A}_{ij} = 0$ otherwise\footnote{We identify nodes and indices to ease the notation.}. Moreover, we define $\mathcal{N}(i)$ as the set of neighbors of node $i$. For attributed graphs, where each node $i$ is associated with a $d$-dimensional feature vector $\mathbf{X}_i \in \mathbb{R}^d$, we denote the feature matrix by $\mathbf{X} \in \mathbb{R}^{|\mathcal{V}| \times d}$.
The goal of the node classification task is to assign each node $i \in \mathcal{V}$ a class label $\hat{y}_i \in \mathcal{K} := \{1, 2, \dots, K\}$, where $K$ stands for the total number of classes.
\subsubsection{Calibration}
Let $\mathbf{H}_i \in \mathbb{R}^h$ denote the node embedding and $y_i \in \mathcal{K}$ the ground-truth label of sample (or node) $i\in \mathcal{V}$.
Let $g: \mathbb{R}^h \rightarrow [0,1]^K$ be a function that takes $\mathbf{H}_i$ as input and outputs a probability vector $g(\mathbf{H}_i)$, where $g(\mathbf{H}_i)_k$ represents the $k$-th element.
The predicted class label for sample $i$ is given by
$\hat{y}_i =\mathop{\arg\max}_{k \in \mathcal{K}}g(\mathbf{H}_i)_k$, where $\hat{p}_i =\mathop{\max}_{k \in \mathcal{K}}g(\mathbf{H}_i)_k$ is called the corresponding confidence score for $\hat{y}_i$.
Perfect calibration is defined as
$
\mathbb{P}(\hat{y}_i=y_i \mid \hat{p}_i=p)=p
$
for all $p \in [0,1]$ and any sample $i$~\cite{guo2017calibration}.
A reliability diagram~\cite{murphy1977reliability} plots accuracy against confidence to visualize the calibration of the model (see Fig. \ref{fig:rds}).
More formally, the samples are grouped into $M \in \mathbb{N}$ equally-spaced interval bins according to their confidences $\hat{p}_i$. For each bin $B_m$, $m \in \{1,2, \dots, M\}$, the accuracy and average confidence are calculated according to
\begin{align}
\mathrm{acc}(B_m) &= \frac{1}{|B_m|}\sum_{i \in B_m}\mathbbm{1}[\hat{y}_i=y_i]
\quad
\mathrm{and} \\
\quad
\mathrm{conf}(B_m) &= \frac{1}{|B_m|}\sum_{i \in B_m}\hat{p}_i\;,
\end{align}
respectively, where $|B_m|$ denotes the number of samples in bin $B_m$ and $\mathbbm{1}$ the indicator function. In case of perfect calibration, the equation $\mathrm{acc}(B_m) = \mathrm{conf}(B_m)$ holds for all $m$.
Reliability diagrams also present a way to identify if the model is over- or underconfident.
If the bars are above the diagonal line, it implies that the accuracy is higher than the average confidence, and the model is called underconfident. If the bars are below the diagonal, the model is overconfident.
The expected calibration error (ECE)~\cite{naeini2015obtaining} measures the miscalibration by averaging the gaps in the reliability diagram and is given by
\begin{equation}
\sum_{m=1}^{M}\frac{|B_m|}{N}|\mathrm{acc}(B_m)-\mathrm{conf}(B_m)|\;,
\label{eq:ece}
\end{equation}
where $N$ is the total number of samples.
The marginal ECE (MECE) approximates the marginal calibration error~\cite{kumar2019verified}, which takes all classes into account. For each bin and every class $k$, it compares the average confidence of samples for class $k$ to the proportion of samples that has as ground-truth label class $k$. The MECE is defined as
\begin{equation}
\sum_{k=1}^K w_k \sum_{m=1}^{M} \frac{1}{N}\left|\sum_{i \in B_m}\mathbbm{1}[y_i=k] - \sum_{i \in B_m}g(\mathbf{H}_i)_k\right|\;,
\label{eq:mece}
\end{equation}
where $w_k$ is a class-dependent weight factor, which is set to $1/K$ if all classes are equally important.
\begin{figure*}[t]
\centering
\subfigure{
\includegraphics[width=0.235\textwidth]{figures/rd/gcn_Cora_rd.png}}
\subfigure{
\includegraphics[width=0.235\textwidth]{figures/ch/gcn_Cora_ch.png}}
\subfigure{
\includegraphics[width=0.235\textwidth]{figures/rd/gcn_Cora_ts_rd.png}}
\subfigure{
\includegraphics[width=0.235\textwidth]{figures/ch/gcn_Cora_ts_ch.png}}
\caption{Reliability diagrams and corresponding confidence histograms for GCN on Cora. The two left plots show the results before calibration, while the two right plots show the results after calibration with temperature scaling. The diagonal line indicates perfect calibration.}
\label{fig:rds}
\end{figure*}
\subsection{Related work}
Guo et al.~\cite{guo2017calibration} showed that modern neural networks are miscalibrated and tend to be overconfident, i.\,e., the confidence scores are higher than the proportions of correct predictions. They proposed temperature scaling, a single-parameter variant of Platt scaling~\cite{platt1999probabilistic}, to calibrate the results. Several other methods were introduced to improve the calibration of deep neural networks (e.\,g., mixup training~\cite{thulasidasan2019mixup} and FALCON~\cite{tomani2021trustworthy}).
Methods that improve calibration by preventing overconfidence include label smoothing~\cite{muller2019does} and focal loss~\cite{mukhoti2020calibrating, charoenphakdee2021focal}.
In GNNs, calibration issues have only been studied recently.
A first evaluation of GNNs was done by Teixeira et al.~\cite{teixeira2019graph}, who performed experiments on multiple node classification datasets and concluded that GNNs are miscalibrated and existing calibration methods are not always able to improve the calibration to the desired extent.
\subsection{Methods}
\subsubsection{Graph neural networks}
Given an adjacency matrix $\mathbf{A}$ and a feature matrix $\mathbf{X}$, the idea of all GNNs is to learn node embeddings $\mathbf{H} \in \mathbb{R}^{|\mathcal{V}| \times h}$. The embedding for node $i$ is denoted by $\mathbf{H}_i \in \mathbb{R}^h$, which can be fed to a task-specific decoder $g$. For example, since we are concerned with node classification, we use a single-layer perceptron with softmax activation as decoder.
For our experiments, we select the widely used models graph convolutional network (GCN)~\cite{kipf2016semi}, graph attention network (GAT)~\cite{velivckovic2017graph}, and simple graph convolution (SGC)~\cite{wu2019simplifying}. Further, we consider graph filter neural network (gfNN)~\cite{nt2019revisiting}, a straightforward extension of SGC, and approximate personalized propagation of neural predictions (APPNP)~\cite{klicpera2019predict}, a model with state-of-the-art performance.
\textit{GCN} applies a normalized adjacency matrix with self-loops $\tilde{\mathbf{A}} = \hat{\mathbf{D}}^{-\frac{1}{2}} (\mathbf{A}+\mathbf{I}) \hat{\mathbf{D}}^{-\frac{1}{2}}$, where $\mathbf{I}$ is the identity matrix and $\hat{\mathbf{D}}$ the degree matrix of $\mathbf{A}+\mathbf{I}$. Concretely, the hidden layer of a GCN is formed according to
$
\mathbf{H}^{(l+1)}
= \sigma(\tilde{\mathbf{A}}\mathbf{H}^{(l)}\mathbf{W}^{(l)}),
$
where ${\mathbf{W}^{(l)}}$ is a trainable weight matrix, $\sigma$ an activation function, and $\mathbf{H}^{(0)} := \mathbf{X}$. GCN aggregates information from a node's neighbors by computing the normalized sum of adjacent node embeddings.
\textit{GAT} differs from GCN in the neighbor aggregation function by introducing an attention mechanism that scales the importance of neighbors when summing over their embeddings.
\iffalse
For each node $i$ and neighbor $j \in \mathcal{N}(i)$, the attention $\alpha_{ij}$ is computed as
{\fontsize{9}{10}
\begin{equation*}
\alpha_{ij} = \frac{\exp(\mathrm{LeakyReLU}(\mathbf{a}^{T}[\mathbf{W}\mathbf{h}_{i};\mathbf{W}\mathbf{h}_{j}])}{\sum_{\tilde{j} \in \mathcal{N}(i)} \exp(\mathrm{LeakyReLU}(\mathbf{a}^{T}[\mathbf{W}\mathbf{h}_{i};\mathbf{W}\mathbf{h}_{\tilde{j}}]))}
\label{2.9}
\end{equation*}}
where $\mathbf{a}$ is a trainable vector, $\mathbf{W}$ a trainable weight matrix, $\mathbf{h}_i$ the hidden embedding of node $i$, and $[\cdot\,;\cdot]$ the concatenation operation.
\fi
\textit{SGC} is a GCN without nonlinear activation functions between the layers, resulting from the authors' conjecture that the good performance of GCNs comes from the aggregation of local neighborhood information and not from the application of nonlinear feature maps.
\textit{gfNN} extends SGC with a nonlinear layer $\sigma$ so that the node embeddings for layer $l$ are obtained from
$
\mathbf{H}^{(l)} = \sigma(\tilde{\mathbf{A}}^{l}\mathbf{X}\mathbf{W}),
$
where $\mathbf{W}$ is a trainable weight matrix.
\textit{APPNP} is based on the personalized PageRank (PPR) algorithm~\cite{page1998rank}. The node embeddings in layer $l+1$ are calculated via
$
\mathbf{H}^{(l+1)} = (1-\alpha)\tilde{\mathbf{A}}\mathbf{H}^{(l)} + \alpha \mathbf{H}^{(0)},
$
where $\alpha \in (0,1]$ is a hyperparameter and $\mathbf{H}^{(0)} := f(\mathbf{X})$, with $f$ being a trainable neural network.
\subsubsection{Calibration methods}
We consider the classical post-processing methods {histogram binning} \cite{zadrozny2001obtaining}, {isotonic regression}~\cite{zadrozny2002transforming}, and Bayesian binning into quantiles (BBQ)~\cite{naeini2015obtaining}, which is a refinement of histogram binning. Further, we include temperature scaling ~\cite{guo2017calibration} as a multiclass calibration method and {Meta-Cal}~\cite{ma2021meta}, a recently introduced approach with state-of-the-art performance.
\textit{Histogram binning} divides the confidence scores $\hat{p}_i$ into $M$ bins and assigns a new score $\hat{q}_m$ to each bin to represent the calibrated confidences. The scores $\hat{q}_m$ are learned by minimizing
$\sum_{m=1}^{M} \sum_{i \in B_m}(\hat{q}_m - y_i)^2$.
\textit{Isotonic regression} learns a piecewise constant function $f$
by minimizing $\sum_{m=1}^M \sum_{i \in B_m}(f(\hat{p}_i)-y_i)^2$. It is a generalization of histogram binning where the bin boundaries and scores are jointly optimized.
\textit{BBQ} extends histogram binning and learns a distribution $\mathbb{P}(\hat{q}_i \mid \hat{p}_i, \mathcal{D}_{\mathrm{val}})$ by marginalizing out all possible binnings, where $\mathcal{D}_{\mathrm{val}}$ is the validation set.
\textit{Temperature scaling} is a single-parameter extension of Platt scaling~\cite{platt1999probabilistic} for multiple classes. Given the output logit vector $\mathbf{z}$ before the softmax activation, a rescaling $\mathbf{z}/T$ depending on a temperature $T > 0$ is applied.
\textit{Meta-Cal} combines temperature scaling as a base model with a bipartite ranking model to weaken the limitation of accuracy-preserving calibration methods. By investigating two practical constraints (miscoverage rate control and coverage accuracy control), the goal is to improve calibration depending on the bipartite ranking while controlling the accuracy.
\section{Experimental study}
\label{sec:experiments}
\subsection{Setup}
\noindent \textbf{Experiments}
We first inspect the calibration of GNN models on benchmark citation datasets, where we take the best hyperparameter and training settings from the corresponding original papers.
Then, we empirically analyze the influence of model capacity (width and depth) on calibration.
It has been observed that stacking too many GCN layers drastically worsens the performance, which is partly attributed to a phenomenon called oversmoothing~\cite{li2018deeper}. Oversmoothing happens when repeated neighbor aggregation leads to similar node embeddings in the graph, and various methods have been proposed to tackle this problem~\cite{klicpera2019predict,xu2018representation}. In the following, we investigate if increasing model depth also affects calibration.
One of the core mechanisms of GNNs is the message aggregation from neighboring nodes.
We examine how graph density, i.\,e., the ratio of the number of edges in the graph to the number of maximum possible edges, influences the calibration performance.
Finally, we also test a new loss function \eqref{eq:loss}
that combines the standard cross-entropy loss $L_{\mathrm{ce}}$ with an ECE-inspired term $L_{\mathrm{cal}}$ for optimizing the calibration. We define $L_{\mathrm{cal}}$ as the cross entropy between the confidence of the sample and the accuracy of its corresponding bin, where the idea is that the confidence should stay close to the accuracy.
Given the original cross-entropy loss $L_{\mathrm{ce}}$, we define the new loss as
\begin{table}[t]
\setlength{\tabcolsep}{0.5em}
\setlength{\extrarowheight}{0.1em}
\caption{Dataset statistics.}
\centering
\begin{tabular}{c|cccccc}
\hline
Dataset & $K$ & $d$ & $|\mathcal{V}|$ & $|\mathcal{E}|$ & Label rate \\
\hline
Cora & 7 & 1,433 & 2,708 & 5,429 & 0.052 \\
Citeseer & 6 & 3,703 & 3,327 & 4,732 & 0.036 \\
Pubmed & 3 & 500 & 19,717 & 44,338 & 0.003 \\
\hline
\end{tabular}
\label{tab:statistics}
\end{table}
\begin{align}
\label{eq:loss}
L &= \alpha L_{\mathrm{ce}} + (1- \alpha) L_{\mathrm{cal}}\quad \mathrm{with}\\
L_{\mathrm{cal}} &=
- \sum_{i=1}^{N}\mathrm{acc}(B_{m}(i))\cdot \log(\hat{p}_i)\;,
\end{align}
where $\alpha \in (0,1)$ and $B_{m}(i)$ denotes the bin that sample $i$ belongs to.
For the experiments on width, depth, graph density, and the new loss function, we focus on GCN and GAT, two of the basic and most widely used GNN models.
\noindent \textbf{Datasets}
Cora, Citeseer, and Pubmed\footnote{\url{https://github.com/kimiyoung/planetoid}} are three commonly used benchmark datasets for node classification.
They are citation networks, where nodes represent scientific publications and edges between pairs of nodes correspond to one publication citing the other. Each node comes with a $d$-dimensional feature vector that indicates the presence of words from a predefined vocabulary. The class label of a node is the topic of the corresponding publication. Similar to previous works~\cite{kipf2016semi,velivckovic2017graph}, we operate under a semi-supervised setting, where only a small amount of labeled data is available during training. The statistics of the datasets are summarized in Table~\ref{tab:statistics}.
\noindent \textbf{Implementation}
The GNN models are implemented using the PyTorch-Geometric library\footnote{\url{https://github.com/pyg-team/pytorch_geometric}}.
The bin number for calculating the ECE and MECE is set to 15.
More information about the hyperparameters and experimental settings can be found in the supplementary material\footnote{Source code and supplementary material available at \url{https://github.com/liu-yushan/calGNN}.}.
\subsection{Results}
\label{sec:gnn_calibration}
\noindent \textbf{Uncalibrated results}
We run all GNNs on the three citation datasets and show the uncalibrated performance with respect to accuracy, ECE, and MECE in Table~\ref{tab:uncal_performance}.
The method APPNP is best on Cora and Pubmed in terms of accuracy (second-best on Citeseer), and it is also best calibrated on the datasets Citeseer and Pubmed. For Cora, gfNN has the lowest ECE and MECE.
All models except for gfNN\footnote{The original paper trains for 50 epochs without early stopping. A different training setting might stabilize the results more.} have stable calibration values with small standard deviations. The worst method with respect to the calibration performance is SGC, which is, apart from the softmax activation for normalization, the only linear model. Adding a nonlinear layer as in gfNN results in better calibration.
Moreover, we find that GAT outperforms GCN in terms of ECE and MECE in two of three datasets.
\begin{table}[t]
\setlength{\tabcolsep}{0.5em}
\setlength{\extrarowheight}{0.1em}
\caption{Uncalibrated performance with respect to accuracy, ECE, and MECE (mean±SD over 100 independent runs). The best results are displayed in bold. }
\label{tab:uncal_performance}
\centering
\begin{tabular}{cc|ccc}
\hline
Dataset & Model & Acc. & ECE & MECE \\ \hline
\multirow{5}{*}{Cora}
& GCN & 81.43±0.60 & 23.51±1.89 &7.01±0.46 \\
& GAT & 83.14±0.39 & 17.26±1.09 & 5.15±0.30 \\
& SGC & 81.19±0.05 &26.03±0.16& 7.78±0.08 \\
& gfNN & 78.73±5.04 & \textbf{6.45±2.44} & \textbf{3.16±1.45} \\
& APPNP & \textbf{83.68±0.36} & 14.90±0.69 & 4.73±0.17 \\
\hline
\multirow{5}{*}{Citeseer}
& GCN & 71.32±0.70 & 21.80±1.21 & 8.57±0.32 \\
& GAT & 70.99±0.60 & 18.92±1.05 & 7.66±0.30 \\
& SGC & \textbf{72.46±0.15}& 53.59±0.14& 19.15±0.00\\
& gfNN & 67.33±6.58 & 15.50±4.47 & 8.40±1.26 \\
& APPNP & 72.10±0.38 & \textbf{11.93±0.80} & \textbf{5.37±0.28} \\
\hline
\multirow{5}{*}{Pubmed}
& GCN & 79.23±0.43 & 10.62±1.28 & 7.29±0.84 \\
& GAT & 79.05±0.38 & 14.37±0.48 & 9.89±0.23 \\
& SGC & 78.72±0.04 & 22.40±0.04 & 14.98±0.02 \\
& gfNN & 77.94±2.32 & 6.04±2.90& 5.23±2.65 \\
& APPNP & \textbf{80.09±0.25} & \textbf{4.38±0.74} & \textbf{3.59±0.41} \\
\hline
\end{tabular}
\end{table}
\begin{figure}[t]
\centering
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/Width/width_gcn_Cora0.png}}
\hspace{-5mm}
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/Width/width_gcn_Citeseer0.png}}
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/Width/width_gat_Cora0.png}}
\hspace{-5mm}
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/Width/width_gat_Citeseer0.png}}
\caption{Varying model width (hidden dimension per layer).}
\label{fig:width}
\end{figure}
\begin{figure}[t]
\centering
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/Depth/depth_gcn_Citeseer0.png}}
\hspace{-5mm}
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/Depth/depth_gcn_Pubmed0.png}}
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/Depth/depth_gat_Citeseer0.png}}
\hspace{-5mm}
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/Depth/depth_gat_Pubmed0.png}}
\caption{Varying depth (number of layers).}
\label{fig:depth}
\end{figure}
\noindent \textbf{Influence of width} We compare the calibration of GCN and GAT for varying model width, i.\,e., the number of hidden dimensions per layer.
While the accuracy basically stays constant, the ECE and MECE
decrease with increasing number of hidden dimensions initially (see Fig.~\ref{fig:width}). When a certain width is reached, the calibration values stagnate or slightly increase again. Generally, wider networks tend to be better calibrated.
\begin{table*}[t]
\setlength{\tabcolsep}{0.5em}
\setlength{\extrarowheight}{0.2em}
\caption{Uncalibrated performance of GCN and GAT under the standard and the new loss function (mean±SD over 10 independent runs). The better results when comparing the two loss functions are underlined.}
\label{tab:cal_loss}
\centering
\begin{tabular}{cc|ccc|ccc}
\hline
Dataset & Model & Acc. ($L_{\mathrm{ce}}$) & ECE ($L_{\mathrm{ce}}$) & MECE ($L_{\mathrm{ce}}$) & Acc. ($L$) & ECE ($L$) & MECE ($L$) \\ \hline
\multirow{2}{*}{Cora}
& GCN & 81.43±0.60 & 23.51±1.89 &7.01±0.46 & \underline{81.81±0.85} & \underline{14.91±2.7} & \underline{4.64±0.56} \\
& GAT & \underline{83.14±0.39} & 17.26±1.09 & 5.15±0.30 & 82.73±0.40 &\underline{5.29±1.31} & \underline{2.41±0.32} \\
\hline
\multirow{2}{*}{Citeseer}
& GCN & 71.32±0.70 & 21.80±1.21 & 8.57±0.32 &\underline{71.67±0.50} & \underline{14.65±0.42} & \underline{6.43±0.26} \\
& GAT & 70.99±0.60 & 18.92±1.05 & 7.66±0.30 &\underline{71.13±0.44} &\underline{9.39±0.97} &\underline{4.58±0.40} \\
\hline
\multirow{2}{*}{Pubmed}
& GCN & \underline{79.23±0.43} & 10.62±1.28 & 7.29±0.84 & 79.00±0.37 &\underline{7.50±0.91} &\underline{5.60±0.73} \\
& GAT & \underline{79.05±0.38} & 14.37±0.48 & 9.89±0.23& 78.88±0.40 & \underline{9.58±0.79} & \underline{6.91±0.63}\\
\hline
\end{tabular}
\end{table*}
\noindent \textbf{Influence of depth} We investigate the influence of model depth, i.\,e., the number of layers, on the calibration performance (see Fig. \ref{fig:depth}). Oversmoothing becomes particularly pronounced when the test accuracy decreases significantly with increasing number of layers.
The ECE first improves when changing from two to three layers, then it increases again until five or six layers. Using an even larger model depth, the ECE eventually decreases again.
\noindent \textbf{Influence of graph density}
For this experiment, we remove different proportions of edges randomly from the dataset, ranging from $0\%$ (original dataset) to $100\%$ (no graph structure at all). The models GCN and GAT only differ in the aggregation mechanism, i.\,e., GAT introduces attention coefficients to weight the importance of neighbors.
The results are shown in Fig.~\ref{fig:density}. Similar to Table~\ref{tab:uncal_performance}, the ECE of GAT is consistently lower than the ECE of GCN on Cora and Citeseer, while on Pubmed, GCN expresses partly better calibration. Generally, the graph density of Pubmed is the lowest. It might be that the attention weights in GAT are beneficial for calibration and especially useful when enough edges exist in the graph.
\noindent \textbf{Influence of new loss function}
Table~\ref{tab:cal_loss} compares the results of the standard cross-entropy loss $L_{\mathrm{ce}}$ and the new loss function $L$ from \eqref{eq:loss}, which contains a calibration error term. The new loss $L$ improves the model calibration in all cases while keeping the accuracy at the same level or even slightly increasing the accuracy.
\noindent \textbf{Underconfidence vs. overconfidence}
Taking the best hyperparameter and training settings from their corresponding publications, all GNNs exhibit underconfidence on all three datasets, i.\,e., the confidence scores are lower than the accuracy of the predictions (see Fig.~\ref{fig:rds} and figures in the supplementary material).
In some cases, however, we find that the model changes from underconfidence to overconfidence if it is trained without early stopping.
\begin{figure}[t]
\centering
\hspace{-8mm}
\subfigure{
\includegraphics[width=0.25\textwidth]{figures/Density/Cora_ECE.png}}\hspace{-6mm}
\subfigure{
\includegraphics[width=0.22\textwidth]{figures/Density/Citeseer_ECE.png}}\hspace{-13mm}
\includegraphics[width=0.22\textwidth]{figures/Density/Pubmed_ECE.png}
\caption{Influence of graph density. The graph density is the ratio of the number of edges in the graph to the number of maximum possible edges.}
\label{fig:density}
\end{figure}
\begin{figure*}[t]
\centering
\subfigure{
\includegraphics[width=0.32\textwidth]{figures/under_over_conf/epochs1.png}}\hspace{3mm}
\subfigure{
\includegraphics[width=0.32\textwidth]{figures/under_over_conf/epochs2.png}}
\caption{Test accuracy, scaled test NLL, and scaled test ECE for GCN on Cora, with a weight decay of $5\text{e-}4$ (left) and $7.5\text{e-}4$ (right).}
\label{fig:under_over_conf_epochs}
\end{figure*}
\begin{figure*}[t]
\centering
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/under_over_conf/rd_100.png}}
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/under_over_conf/rd_200.png}}
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/under_over_conf/rd_300.png}}
\subfigure{
\includegraphics[width=0.23\textwidth]{figures/under_over_conf/rd_400.png}}
\caption{Reliability diagrams for GCN on Cora during the training process. From left to right, the corresponding number of epochs is 100, 200, 300, and $400$. }
\label{fig:under_over_conf_rd}
\end{figure*}
The left plot in Fig.~\ref{fig:under_over_conf_epochs} shows the test accuracy, scaled test negative log-likelihood (NLL), and scaled test ECE for a $4$-layer GCN on Cora during training, with a weight decay set to $5\text{e-}4$.
Around epoch $150$, the NLL and accuracy become stable, while the ECE is still improving. At this point, GCN is underconfident, as shown in the left-most reliability diagram in Fig.~\ref{fig:under_over_conf_rd}.
In the epochs between $200$ and $300$, the ECE gains the best performance when the model changes from underconfidence to overconfidence (see the two diagrams in the middle of Fig.~\ref{fig:under_over_conf_rd}). After epoch $300$, GCN starts to overfit with repect to the ECE, while the NLL and accuracy remain rather unchanged.
During this process, overconfidence aggravates, and the ECE increases to $7.8\%$ in epoch 400, which is displayed in the right-most diagram in Fig. \ref{fig:under_over_conf_rd}.
In summary, GCN first optimizes NLL and accuracy during training, then fits the confidence scores, and eventually starts to overfit regarding the ECE without influencing the NLL and accuracy.
When we slightly increase the weight decay to $7.5\text{e-}4$ (see right plot in Fig.~\ref{fig:under_over_conf_epochs}), the ECE stabilizes after reaching the optimal value, and the values of NLL and accuracy also stay in a smaller range compared to the left plot.
\section{Ratio-binned scaling for calibrating GNNs}
\label{sec:ratio}
\subsection{Same-class-neighbor ratio}
From our experiments, we find that GNN models tend to be underconfident. Even though the overall model exhibits underconfidence, there might be differences depending on node-level properties, which have not been considered before. Especially for graph data, the topology could provide structural information that are useful for calibration. For node classification, the class labels and properties of a node's neighbors have a significant influence on the classification.
We calculate for each node $i$ the same-class-neighbor ratio, i.\,e., the proportion of neighbors that have the same class as node $i$, and develop a new binning scheme that groups samples into bins based on the same-class-neighbor ratio for calibration.
To evaluate the correlation between the same-class-neighbor ratio and the confidence of a model, we calculate the ratio for each node based on the ground-truth labels. In Fig.~\ref{fig:ratio}, we group the nodes into $5$ equally-spaced interval bins according to their ratios.
Employing a trained GNN model, we compute the output of the classifier $g$ for each node and draw the average confidence of the samples in each bin as a blue bar. The gap illustrates the difference between the average confidence and the accuracy in each bin.
We observe that the average confidence increases with the same-class-neighbor ratio, where bins with higher ratios express underconfidence and bins with lower ratios overconfidence.
Consequently, a binning scheme that groups samples depending on their same-class-neighbor ratios would take the graph structure into account and allow for an adaptive calibration depending on the confidence level of each bin.
\subsection{Ratio-binned scaling}
We propose ratio-binned scaling (RBS), a topology-aware method, which first approximates the same-class-neighbor ratio for each sample, then groups the samples into $M$ bins, and finally learns a temperature for each bin to rescale the confidence scores.
In the semi-supervised setting, we only know the labels of a small number of nodes and therefore cannot use the true labels for binning. One natural option is to replace the nodes' ground-truth labels with their confidence scores for estimating the same-class-neighbor ratio. More precisely, we define the estimated ratio for node $i$ as
\begin{equation}
\hat{r}(i) = \frac{1}{\left | \mathcal{N}(i) \right |} \sum_{j \in \mathcal{N}(i)} g(\mathbf{H}_j)_{\hat{y}_i} \quad \in [0,1]\;,
\end{equation}
where $\mathbf{H}_j$ is the node embedding of node $j$, which is learned by a GNN model, and $g$ is the classifier. $g(\mathbf{H}_j)_{\hat{y}_i}$ denotes the confidence score of node $j$ corresponding to the class $\hat{y}_i$ that is predicted for the central node $i$.
\begin{figure*}[t]
\centering
\subfigure{
\includegraphics[width=0.22\textwidth]{figures/ratio/ratio/gcn_Cora.png}}
\subfigure{
\includegraphics[width=0.22\textwidth]{figures/ratio/ratio/gcn_Citeseer.png}}
\subfigure{
\includegraphics[width=0.22\textwidth]{figures/ratio/ratio/gat_Cora.png}}
\subfigure{
\includegraphics[width=0.22\textwidth]{figures/ratio/ratio/gat_Citeseer.png}}
\caption{The nodes are grouped according to their same-class-neighbor ratios. The blue bar represents the average confidence and the gap the difference between average confidence and accuracy in each bin.}
\label{fig:ratio}
\end{figure*}
\begin{table*}[t]
\setlength{\tabcolsep}{0.5em}
\setlength{\extrarowheight}{0.1em}
\caption{Calibrated performance with respect to ECE (mean±SD over 100 independent runs). The best GNN model for each calibration method is underlined. The best calibration method for each GNN model is displayed in bold.}
\label{tab:cal_performance}
\centering
\begin{tabular}{cc|c|cccccc|c}
\hline
Dataset & Model & Uncal. & His. bin. & Iso. reg. & BBQ & Tem. scal. & Meta-Cal & RBS & RRBS\\\hline
\multirow{5}{*}{Cora}
& GCN &23.51±1.89 & 4.50±0.76 & 3.94±0.66 &4.53±0.64 & \textbf{3.82±0.60}
&4.09±0.65 & 3.90±0.61 & 3.10±0.63\\
& GAT & 17.26±1.09 & 4.86±0.62 & 4.04±0.59 & 4.18±0.60 & 3.53±0.66
& \underline {\textbf{3.28±0.65}} & 3.34±0.63 & 2.67±0.54\\
& SGC &26.03±0.16 & 4.38±0.30 & 4.21±0.42 & 4.35±0.21 &4.05±0.11
& 4.02±0.35 & \textbf{3.55±0.07} & 2.57±0.11\\
& gfNN & 6.45±2.44 & \underline {3.80±0.86} & \textbf{3.72±0.78} & 4.15±1.22& 3.74±1.34
& 4.07±1.52 & 3.77±0.96 & 3.39±1.22\\
& APPNP & 14.90±0.69& 4.20±0.62 & \underline{3.43±0.60}& \underline{3.90±0.57} & \underline{3.14±0.50}
& 3.48±0.57 & \underline{\textbf{3.01±0.53}} &2.68±0.44\\
\hline
\multirow{5}{*}{Citeseer}
& GCN & 21.80±1.21 & \underline{4.61±0.82} & \underline{\textbf{4.46±0.93}} & 5.30±1.09 & 4.86±0.76
& 5.04±0.90 & 4.99±0.75 & 4.11±0.88 \\
& GAT & 18.92±1.05 & 5.00±0.73 & 4.90±0.69 & \underline{5.04±0.71} & 5.92±0.58
& 6.08±0.61 & \textbf{4.45±0.73} & 4.71±0.67\\
& SGC & 53.59±0.14 & 7.55±0.23 & 6.93±0.19 & 7.43±0.13 & \underline {4.47±0.19}
& \underline {4.17±0.29} & \textbf{\underline {4.04±0.17}} & 2.97±0.20 \\
& gfNN & 15.50±4.47 & \textbf{4.74±1.00} & 4.92±1.03 & 5.06±1.37 & 5.43±1.27
& 5.45±1.32 &5.19±1.31 & 4.34±1.27\\
& APPNP & 11.93±0.80& 4.75±0.85 & \textbf{4.50±0.67} & 5.10±1.02 & 4.98±0.67
& 5.29±0.67 & 5.08±0.69& 3.97±0.58\\
\hline
\multirow{5}{*}{Pubmed}
& GCN & 10.62±1.28 & 4.69±0.78 & 4.76±0.77 & \underline{4.69±0.74} & 4.27±0.61
& 4.99±1.11 & \textbf{4.16±0.60}& 3.28±0.89 \\
& GAT & 14.37±0.48 & 4.85±0.89 & 4.93±0.78 & 5.70±1.03 & \underline {3.94±0.67}
& 4.45±0.74 & \underline{\textbf{3.61±0.75}} &2.56±0.56\\
& SGC &22.40±0.04 & \underline {4.40±0.29} & \underline{4.29±0.21} & \underline {5.04±0.22} & 4.13±0.12
& 4.64±0.58 &\textbf{4.07±0.17} & 3.01±0.12 \\
& gfNN & 6.04±2.90 & 4.98±1.06 & 5.00±0.83 & 5.15±1.26 & 4.97±1.67
& 6.06±1.95 & \textbf{4.91±1.65} & 3.78±1.03\\
& APPNP & 4.38±0.74 & 4.86±0.75 & 4.72±0.57 & 4.79±0.84 & 3.98±0.59
& \underline{4.34±0.72} & \textbf{3.80±0.60} &2.60±0.47\\
\hline
\end{tabular}
\end{table*}
For the ratio-based binning scheme, let $\{B_m \mid 1 \leq m \leq M\}$ be a set of bins that partitions the interval $[0,1]$ uniformly. After calculating the output for all nodes, each node $i$ is assigned to a bin according to its estimated same-class-neighbor ratio $\hat{r}(i)$, i.\,e., $B_1 = \{i \in \mathcal{V} \mid \hat{r}(i) \in [0, \frac{1}{M}]\}$ and $B_m = \{i \in \mathcal{V} \mid \hat{r}(i) \in (\frac{m-1}{M},\frac{m}{M}]\}$ for $m \in \{2, \dots, M\}$.
Let the output of $g$ be in the form $g(\mathbf{H}_i) = \sigma(\mathbf{Z}_i) \in \mathbb{R}^K$ for node $i$, where $\sigma$ is the softmax function and $\mathbf{Z}_i$ the logits before normalization.
For each bin $B_m$, $m \in \{1, \dots, M\}$, a temperature $T_m > 0$ is learned on the validation dataset.
The calibrated confidence for a test node $j$ is then given by
\begin{equation}
\mathbf{\hat{q}}_j = \sigma (\mathbf{Z}_{j}/T_{m}) \in [0,1]^K\quad \mathrm{if}\; j \in B_m.
\end{equation}
We apply temperature scaling for calibrating the nodes in each bin, but it would also be possible to apply other post-processing calibration methods for obtaining calibrated scores.
\subsection{Results}
Table~\ref{tab:cal_performance} summarizes the calibration performance of all considered post-processing calibration methods and our proposed method RBS in terms of ECE. All methods can improve the calibration of GNN models on Cora and Citeseer. In particular, the obtained ECE for a specific dataset and calibration method is rather similar for all GNNs regardless of the uncalibrated ECE.
On Pubmed, most methods have difficulties improving calibration of APPNP, which already has low ECE.
RBS gains the best performance in the majority of the cases and outperforms classical temperature scaling in $11$ out of $15$ experiments.
Next to a good calibration performance, accuracy preservation is desirable for calibration methods. RBS and temperature scaling do not change the ranking of the classes and thus the accuracy stays unchanged. Meta-Cal trades good calibration for lower accuracy, while the other methods yield comparable or even slightly improved accuracy in some cases (see supplementary material).
\subsection{Effectiveness of real-ratio-binned scaling}
Table~\ref{tab:cal_performance} also shows the calibrated results of real-ratio-binned scaling (RRBS), where we assume that the ground-truth labels are available for all nodes. RRBS outperforms the best calibration method in 14 out of 15 experiments. Although the correct labels are not accessible in the semi-supervised setting, the results still indicate the effectiveness of the intuition of our proposed method.
\section{Discussion}
\label{sec:discussion}
In general, the calibration performance depends on the specific GNN model and dataset, where all models perform best on Pubmed (see Table~\ref{tab:cal_performance}).
When using the hyperparameter and training settings from the original publications, all GNNs tend to be underconfident on all three datasets, in contrast to the finding that deep neural network models rather exhibit overconfidence~\cite{guo2017calibration,thulasidasan2019mixup}. However, when plotting the reliability diagrams for a varying number of epochs, we observe that in some cases, underconfidence changes to overconfidence when the number of epochs increases. It seems that underconfidence or overconfidence is not necessarily a property of the model architecture but is also dependent on the training setting.
Most GNNs suffer from oversmoothing, which becomes apparent when increasing the number of layers in the model~\cite{klicpera2019predict,li2018deeper,xu2018representation}. We observe that for large numbers of layers, the accuracy drops significantly, while the ECE improves. Oversmoothing results in similar node embeddings, which might be uninformative for the model. In this case, the model would most likely learn the distribution of classes in the training data as confidence scores. Therefore, all samples would be grouped into one bin, resulting in low ECE if the test distribution is close to the training distribution. However, such a model does not make use of the underlying graph structure and is probably not useful for application.
The results for RBS and RRBS show the potential of a calibration method that takes the graph structure into account, where the binning scheme is constructed depending on node-level properties. RRBS almost always outperforms RBS, which suggests that RBS might be especially helpful for cases where the estimated ratios are close to the real ratios, i.e., for models with relatively high accuracy. The number of bins for RBS was chosen from $\{2,3,4\}$, and it seems that even a small number of bins can lead to improved calibration compared to classical temperature scaling.
It would further be interesting to apply RBS to other kinds of datasets, e.g., heterophilic graphs, where nodes from different classes are likely to be connected.
\section{Conclusion}
We investigated the calibration of graph neural networks for node classification on three benchmark datasets. Graph neural networks seem to be miscalibrated, where the exact calibration depends on both the dataset and the model. Existing post-processing calibration methods are able to alleviate the miscalibration but do not consider the graph structure. Based on our experimental finding that the nodes in the graph express different levels of over- or underconfidence depending on their same-class-neighbor ratios, we proposed the topology-aware calibration metohd ratio-binned scaling. It takes the predictions of neighboring nodes into account and shows better performance compared to state-of-the-art baselines.
For future work, it would be interesting to gain a more theoretical understanding of the calibration properties and conduct experiments on larger and a wider variety of datasets.
\iffalse
\begin{table}[t]
\setlength{\tabcolsep}{0.5em}
\setlength{\extrarowheight}{0.1em}
\caption{Calibrated performance of SOTA (best baseline method from Table~\ref{tab:cal_performance}), RBS, and RRBS (mean±SD over 100 independent runs). The best calibration method for each GNN model is displayed in bold.}
\label{tab:rrbs}
\centering
\begin{tabular}{cc|c|ccc}
\hline
Dataset & Model & Uncal. & SOTA & RBS & RRBS \\ \hline
\multirow{5}{*}{Cora}
& GCN & 21.17±0.73 & 3.73±0.62 & 3.69±0.70 & \textbf{3.19±0.57} \\
& GAT & 15.19±0.54 & \textbf{3.37±0.65} & 3.54±0.76 & 3.46±0.62 \\
& SGC & 24.95±0.19 & 3.63±0.27 &3.23±0.11 & \textbf{2.86±0.16}\\
& gfNN & 16.30±0.35 & \textbf{3.08±0.43} & 3.57±0.79 & 3.36±0.48 \\
& APPNP & 16.96±0.56 & 3.38±0.59 & 3.26±0.64 & \textbf{3.15±0.51} \\
\hline
\multirow{5}{*}{Citeseer}
& GCN & 21.04±0.89 & 4.58±0.76 & 5.15±0.84 & \textbf{3.98±0.69} \\
& GAT & 17.00±0.55 & 5.19±0.68 & \textbf{4.31±0.72} & 4.85±0.86 \\
& SGC & 42.89±0.08 & 3.94±0.15 & 3.07±0.14 & \textbf{2.88±0.09}\\
& gfNN & 20.06±0.54 & 4.85±0.84 & 5.26±0.82 & \textbf{4.64±1.23} \\
& APPNP & 13.24±0.57 & 4.85±0.84 & 5.26±0.82 & \textbf{3.80±0.73}\\
\hline
\multirow{5}{*}{Pubmed}
& GCN & 26.59±0.65 & 4.38±0.60 & 4.49±0.60 & \textbf{3.34±0.65} \\
& GAT & 4.46±0.76 & 3.96±0.69 & 3.70±0.65 & \textbf{3.11±0.62}\\
& SGC & 20.99±0.02 & \textbf{3.74±0.29} & 4.24±0.14 & 3.88±0.11 \\
& gfNN & 4.38±0.42 & 4.74±0.67 & 4.71±1.33 & \textbf{3.56±1.40} \\
& APPNP & 5.14±0.83 & 4.47±0.60 & 4.21±0.75 & \textbf{3.05±0.55}\\
\hline
\end{tabular}
\end{table}
\fi
\section*{Acknowledgment}
This work has been supported by the German Federal Ministry for Economic Affairs and Climate Action (BMWK) as part of the project RAKI under grant number 01MD19012C.
\bibliographystyle{IEEEtran}
| {'timestamp': '2022-06-06T02:14:34', 'yymm': '2206', 'arxiv_id': '2206.01570', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01570'} | arxiv |
\section{Broader Impact}
This work provides a technical advancement in the field of unsupervised representation learning, that already has great impact throughout many applications. In particular, in the medical context, including prior information can be of great value in order to convince clinicians to use AI solutions for computer-aided diagnosis. This work is also a theoretical advancement in representation learning for deep learning (DL) applications. We believe that it is crucial to provide theoretical guarantees of current DL systems in order to improve their reliability and robustness.
\section{More Empirical Evidence}
In this section, we provide additional empirical evidence to confirm several claims and arguments developed in the paper.
\subsection{Decoupled Uniformity optimizes alignment}
\begin{figure}[h!]
\centering
\includegraphics[width=.6\linewidth]{results/alignment_cifar_decoupled-unif.png}
\caption{Alignment metric $\cL_{align}$ computed on the validation set during optimization of Decoupled Uniformity loss with various batch sizes $n$ and a fixed latent space dimension $d=128$. We use 100 positive samples per image to compute $\cL_{align}$. }
\end{figure}
We empirically show here that Decoupled Uniformity optimizes alignment, even in the regime when the batch size $n> d+1$, where $d$ is the representation space dimension. We use CIFAR-10 and CIFAR-100 datasets and we optimize Decoupled Uniformity (without kernel) with all SimCLR augmentations with $d=128$ and we vary the batch size $n$. We report the alignment metric defined in~\cite{wang_understanding_2020} as $\cL_{align}=\bbE_{\cA(x|\bar{x})\cA(x'|\bar{x})p(\bar{x})} ||f(x)-f(x')||^2$.
\subsection{Multi-view Contrastive Learning with Decoupled Uniformity}
When the intra-class connectivity hypothesis is full-filled, we showed that Decoupled Uniformity loss can tightly bound the classification risk for well-aligned encoders (see Theorem~\ref{th:boundness_intra_class_hyp}). Under that hypothesis, we consider the standard empirical estimator of $\mu_{\bar{x}}\approx \sum_{v=1}^V f(x^{(v)})$ for $V$ views. Using all SimCLR augmentations, we empirically verify that increasing $V$ allows for: 1) a better estimate of $\mu_{\bar{x}}$ which implies a faster convergence and 2) better SOTA results on both small-scale (CIFAR10, CIFAR100, STL10) and large-scale (ImageNet100) vision datasets.
We always use batch size $n=256$ for all approaches with ResNet18 backbone for CIFAR10, CIFAR100 and STL10 and ResNet50 for ImageNet100. We report the results in Table~\ref{tab:multiview_decoupled_unif}.
\begin{table}[h!]
\centering
\begin{adjustbox}{max width=\textwidth}
\begin{tabular}{c c c c c c c c c}
\toprule
Model & \multicolumn{2}{c}{CIFAR-10} & \multicolumn{2}{c}{CIFAR-100} & \multicolumn{2}{c}{ImageNet100} & \multicolumn{2}{c}{STL10} \\
& $e=200$ & $e=400$ & $e=200$ & $e=400$ & $e=200$ & $e=400$ & $e=200$ & $e=400$ \\
\midrule
SimCLR\cite{chen_simple_2020} & 79.4 & 81.75 & 48.89 & 53.02 & 65.30 & 66.52 & 76.99 & 79.02 \\
BYOL\cite{grill2020bootstrap} & 80.14 & 81.97 & 51.57 & 53.65 & 72.20 & 72.26 & 77.62 & 79.61 \\
Decoupled Unif (2 views) & 82.43 & \textbf{85.82} & 56.95 & 58.89 & 71.98 & 72.24 & 78.12 & 79.89 \\
Decoupled Unif (4 views) & 84.99 & 85.34 & 57.23 & 59.07 & 72.08 & 75.00 & 78.25 & \textbf{80.47} \\
Decoupled Unif (8 views) & \textbf{86.50} & 85.80 & \textbf{59.63} & \textbf{59.74} & \textbf{74.70} & \textbf{75.00} & \textbf{79.82} & 80.30 \\
\bottomrule
\end{tabular}
\end{adjustbox}
\caption{A better approximation of centroids $\mu_{\bar{x}}$ (i.e. increasing number of views) when augmentation overlap hypothesis is (nearly) full-filled implies faster convergence. All models are pre-trained with batch size $n=256$. We use ResNet18 backbone for CIFAR10, CIFAR100, STL10 and ResNet50 for ImageNet100. We report linear evaluation accuracy ($\%$) for a given number of epochs $e$. }
\label{tab:multiview_decoupled_unif}
\end{table}
\subsection{Longer training on ImageNet100}
A longer training time is beneficial for our method when using the BigBiGAN representation pretrained on ImageNet as prior ($K_{GAN}$ Decoupled Unif). In particular, we show that at 400 epochs, we obtain SOTA results. We always use batch size $n=256$ in this experiment and we use the kernel $K_{GAN}(\bar{x}, \bar{x}')=K(z(\bar{x}), z(\bar{x}'))$ where $K$ is an RBF kernel and $z(\cdot)$ is the representation given by BigBiGAN's encoder pre-trained on ImageNet.
\begin{table}[h!]
\centering
\begin{adjustbox}{max width=\textwidth}
\begin{tabular}{c c c}
\toprule
Model & epochs & ImageNet100 \\
\midrule
SimCLR (repro) & 400 & 66.52 \\
BYOL (repro) & 400 & 72.26 \\
CMC~\cite{tian_contrastive_2020} & 400 & 73.58 \\
DCL~\cite{chuang_debiased_2020} & 400 & 74.6 \\
AlignUnif~\cite{wang_understanding_2020} & 240 & 74.6\\
Decoupled Unif (4 views) & 400 & 75.0 \\
\textit{Pretrained ImageNet} \\
BigBiGAN~\cite{donahue2019large} & - & 72.0\\
$K_{GAN}$ Decoupled Unif (4 views) & 400 & \textbf{76.60} \\
\midrule
Supervised & 100 & $82.1_{\pm 0.59}$\\
\bottomrule
\end{tabular}
\end{adjustbox}
\captionof{table}{Using prior information given by BigBiGAN encoder pre-trained on ImageNet for Kernel Decoupled Uniformity provides better representation.}
\end{table}
\subsection{Influence of temperature and batch size for Decoupled Uniformity}
InfoNCE is known to be sensitive to batch size and temperature to provide SOTA results. In our theoretical framework, we assumed that $f(x)\in \bbS^{d-1}$ but we can easily extend it to $f(x)\in \sqrt{t}\bbS^{d-1}$ where $t>0$ is a hyper-parameter. It corresponds to write $\cL_{unif}^d(f)=\bbE_{p(\bar{x})p(\bar{x}')}e^{-t||\mu_{\bar{x}}-\mu_{\bar{x}'}||^2}$. We show here that Decoupled Uniformity does not require very large batch size (as it is the case for SimCLR) and produce good representations for $t\in [1, 5]$.
\begin{table}[h!]
\centering
\begin{tabular}{c c c c c c c}
\toprule
Datasets & $t=0.1$ & $t=0.5$ & $t=1$ & $t=2$ & $t=5$ & $t=10$\\
\midrule
CIFAR10 & 73.91 & 83.01 & 84.72 & 85.82 & 83.05 & 74.82\\
CIFAR100 & 39.16 & 51.33 & 55.91 & 58.89 & 56.70 & 48.29 \\
\bottomrule
\end{tabular}
\caption{Linear evaluation accuracy (\%) after training for 400 epochs with batch size $n=256$ and varying temperature in Decoupled Uniformity loss with SimCLR augmentations. $t=2$ gives overall the best results, similarly to the uniformity loss in~\cite{wang_understanding_2020}}
\end{table}
\begin{table}[h!]
\centering
\begin{tabular}{c c c c c c}
\toprule
Datasets & Loss & $n=128$ & $n=512$ & $n=1024$ & $n=2048$\\
\midrule
\multirow{2}{*}{CIFAR10} & SimCLR & 78.89 & 79.40 & 80.02 & 80.06 \\
& Decoupled Unif & 82.67 & 82.12 & 82.74 & 82.33\\
\midrule
\multirow{2}{*}{CIFAR100} & SimCLR & 49.53 & 53.46 & 54.45 & 55.32 \\
& Decoupled Unif & 54.61 & 54.12 & 55.56 & 55.20 \\
\bottomrule
\end{tabular}
\caption{Linear evaluation accuracy (\%) after training for 200 epochs with a batch size $n$, ResNet18 backbone and latent dimension $d=128$. Decoupled Uniformity is less sensitive to batch size than SimCLR thanks to its decoupling between positives and negatives, similarly to~\cite{yeh2021decoupled}.}
\end{table}
\subsection{Kernel choice on RandBits experiment}
In our experiments on RandBits, we used RBF Kernel in Decoupled Uniformity but other kernels can be considered. Here, we have compared our approach with a cosine kernel on Randbits with $k=10$ and $k=20$ bits. There is no hyper-parameter to tune with cosine. From Table~\ref{tab:kernel_randbits}, we see that cosine gives comparable results for $k=10$ bits with RBF but it is not appropriate for $k=20$ bits.
\begin{table}[h!]
\centering
\begin{tabular}{c c c c c}
\toprule
Kernel & 10 bits & 20 bits\\
\midrule
RBFKernel($\sigma=1$) & $66.25_{\pm 0.17}$ & $9.91_{\pm 0.13}$ \\
RBFKernel($\sigma=30$) & $67.21_{\pm 0.29}$ & $66.46_{\pm 0.19}$ \\
RBFKernel($\sigma=50$) & $68.42_{\pm 0.51}$ & $68.58_{\pm 0.17}$\\
CosineKernel & $66.56_{\pm 0.45}$ & $9.68_{\pm 0.18}$ \\
\bottomrule
\end{tabular}
\caption{Linear evaluation after training on RandBits-CIFAR10 with ResNet18 for 200 epochs. RBF and Cosine kernels are evaluated.}
\label{tab:kernel_randbits}
\end{table}
\section{Geometrical Considerations about Decoupled Uniformity}
In this section, we provide a geometrical understanding of Decoupled Uniformity loss from a metric learning point of view. In particular, we consider the Log-Sum-Exp (LSE) operator often used in CL as an approximation of the maximum.
We consider the finite-samples case with $n$ original samples $(\bar{x}_i)_{i\in[1..n]}\overset{iid}{\sim} p(\bar{x})$ and $V$ views $(x_i^{(v)})_{v\in [1..V]}\overset{iid}{\sim}\cA(\cdot|\bar{x}_i)$ for each sample $\bar{x}_i$. We make an abuse of notations and set $\mu_i=\frac{1}{V}\sum_{v=1}^V f(x_i^{(v)})$. Then we have:
\begin{equation}
\begin{aligned}
\hat{\cL}_{unif}^d &= \log \frac{1}{n(n-1)}\sum_{i\neq j} \exp\left(-||\mu_i - \mu_j||^2\right)\\
&= \log \frac{1}{n(n-1)}\sum_{i\neq j} \exp\left(-s_i^+ - s_j^+ + 2 s_{ij}^-\right)
\label{eq:proofLdunif}
\end{aligned}
\end{equation}
where $s_i^+ = ||\mu_i||^2 = \frac{1}{V^2} \sum_{v, v'} s(x_i^{(v)}, x_i^{(v')})$, $s_{ij}^-=\frac{1}{V^2}\sum_{v, v'} s(x_i^{(v)}, x_j^{(v')})$ and $s(\cdot, \cdot)=\langle f(\cdot), f(\cdot)\rangle_2$ is viewed as a similarity measure.
From a metric learning point-of-view, we shall see that minimizing Eq.~\ref{eq:proofLdunif} is (almost) equivalent to looking for an encoder $f$ such that the sum of similarities of all views from the same anchor ($s_i^+$ and $s_j^+)$ are higher than the sum of similarities between views from different instances ($s_{ij}^-$):
\begin{equation}
s_i^+ + s_j^+ > 2s_{ij}^- + \epsilon \quad \forall i\neq j
\end{equation}
where $\epsilon$ is a margin that we suppose "very big" (see hereafter). Indeed, this inequality is equivalent to $-\epsilon > 2s_{ij}^- - s_i^+ - s_j^+$ for all $i\neq j$, which can be written as :
\begin{equation*}
\argmin_f \max(-\epsilon, \{2s_{ij}^- - s_i^+-s_j^+\}_{i,j\in [1..n], j\neq i})
\end{equation*}
This can be transformed into an optimization problem using the LSE (log-sum-exp) approximation of the $\max$ operator:
\begin{equation*}
\argmin_f \log\left(\exp(-\epsilon) + \sum_{i\neq j} \exp{(-s_i^+ - s_j^+ + 2s_{ij}^-)}\right)
\end{equation*}
Thus, if we use an infinite margin ($\lim_{\epsilon \rightarrow \infty}$) we retrieve exactly our optimization problem with Decoupled Uniformity in Eq.\ref{eq:proofLdunif} (up to an additional constant depending on $n$).
\section{Additional general guarantees on downstream classification}
\subsection{Optimal configuration of supervised loss}
In order to derive guarantees on a downstream classification task $\cD$ when optimizing our unsupervised decoupled uniformity loss, we define a supervised loss that measures the risk on a downstream supervised task. We prove in the next section that the minimizers of this loss have the same geometry as the ones minimizing cross-entropy and SupCon~\cite{khosla_supervised_2020}: a regular simplex on the hyper-sphere~\cite{graf2021dissecting}. More formally, we have:
\begin{lemma}
Let a downstream task $\cD$ with $C$ classes. We assume that $C \le d+1$ (\textit{i.e.,} a big enough representation space), that all classes are balanced and the realizability of an encoder $f^*=\argmin_{f\in \cF}\cL_{sup}(f)$ with $\mathcal{L}_{sup}(f) = \log \bbE_{y, y'\sim p(y)p(y')}e^{-||\mu_y - \mu_{y'}||^2}$, and $\mu_y = \bbE_{p(\bar{x}|y)} \mu_{\bar{x}}$. Then the optimal centroids $(\mu_y^*)_{y\in \cY}$ associated to $f^*$ make a regular simplex on the hypersphere $\bbS^{d-1}$ and they are perfectly linearly separable, i.e $\min_{(w_y)_{y\in \cY}\in \bbR^d}\bbE_{(\bar{x}, y)\sim \cD}\mathbb{1}(w_y\cdot \mu_y^* < 0)=0$. Proof in the next section.
\end{lemma}
This property notably implies that we can realize 100\% accuracy at optima with linear evaluation (taking the linear classifier $g(\bar{x})=W^*f^*(\bar{x})$ with $W^*=(\mu_y^*)_{y\in \cY}\in \bbR^{C\times d}$).
\subsection{General guarantees of Decoupled Uniformity}
In its most general formulation, we tightly bound the previous supervised loss by Decoupled Uniformity loss $\cL_{unif}^d$ depending on a variance term of the centroids $\mu_{\bar{x}}$ conditionally to the labels:
\begin{theorem} (Guarantees for a given downstream task)
For any $f\in \cF$ and augmentation $\cA$ we have:
\begin{equation}
\cL_{unif}^d(f) \le \cL_{sup}(f) \le 2\sum_{j=1}^d\var(\mu_{\bar{x}}^j |y) + \cL_{unif}^d(f) \le 4\mathbb{E}_{p(\bar{x}|y)p(\bar{x}'|y)}||\mu_{\bar{x}}-\mu_{\bar{x}'}|| + \cL_{unif}^d(f)
\end{equation}
where $\var(\mu_{\bar{x}}^j|y)=\bbE_{p(\bar{x}|y)}(\mu_{\bar{x}}^j - \bbE_{p(\bar{x}'|y)}\mu_{\bar{x}'}^j)^2$, $y=\argmax_{y'\in \cY} \var(\mu_{\bar{x}}^j|y')$ and $\mu^j_{\bar{x}}$ is the $j$-th component of $\mu_{\bar{x}}=\bbE_{\cA(x|\bar{x})}f(x)$. Proof in the next section.
\label{th:downstream_gen}
\end{theorem}
Intuitively, it means that we will achieve good accuracy if all centroids $(\mu_{\bar{x}})_{\bar{x}\in \bar{\cX}}$ for samples $\bar{x}\in \bar{\cX}$ in the same class are not too far. This theorem is very general since we do not require the intra-class connectivity assumption on $\cA$; so any $\cA \subset \cA^*$ can be used.
\section{Experimental Details}
Code will be released upon acceptance of the manuscript. We provide a detailed pseudo-code of our algorithm as well as all experimental details to reproduce the experiments run in the manuscript.
\subsection{Pseudo-code}
\begin{algorithm}
\caption{Pseudo-code of the algorithm}
\begin{algorithmic}
\Require Batch of images $(\bar{x}_1, ...,\bar{x}_n)\in \bar{\cX}$, augmentation distribution $\cA$
\State $K_n \gets (K(\bar{x}_i, \bar{x}_j))_{i,j\in [1..n]}$ \Comment{Compute the kernel matrix}
\State $\mathbf{\alpha} \gets (K_n + n\lambda\mathbf{I}_n)^{-1}K_n$ \Comment{Compute weights for centroid estimation}
\State $x_i^{(1)},...,x_i^{(V)}\overset{iid}{\sim} \cA(\cdot |\bar{x}_i)$ \Comment{Sample $V$ views per image}
\State $F \gets (\frac{1}{V}\sum_{v=1}^V f(x_i^{(v)}))_{i\in [1..n]}$ \Comment{Compute the averaged image representations}
\State $\hat{\mu} \gets \alpha F$ \Comment{Centroid estimation}
\State $\hat{\cL}_{unif}^d \gets \log \frac{1}{n(n-1)}\sum_{i\neq j} \exp(-||\hat{\mu}_i - \hat{\mu}_j||^2)$ \Comment{Kernel Decoupled Uniformity loss }
\Return $\hat{\cL}_{unif}^d$
\end{algorithmic}
\end{algorithm}
\subsection{Implementation in PyTorch}
\begin{algorithm}
\caption{Implementation in PyTorch}
\begin{lstlisting}[language=Python]
# loader: generator of images
# n: batch size
# n_views: number of views
# d: latent space dimension
# f: encoder (with projection head)
# x: Tensor of shape [n, *]
# aug: augmentation module generating views
# K: kernel defined on image space
for x in loader:
alphas = (K(x, x) + n*lamb*torch.eye(n)).inverse() @ K(x, x)
x = aug(x, n_views) # shape=[n*n_views, *]
z = f(x).view([n, n_views, d]) # shape=[n, n_views, d]
mu = alphas.detach() @ z.mean(dim=1) # shape=[n, d]
loss = L(mu)
loss.backward()
def L(mu, t=2):
return torch.pdist(z, p=2).pow(2).mul(-t).exp().mean().log()
\end{lstlisting}
\end{algorithm}
\subsection{Datasets}
\paragraph{CIFAR~\cite{krizhevsky2009learning}} We use the original training/test split with 50000 and 10000 images respectively of size $32\times 32$.
\paragraph{STL-10~\cite{coates2011analysis}} In unsupervised pre-training, we use all labelled+unlabelled images (105000 images) for training and the remaining 8000 for test with size $96\times 96$. During linear evaluation, we only use the 5000 training labelled images for learning the weights.
\paragraph{CUB200-2011~\cite{wah2011caltech}} This dataset is composed of 200 fine-grained bird species with 5994 training images and 5794 test images rescaled to $224\times 224$.
\paragraph{UTZappos~\cite{yu2014fine}} This dataset is composed of images of shoes from zappos.com. In order to be comparable with the literature on weakly supervised learning, we follow~\cite{tsai2022conditional} and split it into 35017 training images and 15008 test images resized at $32\times 32$.
\paragraph{ImageNet100~\cite{deng2009imagenet, tian_contrastive_2020}} It is a subset of ImageNet containing 100 random classes and introduced in~\cite{tian_contrastive_2020}. It contains 126689 training images and 5000 testing images rescaled to $224\times 224$. It notably allows a reasonable computational time since we runt all our experiments on a single server node with 4 V100 GPU.
\paragraph{BHB~\cite{dufumier_contrastive_2021}} This dataset is composed of 10420 3D brain MRI images of size $121\times 145\times 121$ with $1.5mm^3$ spatial resolution. Only healthy subjects are included.
\paragraph{BIOBD~\cite{hozer2021lithium}} It is also a brain MRI dataset including 662 3D anatomical images and used for downstream classification. Each 3D volume has size $121\times 145\times 121$. It contains 306 patients with bipolar disorder vs 356 healthy controls and we aim at discriminating patients vs controls. It is particularly suited to investigate biomarkers discovery inside the brain~\cite{hibar2018cortical}.
\subsection{Contrastive Models}
\paragraph{Architecture.} For all small-scale vision datasets (CIFAR-10~\cite{krizhevsky2009learning}, CIFAR-100~\cite{krizhevsky2009learning}, STL-10~\cite{coates2011analysis}, CUB200-2011~\cite{wah2011caltech} and UT-Zappos~\cite{yu2014fine}), we used official ResNet18~\cite{he2016deep} backbone where we replaced the first $7\times 7$ convolutional kernel by a smaller $3\times 3$ kernel and we removed the first max-pooling layer for CIFAR-10, CIFAR-100 and UTZappos. For ImageNet100, we used ResNet50~\cite{he2016deep} for stronger baselines as it is common in the literature.
For medical images on brain MRI datasets (BHB~\cite{dufumier_contrastive_2021} and BIOBD\cite{hozer2021lithium}, we used DenseNet121~\cite{huang2017densely} as our default backbone encoder, following previous literature on these datasets~\cite{dufumier_contrastive_2021}.
Following~\cite{chen_simple_2020}, we use the representation space after the last average pooling layer with 2048 dimensions to perform linear evaluation and use a 2-layers MLP projection head with batch normalization between each layer for a final latent space with 128 dimensions.
\paragraph{Batch size.} We always use a default batch size 256 for all experiments on vision datasets and 64 for brain MRI datasets (considering the computational cost with 3D images and since it had little impact on the performance~\cite{dufumier_contrastive_2021}).
\paragraph{Optimization.} We use SGD optimizer on small-scale vision datasets (CIFAR-10, CIFAR-100, STL-10, CUB200-2011, UT-Zappos) with a base learning rate $0.3\times \text{batch size}/256$ and a cosine scheduler. For ImageNet100, we use a LARS~\cite{you2017large} optimizer with learning rate $0.02\times \sqrt{\text{batch size}}$ and cosine scheduler. In Kernel Decoupled Uniformity loss, we set $\lambda=\frac{0.01}{\sqrt{\text{batch size}}}$ and $t=2$. For SimCLR, we set the temperature to $\tau=0.07$ for all datasets following \cite{yeh2021decoupled}. Unless mentioned otherwise, we use 2 views for Decoupled Uniformity (both with and without kernel) and the computational cost remains comparable with standard contrastive models.
\paragraph{Training epochs.} By default, we train the models for 200 epochs unless mentioned otherwise for all vision data-sets excepted CUB200-2011 and UTZappos where we train them for 1000 epochs, following~\cite{tsai2022conditional}. For medical datasets, we perform pre-training for 50 epochs, as in \cite{dufumier_contrastive_2021}. For linear evaluation, we use a simple linear layer trained for 300 epochs with an initial learning rate 0.1 decayed by 0.1 on each plateau.
\paragraph{Augmentations.} We follow~\cite{chen_simple_2020} to define our full set of data augmentations for vision datasets including: \textit{RandomResizedCrop} (uniform scale between 0.08 to 1), \textit{RandomHorizontalFlip} and color distorsion (including color jittering and gray-scale). For medical datasets, we use cutout covering 25\% of the image in each direction ($1/4^3$ of the entire volume), following~\cite{dufumier_contrastive_2021}.
\subsubsection{Generative Models}
\paragraph{Architecture.} For VAE, we use ResNet18 backbone with a completely symmetric decoder using nearest-neighbor interpolation for up-sampling. For DCGAN, we follow the architecture described in ~\cite{radford2015unsupervised}. We keep the original dimension for CIFAR-10 and CIFAR-100 datasets and we resize the images to $64\times 64$ for STL-10. For BigBiGAN~\cite{donahue2019large}, we use the ResNet50 pre-trained encoder available at \url{https://tfhub.dev/deepmind/bigbigan-resnet50/1} with BN+CReLU features.
\paragraph{Training.} For VAE, we use PyTorch-lightning pre-trained model for STL-10 \footnote{\url{https://github.com/PyTorchLightning/pytorch-lightning}} and we optimize VAE for CIFAR-10 and CIFAR-100 for 400 epochs using an initial learning rate $10^{-4}$ and SGD optimizer with a cosine scheduler. We use the same pipeline on RandBits dataset. For DCGAN, we optimize it using Adam optimizer (following~\cite{radford2015unsupervised}) and base learning rate $2\times 10^{-4}$.
\section{Omitted Proofs}
\subsection{Estimation Error with Empirical Decoupled Uniformity}
\begin{property}
$\hat{\cL}_{unif}^d(f)$ fulfills $|\hat{\cL}_{unif}^d(f) - \cL_{unif}^d(f)|\le O\left(\frac{1}{\sqrt{n}}\right)$.
\label{prop:decoupled_unif_estim}
\end{property}
\begin{proof}
For any $x\in \cX$, since $f(x)\in \bbS^{d-1}$, then $||\mu_{\bar{x}}||=||\bbE_{\cA(x|\bar{x})}f(x)||\le \bbE_{\cA(x|\bar{x})}||f(x)||= 1$. As a result, $e^{-||\mu_{\bar{x}}-\mu_{\bar{x}'}||^2}\in I\defeq [e^{-4}, 1]$ for any $\bar{x}, \bar{x}'\in \bar{\cX}$. Since $\log$ is $k$-Lipschitz on $I$ then:
\begin{equation*}
|\hat{\cL}_{unif}^d(f) - \cL_{unif}^d(f)| \le k\left|\frac{1}{n(n-1)}\sum_{i\neq j} e^{-||\mu_{\bar{x}_i} - \mu_{\bar{x}_j}||^2} - \bbE_{p(\bar{x})p(\bar{x}')}e^{-||\mu_{\bar{x}} - \mu_{\bar{x}'}||^2} \right|
\end{equation*}
For a fixed $\bar{x}\in \bar{\cX}$, let $g_n(\bar{x}) = \frac{1}{n}\sum_{i=1}^n e^{-||\mu_{\bar{x}}- \mu_{\bar{x}_i}||^2}$ and $g(\bar{x})=\bbE_{p(\bar{x}')}e^{-||\mu_{\bar{x}}-\mu_{\bar{x}'}||^2}$. Since $(Z_i)_{i\in[1..n]} = \left(e^{-||\mu_{\bar{x}}- \mu_{\bar{X}_i}||^2}- g(\bar{x})\right)_{i\in [1..n]}$ are iid with bounded support in $[-2, 2]$ and zero mean then by Berry–Esseen theorem we have $|g_n(\bar{x})-g(\bar{x})|\le O(\frac{1}{\sqrt{n}})$. Similarly, $(Z_i')_{i\in [1..n]}=\left(g_n(\bar{X}_i) - \bbE_{p(\bar{x})}g_n(\bar{x})\right)$ are iid, bounded in $[-2, 2]$ and with zero mean. So $|\frac{1}{n}\sum_{i=1}^n g_n(\bar{x}_i) - \bbE_{p(\bar{x})}g_n(\bar{x})|\le O(\frac{1}{\sqrt{n}})$ by Berry–Esseen theorem. Then we have:
\begin{align*}
|\hat{\cL}_{unif}^d(f) - \cL_{unif}^d(f)| &\le k|\frac{n}{(n-1)n}\sum_{i=1}^n g_n(\bar{x}_i) - \bbE_{p(\bar{x})}g(\bar{x})|\\
&\le 2k|\frac{1}{n}\sum_{i=1}^n g_n(\bar{x}_i) - \bbE_{p(\bar{x})}g_n(\bar{x})+\bbE_{p(\bar{x})}g_n(\bar{x})-\bbE_{p(\bar{x})}g(\bar{x})|\\
&\le O(\frac{1}{\sqrt{n}}) + O(\frac{1}{\sqrt{n}})\le O(\frac{1}{\sqrt{n}})
\end{align*}
\end{proof}
\subsection{Optimality of Decoupled Uniformity}
\setcounter{theorem}{0}
\begin{theorem}(Optimality of Decoupled Uniformity)
Given $n$ points $(\bar{x}_i)_{i\in [1..n]}$ such that $n\le d+1$, the optimal decoupled uniformity loss is reached when:
\begin{enumerate}
\item (Perfect uniformity) All centroids $(\mu_i)_{i\in [1..n]} = (\mu_{\bar{x}_i})_{i\in [1..n]}$ make a regular simplex on the hyper-sphere $\bbS^{d-1}$
\item (Perfect alignment) $f$ is perfectly aligned, i.e $\forall x, x'\overset{iid}{\sim} \cA(\cdot|\bar{x}_i), f(x)=f(x')$
\end{enumerate}
\label{th:AppendixOptimal_decoupled_unif}
\end{theorem}
\begin{proof}
We will use Jensen's inequality and basic algebra to show these 2 properties. By triangular inequality, we have $||\mu_i||=||\bbE_{x\sim \cA(.|\bar{x}_i)} f(x)||\le \bbE||f(x)|| = 1$ since we assume $f(x)\in \bbS^d$. So all $(\mu_i)$ are bounded by 1.
Let $\mathbf{\mu}=(\mu_i)_{i\in [1..n]}$. We have:
\begin{align*}
\Gamma(\mathbf{\mu}) &:= \sum_{i,j=1}^n ||\mu_i - \mu_j||^2 =\sum_{i,j} ||\mu_i||^2 + ||\mu_j||^2 -2 \mu_i \cdot \mu_j \\
&\le \sum_{i, j} (2 - 2\mu_i \cdot \mu_j)\\
&= 2n^2 -2||\sum_{i} \mu_i||^2 \le 2n^2
\end{align*}
with equality if and only if $\sum_{i=1}^n \mu_i = 0$ and $\forall i \in [1..n], ||\mu_i||=1$. By strict convexity of $u\rightarrow e^{-u}$, we have:
\begin{align*}
\sum_{i\neq j} \exp(-||\mu_i - \mu_j||^2) &\ge n(n-1)\exp\left(-\frac{\Gamma(\mathbf{\mu})}{n(n-1)}\right)\\
&\ge n(n-1)\exp\left(-\frac{2n}{n-1}\right)
\end{align*}
with equality if and only if all pairwise distance $||\mu_i - \mu_j||$ are equal (equality case in Jensen's inequality for strict convex function), $\sum_{i=1}^n \mu_i=0$ and $||\mu_i|| = 1$. So all centroids must form a regular $n-1$-simplex inscribed on the hypersphere $\bbS^{d-1}$ centered at 0. \\
Finally, since $||\mu_i|| = 1$ then we have equality in the Jensen's inequality $||\mu_i||=||\bbE_{\cA(x|\bar{x}_i)}f(x)||\le \bbE_{\cA(x|\bar{x}_i)} ||f(x)|| = 1$. Since $||\cdot||$ is strictly convex on the hyper-sphere, then $f$ must be constant on $\supp \cA(\cdot|\bar{x}_i)$, for all $\bar{x}_i$ so $f$ must be perfectly aligned.
\end{proof}
\begin{theorem}(Asymptotical Optimality)
When the number of samples is infinite $n\rightarrow \infty$, then for any perfectly aligned encoder $f\in \cF$ that minimizes $\mathcal{L}_{unif}^d$, the centroids $\mu_{\bar{x}}$ for $\bar{x}\sim p(\bar{x})$ are uniformly distributed on the hypersphere $\bbS^{d-1}$.
\end{theorem}
\begin{proof}
Let $f\in \cF$ perfectly aligned. Then all centroids $\mu_{\bar{x}} = f(\bar{x})$ lie on the hypersphere $\bbS^{d-1}$ and we are optimizing:
\begin{equation*}
\argmin_f \cL_{unif}^d(f) = \argmin_f \bbE_{\bar{x},\bar{x}'\overset{iid}{\sim} p(\bar{x})} e^{-||f(\bar{x}) - f(\bar{x}')||^2}
\end{equation*}
So a direct application of Proposition 1. in~\cite{wang_understanding_2020} shows that the uniform distribution on $\bbS^{d-1}$ is the unique solution to this problem and that all centroids are uniformly distributed on the hyper-sphere.
\end{proof}
\subsection{Optimality of Supervised Loss}
\setcounter{theorem}{5}
\begin{lemma}
Let a downstream task $\cD$ with $C$ classes. We assume that $C \le d+1$ (\textit{i.e.,} a big enough representation space), that all classes are balanced and the realizability of an encoder $f^*=\argmin_{f\in \cF}\cL_{sup}(f)$ with $\mathcal{L}_{sup}(f) = \log \bbE_{y, y'\sim p(y)p(y')}e^{-||\mu_y - \mu_{y'}||^2}$, and $\mu_y = \bbE_{p(\bar{x}|y)} \mu_{\bar{x}}$. Then the optimal centroids $(\mu_y^*)_{y\in \cY}$ associated to $f^*$ make a regular simplex on the hypersphere $\bbS^{d-1}$ and they are perfectly linearly separable, i.e $\min_{(w_y)_{y\in \cY}\in \bbR^d}\bbE_{(\bar{x}, y)\sim \cD}\mathbb{1}(w_y\cdot \mu_y^* < 0)=0$.
\end{lemma}
\begin{proof}
This proof is very similar to the one in Theorem~\ref{th:optimal_decoupled_unif}. We first notice that all "labelled" centroids $\mu_{y}= \bbE_{p(\bar{x}|y)} \mu_{\bar{x}}$ are bounded by 1 ($||\mu_y|| \le \bbE_{p(\bar{x}|y)}\bbE_{\cA(x|\bar{x})} ||f(x)||=1 $ by Jensen's inequality applied twice). Then, since all classes are balanced, we can re-write the supervised loss as:
\begin{equation*}
\cL_{sup}(f) = \log \frac{1}{C^2} \sum_{y,y'=1}^C e^{-||\mu_y - \mu_{y'}||^2}
\end{equation*}
We have:
\begin{align*}
\Gamma_{\cY}(\mathbf{\mu}) &:= \sum_{y,y'=1}^C ||\mu_y - \mu_{y'}||^2 =\sum_{y,y'} ||\mu_y||^2 + ||\mu_{y'}||^2 -2 \mu_{y} \cdot \mu_{y'} \\
&\le \sum_{y, y'} (2 - 2\mu_y \cdot \mu_{y'})\\
&= 2C^2 -2||\sum_{y} \mu_y||^2 \le 2C^2
\end{align*}
with equality if and only if $\sum_{y=1}^C \mu_y = 0$ and $\forall y \in [1..C], ||\mu_y||=1$. By strict convexity of $u\rightarrow e^{-u}$, we have:
\begin{align*}
\sum_{y\neq y'} \exp(-||\mu_y - \mu_{y'}||^2) &\ge C(C-1)\exp\left(-\frac{\Gamma_{\cY}(\mathbf{\mu})}{C(C-1)}\right)\\
&\ge C(C-1)\exp\left(-\frac{2C}{C-1}\right)
\end{align*}
with equality if and only if all pairwise distance $||\mu_y - \mu_{y'}||$ are equal (equality case in Jensen's inequality for strict convex function), $\sum_{y=1}^C \mu_y=0$ and $||\mu_y|| = 1$. So all centroids must form a regular $C-1$-simplex inscribed on the hypersphere $\bbS^{d-1}$ centered at 0. Furthermore, since $||\mu_y||=1$ then we have equality in the Jensen's inequality $||\mu_y||=||\bbE_{p(\bar{x}|y) \cA(x|\bar{x})}f(x)||\le \bbE_{p(\bar{x}|y)\cA(x|\bar{x})} ||f(x)|| = 1$ so $f$ must by perfectly aligned for all samples belonging to the same class:
$\forall \bar{x}, \bar{x}'\sim p(\cdot|y), f(\bar{x}) = f(\bar{x}') $.
\end{proof}
\subsection{Generalization bounds for decoupled uniformity}
\begin{theorem} (Guarantees for a given downstream task)
For any $f\in \cF$ and augmentation distribution $\cA$, we have:
\begin{equation}
\cL_{unif}^d(f) \le \cL_{unif}^{sup}(f) \le 2\sum_{j=1}^d\var(\mu_{\bar{x}}^j |y) + \cL_{unif}^d(f) \le 4\mathbb{E}_{p(\bar{x}|y)p(\bar{x}'|y)}||\mu_{\bar{x}}-\mu_{\bar{x}'}|| + \cL_{unif}^d(f)
\end{equation}
where $\var(\mu_{\bar{x}}^j|y)=\bbE_{p(\bar{x}|y)}(\mu_{\bar{x}}^j - \bbE_{p(\bar{x}'|y)}\mu_{\bar{x}'}^j)^2$ and $\mu^j_{\bar{x}}$ is the $j$-th component of $\mu_{\bar{x}}=\bbE_{\cA(x|\bar{x})}f(x)$.
\end{theorem}
\begin{proof}
\paragraph{Lower bound.} To derive the lower bound, we apply Jensen's inequality to convex function $u\rightarrow e^{-u}$:
\begin{align*}
\exp \cL_{unif}^d(f) &= \bbE_{p(\bar{x})p(\bar{x}')}e^{-||\mu_{\bar{x}} - \mu_{\bar{x}'}||^2} \\
&= \bbE_{p(\bar{x}|y)p(\bar{x}'|y)p(y)p(y')}e^{-||\mu_{\bar{x}} - \mu_{\bar{x}'}||^2}\\
&\le \bbE_{p(y)p(y')}\exp \left(-\bbE_{p(\bar{x}|y)p(\bar{x}'|y')}||\mu_{\bar{x}} - \mu_{\bar{x}'}||^2\right)
\end{align*}
Then, by Jensen's inequality applied to $||.||^2$:
\begin{align*}
\bbE_{p(\bar{x}|y)p(\bar{x}'|y')}||\mu_{\bar{x}} - \mu_{\bar{x}'}||^2 &\stackrel{(1)}{=} \bbE_{p(\bar{x}|y)} ||\mu_{\bar{x}}||^2 + \bbE_{p(\bar{x}'|y')} ||\mu_{\bar{x}'}||^2 - 2\mu_y\cdot \mu_{y'}\\
&\ge ||\bbE_{p(\bar{x}|y)}\mu_{\bar{x}}||^2 + ||\bbE_{p(\bar{x}'|y')}\mu_{\bar{x}'}||^2 - 2\mu_y\cdot \mu_{y'} \\
&\stackrel{(1)}{=} ||\mu_y - \mu_{y'}||^2
\end{align*}
(1) follows according to the previous lemma. So we can conclude:
\begin{align*}
\exp \cL_{unif}^d(f) \le \bbE_{p(y)p(y')}\exp(-||\mu_y - \mu_{y'}||^2) = \exp \mathcal{L}_{unif}^{sup}
\end{align*}
\paragraph{Upper bound.} For this bound, we will use the following equality (by definition of variance):
\begin{align*}
||\bbE_{p(\bar{x}|y)}\mu_{\bar{x}}||^2 &= ||\bbE_{p(\bar{x}|y)}\mu_{\bar{x}}||^2 - \bbE_{p(\bar{x}|y)}||\mu_{\bar{x}}||^2 + \bbE_{p(\bar{x}|y)}||\mu_{\bar{x}}||^2 \\
&= -\sum_{j=1}^d \var(\mu_{\bar{x}}^j|y) + \bbE_{p(\bar{x}|y)}||\mu_{\bar{x}}||^2
\end{align*}
So we start by expending:
\begin{align*}
||\mu_{y} - \mu_{y'}||^2 &= ||\bbE_{p(\bar{x}'|y')}\mu_{\bar{x}'}||^2 + ||\bbE_{p(\bar{x}|y)}\mu_{\bar{x}}||^2 - 2\bbE_{p(\bar{x}|y)p(\bar{x}'|y')}\mu_{\bar{x}} \cdot \mu_{\bar{x}'} \\
&= \bbE_{p(\bar{x}|y)} ||\mu_{\bar{x}}||^2 + \bbE_{p(\bar{x}'|y')}||\mu_{\bar{x}'}||^2 - \left(\sum_{j=1}^d \var(\mu_{\bar{x}}^j|y) + \var(\mu_{\bar{x}'}^j|y) \right) - 2\bbE_{p(\bar{x}|y)p(\bar{x}'|y')}\mu_{\bar{x}} \cdot \mu_{\bar{x}'} \\
&= \bbE_{p(\bar{x}|y)p(\bar{x}'|y')} ||\mu_{\bar{x}} - \mu_{\bar{x}'}||^2 - 2\left(\sum_{j=1}^d \var(\mu_{\bar{x}}^j|y) \right)
\end{align*}
So by applying again Jensen's inequality:
\begin{align*}
\exp \cL_{unif}^{sup}=\bbE_{p(y)p(y')}\exp(-||\mu_y - \mu_{y'}||^2) &\le \bbE_{p(y)p(y')}\exp\left(-\bbE_{p(\bar{x}|y)p(\bar{x}'|y')} ||\mu_{\bar{x}} - \mu_{\bar{x}'}||^2 + 2\left(\sum_{j=1}^d \var(\mu_{\bar{x}}^j|y) \right)\right)\\
&\le\exp2\left(\sum_{j=1}^d \var(\mu_{\bar{x}}^j|y_m) \right)\bbE_{p(y)p(y')}\exp\left(-\bbE_{p(\bar{x}|y)p(\bar{x}'|y')} ||\mu_{\bar{x}} - \mu_{\bar{x}'}||^2\right)\\
&=\exp 2\left(\sum_{j=1}^d \var(\mu_{\bar{x}}^j|y_m) \right)\exp \cL_{unif}^d
\end{align*}
We set $y_m=\argmax_{i, y\in [1..d]\times \cY}\var(\mu_{\bar{x}}^j|y)$
We conclude here by taking the $\log$ on the previous inequality.
\paragraph{Variance upper bound.} Starting from the definition of conditional variance:
\begin{align*}
\sum_{j=1}^d \var(\mu_{\bar{x}}^j|y_m) &= \bbE_{p(\bar{x}|y_m)}||\mu_{\bar{x}}||^2 - ||\bbE_{p(\bar{x}|y_m)}\mu_{\bar{x}}||^2 \\
&= \bbE_{p(\bar{x}|y_m)}\left((||\mu_{\bar{x}}|| - ||\bbE_{p(\bar{x}|y_m)}\mu_{\bar{x}}||)(||\mu_{\bar{x}}|| + ||\bbE_{p(\bar{x}|y_m)}\mu_{\bar{x}}||)\right)\\
&\stackrel{(1)}{\le} \mathbb{E}_{p(\bar{x}|y_m)}||\mu_{\bar{x}}- \bbE_{p(\bar{x}'|y_m)}\mu_{\bar{x}'}||(||\mu_{\bar{x}}|| + ||\bbE_{p(\bar{x}|y_m)}\mu_{\bar{x}}||)\\
&\stackrel{(2)}{\le} 2 \mathbb{E}_{p(\bar{x}|y_m)}||\mu_{\bar{x}}- \bbE_{p(\bar{x}'|y_m)}\mu_{\bar{x}'}||\\
&\stackrel{(3)}{\le} 2\mathbb{E}_{p(\bar{x}|y_m)p(\bar{x}'|y_m)}||\mu_{\bar{x}}- \mu_{\bar{x}'}||
\end{align*}
(1) Follows from standard inequality $||a-b||\ge |||a|| - ||b|||$ (from Cauchy-Schwarz). (2) follows from boundness of $||\mu_{\bar{x}}||\le 1$ and Jensen's inequality. (3) is again Jensen's inequality.
\end{proof}
\subsection{Generalization bound under intra-class connectivity assumption}
\setcounter{theorem}{2}
\begin{theorem}
Assuming \ref{hyp:embed_intra_class_connect}, then for any $\epsilon$-weak aligned encoder $f\in \cF$:
\begin{equation}
\cL_{unif}^d(f) \le \cL_{unif}^{sup}(f) \le 8D\epsilon + \cL_{unif}^{d}(f)
\end{equation}
Where $D$ is the maximum diameter of all intra-class graphs $G_y$ ($y\in \cY$).
\end{theorem}
\begin{proof}
Let $y\in \cY$ and $\bar{x}, \bar{x}'\sim p(\bar{x}|y)p(\bar{x}'|y)$. By Assumption \ref{hyp:embed_intra_class_connect}, it exists a path of length $p\le D$ connecting $(\bar{x}, \bar{x}')$ in $G_y$. So it exists $(\bar{x}_i)_{i\in [1..p+1]}\in \bar{\cX}$ and $(x_i)_{i\in [1..p]\in \cX}$ s.t $\forall i\in [1..p], x_i\sim \cA(x_i|\bar{x}_i)\cap \cA(x_i|\bar{x}_{i+1})$, $\bar{x}_1=\bar{x}$ and $\bar{x}_{p+1} = \bar{x}'$. Then:
\begin{align*}
||\mu_{\bar{x}} - \mu_{\bar{x}'}|| &= ||\mu_{\bar{x}_1} - \mu_{\bar{x}_p}||\\
&= ||\sum_{i=1}^p \mu_{\bar{x}_{i+1}} - \mu_{\bar{x}_i}||\\
&\le \sum_{i=1}^p||\mu_{\bar{x}_{i+1}} - \mu_{\bar{x}_i}||\\
&= \sum_{i=1}^p||\mu_{\bar{x}_{i+1}} - f(x_i) + f(x_i) - \mu_{\bar{x}_i}||\\
&\le \sum_{i=1}^p||\mu_{\bar{x}_{i+1}} - f(x_i)|| + ||f(x_i)- \mu_{\bar{x}_i}||\\
&\stackrel{(1)}{\le}\sum_{i=1}^p\bbE_{p(x|\bar{x}_{i+1})}||f(x) - f(x_i)|| + \bbE_{p(x|\bar{x}_i)}||f(x_i)- f(x)||\\
&\stackrel{(2)}{\le}\sum_{i=1}^p (\epsilon + \epsilon)= 2\epsilon p \le 2\epsilon D
\end{align*}
(1) follows from Jensen's inequality and by definition of $\mu_{\bar{x}}$. (2) follows because $f$ is $\epsilon$-weak aligned and $x_i\sim \cA(x_i|\bar{x}_i)\cap \cA(x_i|\bar{x}_{i+1})$.
So we have $||\mu_{\bar{x}}-\mu_{\bar{x}'}||\le 2\epsilon D$ and we can conclude by Theorem \ref{th:downstream_gen} (right inequality).
\end{proof}
\subsection{Conditional Mean Embedding Estimation}
Let $f\in \cF$ fixed.
\begin{theorem}(Conditional Mean Embedding estimation)
We assume that $\forall g\in \cH_{\cX}, \bbE_{p(x|\cdot)}g(x) \in \cH_{\bar{\cX}}$. Let $\{(x_1, \bar{x}_1),...,(x_n, \bar{x}_n)\}$ iid samples from $p(x| \bar{x})p(\bar{x})$. Let $\Phi_n =[\phi(\bar{x}_1),...,\phi(\bar{x}_n)]$ and $\Psi_f=[f(x_1), ..., f(x_n)]^T$. An estimator of the conditional mean embedding is:
\begin{align}
\forall \bar{x}\in \bar{\cX}, \hat{\mu}_{\bar{x}} = \sum_{i=1}^n \alpha_i(\bar{x}) f(x_i)
\end{align}
where $\alpha_i(\bar{x})=\sum_{j=1}^n [(\Phi_n^T\Phi_n+\lambda n\mathbf{I}_n)^{-1}]_{ij}\langle \phi(\bar{x}_j), \phi(\bar{x})\rangle_{\mathcal{H}_{\bar{X}}}$. It converges to $\mu_{\bar{x}}$ with the $\ell_2$ norm at a rate $O(n^{-1/4})$ for $\lambda=O(\frac{1}{\sqrt{n}})$.
\end{theorem}
\begin{proof}
Let $m_{\bar{x}} = \bbE_{p(x|\bar{x})}\langle f(x), f(\cdot)\rangle \in \cH_{\cX}$ be the conditional mean embedding operator. According to Theorem 6 in \cite{song2013kernel} and the assumption $\forall g\in \cH_{\cX}, \bbE_{p(x|\cdot)}g(x) \in \cH_{\bar{\cX}}$, this estimator can be approximated by:
\begin{equation*}
\hat{m}_{\bar{x}} = \sum_{i=1}^n \alpha_i(\bar{x}) \langle f(x_i), f(\cdot) \rangle
\end{equation*}
with $\alpha_i$ defined previously in the theorem. This estimator converges with RKHS norm to $m_{\bar{x}}$ at rate $O(\frac{1}{\sqrt{n\lambda}}+\lambda)$. So we need to link $m_{\bar{x}}, \hat{m}_{\bar{x}}$ with $\mu_{\bar{x}}, \hat{\mu}_{\bar{x}}$. We have:
\begin{align*}
\langle m_{\bar{x}}, \hat{m}_{\bar{x}}\rangle_{\cH_{\cX}} &= \left\langle \bbE_{p(x|\bar{x})}\langle f(x), f(\cdot)\rangle_{\bbR^d} , \sum_{i=1}^n \alpha_i(\bar{x}) \langle f(x_i), f(\cdot) \rangle_{\bbR^d}\right\rangle_{\cH_{\cX}}\\
&= \sum_{i=1}^n \alpha_i(\bar{x}) \left\langle \langle \bbE_{p(x|\bar{x})}f(x), f(\cdot)\rangle_{\bbR^d}, \langle f(x_i), f(\cdot)\rangle_{\bbR^d} \right\rangle_{\cH_{\cX}} \\
&\stackrel{(1)}{=} \sum_{i=1}^n \alpha_i(\bar{x})\langle \bbE_{p(x|\bar{x})}f(x), f(x_i)\rangle_{\bbR^d}\\
&= \langle \mu_{\bar{x}}, \hat{\mu}_{\bar{x}}\rangle_{\bbR^d}
\end{align*}
(1) holds by the reproducing property of kernel $K_{\cX}$ in $\cH_{\cX}$. We can similarly obtain:
\begin{align*}
||m_{\bar{x}}||_{\cH_{\cX}}^2 &= \left\langle \bbE_{p(x|\bar{x})} \langle f(x), f(\cdot)\rangle_{\bbR^d}, \bbE_{p(x|\bar{x})} \langle f(x), f(\cdot)\rangle_{\bbR^d} \right\rangle_{\cH_{\cX}}\\
&\stackrel{(1)}{=} \langle \bbE_{p(x|\bar{x})}f(x), \bbE_{p(x|\bar{x})}f(x)\rangle_{\bbR^d} \\
&= ||\mathbb{E}_{p(x|\bar{x})}f(x)||^2 = ||\mu_{\bar{x}}||^2
\end{align*}
Again, (1) by reproducing property of $K_{\cX}$. And finally:
\begin{align*}
||\hat{m}_{\bar{x}}||^2_{\cH_{\cX}} &= \left\langle \sum_{i=1}^n \alpha_i(\bar{x}) \langle f(x_i), f(\cdot) \rangle_{\bbR^d} , \sum_{i=1}^n \alpha_i(\bar{x}) \langle f(x_i), f(\cdot) \rangle_{\bbR^d}\right\rangle_{\cH_{\cX}}\\
&= \sum_{i,j} \alpha_i(\bar{x})\alpha_j(\bar{x})\langle f(x_i), f(x_j)\rangle_{\bbR^d}\\
&= ||\hat{\mu}_{\bar{x}}||^2_{\bbR^d}
\end{align*}
By pooling these 3 equalities, we have:
\begin{align*}
||m_{\bar{x}} - \hat{m}_{\bar{x}}||_{\cH_{\cX}}^2 &= ||m_{\bar{x}}||^2 + ||\hat{m}_{\bar{x}}||^2 - 2 \langle m_{\bar{x}}, \hat{m}_{\bar{x}}\rangle\\
&= ||\mu_{\bar{x}}||^2 + ||\hat{\mu}_{\bar{x}}||^2 - 2 \langle \mu_{\bar{x}}, \hat{\mu}_{\bar{x}}\rangle\\
&= ||\mu_{\bar{x}}- \hat{\mu}_{\bar{x}}||_{\bbR^d}^2
\end{align*}
We can conclude since $||m_{\bar{x}} - \hat{m}_{\bar{x}}|| \le O(\lambda + (n\lambda)^{-1/2})$.
\end{proof}
\subsection{Generalization bound under extended intra-class connectivity hypothesis}
\begin{theorem_star}
Assuming \ref{hyp:kernel_expressivity} and \ref{hyp:extended_intra_class_connectivity} holds for a reproducible kernel $K_{\bar{\cX}}$ and augmentation distribution $\cA$. Let $f\in \cF$ $\epsilon'$-aligned. Let $(\bar{x}_i)_{i\in [1..n]}$ be $n$ samples iid drawn from $p(\bar{x})$. We have:
\begin{equation}
\cL_{unif}^d(f) \le \cL_{unif}^{sup}(f) \le \cL_{unif}^d(f) + 4D(2\epsilon'+\beta_n(K_{\bar{\cX}})\epsilon)+O(n^{-1/4})
\end{equation}
where $\beta_n(K_{\bar{\cX}}) = (\lambda_{min}(K_n) + \sqrt{n}\lambda)^{-1}=O(1)$ for $\lambda = O(\frac{1}{\sqrt{n}})$, $K_n=(K_{\bar{\cX}}(\bar{x}_i, \bar{x}_j))_{i,j\in [1..n]}$and $D$ is the maximal diameter for all $\tilde{G}_y$, $y\in \cY$. We noted $\lambda_{min}(K_n)$ is the minimal eigenvalue of $K_n$.
\end{theorem_star}
\begin{proof}
Let $y\in \cY$ and $\bar{x}, \bar{x}'\sim p(\bar{x}|y)p(\bar{x}'|y)$. By Assumption \ref{hyp:extended_intra_class_connectivity}, it exists a path of length $p\le D$ connecting $\bar{x}, \bar{x}'$ in $\tilde{G}$. So it exists $(\bar{u}_i)_{i\in [1..p+1]}\in \bar{\cX}$ and $(u_i)_{i\in I}\in \cX$ s.t $\forall i\in I, u_i\sim \cA(u_i|\bar{u}_i)\cap \cA(u_i|\bar{u}_{i+1})$ and
$\forall j\in J, \max(K(\bar{u}_j, \bar{u}_j), K(\bar{u}_{j+1}, \bar{u}_{j+1}))-K(\bar{u}_j, \bar{u}_{j+1})\le \epsilon$ with $(I, J)$ a partition of $[1..p]$. Furthermore, $\bar{u}_1=\bar{x}$ and $\bar{u}_{p+1} = \bar{x}'$. As a result, we have:
\begin{align*}
||\mu_{\bar{x}}-\mu_{\bar{x}'}|| &= ||\mu_{\bar{u}_1} - \mu_{\bar{u}_p}||\\
&= ||\sum_{i=1}^p \mu_{\bar{u}_{i+1}} - \mu_{\bar{u}_i}||\\
&\le \sum_{i=1}^p||\mu_{\bar{u}_{i+1}} - \mu_{\bar{u}_i}||\\
&= \sum_{i\in I}||\mu_{\bar{u}_{i+1}} - \mu_{\bar{u}_i}|| + \sum_{j\in J}||\mu_{\bar{u}_{j+1}} - \mu_{\bar{u}_j}||
\end{align*}
\paragraph{Edges in $E$.} As in proof of Theorem \ref{th:boundness_intra_class_hyp}, we use the $\epsilon'$-alignment of $f$ to derive a bound:
\begin{align*}
\sum_{i\in I}||\mu_{\bar{u}_{i+1}} - \mu_{\bar{u}_i}|| &= \sum_{i\in I}||\mu_{\bar{u}_{i+1}} - f(u_i) + f(u_i) - \mu_{\bar{u}_i}||\\
&\le \sum_{i\in I}||\mu_{\bar{u}_{i+1}} - f(u_i)|| + ||f(u_i)- \mu_{\bar{u}_i}||\\
&\stackrel{(1)}{\le}\sum_{i\in I}\bbE_{p(u|\bar{u}_{i+1})}||f(u) - f(u_i)|| + \bbE_{p(u|\bar{u}_i)}||f(u_i)- f(u)||\\
&\stackrel{(2)}{\le}\sum_{i\in I} (\epsilon' + \epsilon')= 2\epsilon' |I|
\end{align*}
(1) holds by Jensen's inequality and (2) because $f$ is $\epsilon'$-aligned.
\paragraph{Edges in $E_K$} For this bound, we will use Theorem \ref{th:cond_mean_embed_estim} to approximate $\mu_{\bar{u}}$ and then derive a bound from the property of $G_K^\epsilon$. Let $(x_k)_{k\in [1.n]}\sim p(x_k|\bar{x}_k)$ $n$ samples iid. By Theorem \ref{th:cond_mean_embed_estim}, we know that, for all $j\in J$, $\hat{\mu}_{\bar{u}_j}$ converges to $\mu_{\bar{u}_j}$ with $\ell_2$ norm at rate $O(n^{-1/4})$ where $\hat{\mu}_{\bar{u}_j} = \sum_{k,l=1}^n \alpha_{k,l}K_{\bar{\cX}}(\bar{x}_l, \bar{u}_j) f(x_k)$ and $\alpha_{k, l}=[(K_n + n\lambda \mathbf{I}_n)^{-1}]_{k,l}$. As a result, for any $j\in J$, we have:
\begin{align*}
||\mu_{\bar{u}_{j+1}}-\mu_{\bar{u}_j}|| &=||\mu_{\bar{u}_{j+1}}-\hat{\mu}_{\bar{u}_{j+1}} +\hat{\mu}_{\bar{u}_{j+1}} - \hat{\mu}_{\bar{u}_{j}} + \hat{\mu}_{\bar{u}_{j}} - \mu_{\bar{u}_j}||\\
&\le ||\mu_{\bar{u}_{j+1}}-\hat{\mu}_{\bar{u}_{j+1}}|| + ||\hat{\mu}_{\bar{u}_{j+1}} - \hat{\mu}_{\bar{u}_{j}}|| + ||\hat{\mu}_{\bar{u}_{j}} - \mu_{\bar{u}_j}||
&\stackrel{(1)}{\le} O\left(\frac{1}{n^{1/4}}\right) + ||\hat{\mu}_{\bar{u}_{j+1}} - \hat{\mu}_{\bar{u}_{j}}||
\end{align*}
Where (1) holds by Theorem \ref{th:cond_mean_embed_estim}. Then we will need the following lemma to conclude:
\paragraph{Lemma.} For any $a, b, c\in \bar{\cX}, \max(K(a, a), K(b, b)) - K(a, b)\ge |K(a, c) - K(b, c)| $ for any reproducible kernel K.
\begin{proof}
Let $a, b, c\in \bar{\cX}$. We consider the distance $d(x, y)=K(x, x)+K(y,y)-2K(x,y)$ (it is a distance since $K$ is a reproducible kernel so it can be expressed as $K(\cdot, \cdot)=\langle \phi(\cdot), \phi(\cdot)\rangle$). We will distinguish two cases.
\paragraph{Case 1.} We assume $K(a, c) \ge K(b, c)$. We have the following triangular inequality:
\begin{align*}
d(a, b) + d(a, c) &\ge d(b, c) \\
\implies K(a, b) + K(b,b)-2K(a,b) + K(a, a) + K(c, c)-2K(a,c) &\ge K(b,b) + K(c,c) - 2K(b,c)\\
\implies K(a,a) - K(a,b) \ge K(a,c) - K(b,c) \ge 0
\end{align*}
So $\max(K(a,a), K(b,b)) - K(a,b) \ge |K(a,c) - K(b,c)|$.
\paragraph{Case 2.} We assume $K(b, c) \ge K(a, c)$. We apply symmetrically the triangular inequality:
\begin{align*}
d(a, b) + d(b, c) &\ge d(a, c) \\
\implies K(b,b) - K(a,b) \ge K(b,c) - K(a,c) \ge 0
\end{align*}
So $\max(K(a,a), K(b,b)) - K(a,b) \ge |K(a,c) - K(b,c)|$, concluding the proof.
\end{proof}
Then, by definition of $\hat{\mu}_{\bar{u}_j}$:
\begin{align*}
||\hat{\mu}_{\bar{u}_{j+1}} - \hat{\mu}_{\bar{u}_{j}}|| &= ||\sum_{k,l=1}^n \alpha_{k,l}K(\bar{x}_l, \bar{u}_{j+1}) f(x_k) - \sum_{k,l=1}^n \alpha_{k,l}K(\bar{x}_l, \bar{u}_{j}) f(x_k)||\\
&= ||A C||
\end{align*}
Where $A = (\sum_{k=1}^n\alpha_{kj}f(x_k)^i)_{i,j}\in \bbR^{d\times n}$ ($f(\cdot)^i$ is the i-th component of $f(\cdot)$) and $C=(K(\bar{x}_l, \bar{u}_{j+1})-K(\bar{x}_l, \bar{u}_j))_{l}\in \bbR^{n\times 1}$. So, using the property of spectral $\ell_2$ norm we have:
\begin{align*}
||\hat{\mu}_{\bar{u}_{j+1}} - \hat{\mu}_{\bar{u}_{j}}|| &= ||A C|| \le ||A||_2 ||C||_2\\
\end{align*}
Using the previous lemma and because $(\bar{u}_j, \bar{u}_{j+1})\in E_K$, we have: $||C||_2^2=\sum_{i=1}^n(K(\bar{x}_i, \bar{u}_{j+1})-K(\bar{x}_i, \bar{u}_j))^2 \le \sum_{i=1}^n (\max(K(\bar{u}_{j+1}, \bar{u}_{j+1}), K(\bar{u}_{j}, \bar{u}_{j}))-K(\bar{u}_{j}, \bar{u}_{j+1}))^2 \le n\epsilon^2$ . To conclude, we will prove that $||A||_2 \le ||\mathbf{\alpha}||_2$ where $\mathbf{\alpha} = (\alpha_{ij})_{i,j\in [1..n]^2}$. For any $v\in \bbR^{n}$, we have:
\begin{align*}
||Av||^2 &= ||\sum_{k,j=1}^n \alpha_{k,j}v_j f(x_k)||^2 \stackrel{(1)}{\le} \left(\sum_{k,j=1}^n \alpha_{k,j}v_j\right)^2 = ||\alpha v ||^2 \stackrel{(2)}{\le} ||\alpha||_2^2 ||v||^2
\end{align*}
Where (1) holds with Cauchy-Schwarz inequality and because $f(\cdot)\in \bbS^{d-1}$ and (2) holds by definition of spectral $\ell_2$ norm. So we have $\forall v\in \bbR^d, ||Av||\le ||\alpha||_2 ||v||$, showing that $||A||_2 \le ||\alpha||_2$.
So we can conclude that:
\begin{align*}
\sum_{j\in J}||\mu_{\bar{u}_{j+1}} - \mu_{\bar{u}_j}||& \le \sum_{j\in J} \left(\sqrt{n}||(K_n+\lambda n\mathbf{I}_n)^{-1}||_2 \epsilon + O(n^{-1/4}) \right) = |J|||(K_n+n\lambda \mathbf{I}_n)^{-1}||_2\sqrt{n} \epsilon + O(n^{-1/4})
\end{align*}
We set $\beta_n(K_n)=\sqrt{n}||(K_n+\lambda n \mathbf{I}_n)^{-1}||_2$. In order to see that $\beta_n(K_n) = (\frac{\lambda_{min}(K_n)}{\sqrt{n}} + \sqrt{n}\lambda)^{-1}$ with $\lambda_{min}(K_n)>0$ the minimum eigenvalue of $K_n$, we apply the spectral theorem on the symmetric definite-positive kernel matrix $K_n$. Let $0<\lambda_1 \le \lambda_2\le...\le \lambda_n$ the eigenvalues of $K_n$. According to the spectral theorem, it exists $U$ an unitary matrix such that $K_n=UDU^T$ with $D=\diag(\lambda_1, ..., \lambda_n)$. So, by definition of spectral norm:
\begin{align*}
||(K_n+n\lambda \mathbf{I}_n)^{-1}||_2^2 &= \lambda_{max}\left(U(D+n\lambda \mathbf{I}_n)^{-1}U^T U(D+\lambda n\mathbf{I}_n)^{-1}U^T\right)\\
&= \lambda_{max}(U\tilde{D}U^T)\\
&= (\lambda_1 + n\lambda)^{-2}
\end{align*}
where $\tilde{D} = \diag(\frac{1}{(\lambda_1+n\lambda)^2}, ..., \frac{1}{(\lambda_n+n\lambda)^2})$. So we can conclude that $\beta_n(K_n) = (\frac{\lambda_1}{\sqrt{n}} + \sqrt{n}\lambda)^{-1}=O(1)$ for $\lambda=O(\frac{1}{\sqrt{n}})$. \\
Finally, by pooling inequalities for edges over $E$ and $E_K$, we have:
\begin{align*}
||\mu_{\bar{x}}-\mu_{\bar{x}'}|| \le 2\epsilon' |I| + |J|\beta_n(K_n) \epsilon + O(n^{-1/4})\le D (2\epsilon' + \beta_n(K_n)\epsilon) + O(n^{-1/4})
\end{align*}
We can conclude by plugging this inequality in Theorem \ref{th:downstream_gen}.
\end{proof}
\begin{theorem}
We assume \ref{hyp:extended_intra_class_connectivity} and \ref{hyp:kernel_expressivity} hold for a reproducible kernel $K_{\bar{\cX}}$ and augmentation distribution $\cA$. Let $(x_i, \bar{x}_i)_{i\in [1..n]}\sim \cA(x_i, \bar{x}_i)$ iid samples. Let $\hat{\mu}_{\bar{x}_j}=\sum_{i=1}^n \alpha_{i,j}f(x_i)$ with $\alpha_{i,j}=((K_n+\lambda \mathbf{I}_n)^{-1} K_n)_{ij}$ and $K_n=[K_{\bar{\cX}}(\bar{x}_i, \bar{x}_j)]_{i,j\in [1..n]}$. Then the empirical decoupled uniformity loss $\hat{\cL}_{unif}^d\defeq \log \frac{1}{n(n-1)} \sum_{i,j=1}^n\exp(-||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}||^2)$ verifies, for any $\epsilon'$-weak aligned encoder $f\in \cF$:
\begin{equation}
\hat{\cL}_{unif}^d - O\left(\frac{1}{n^{1/4}}\right) \le \cL_{unif}^{sup}(f) \le \hat{\cL}_{unif}^d + 4D(2\epsilon'+\beta_n(K_{\bar{\cX}})\epsilon) + O\left(\frac{1}{n^{1/4}}\right)
\end{equation}
\end{theorem}
\begin{proof}
We just need to prove that, for any $f\in \cF$, $|\cL_{unif}^d(f) - \hat{\cL}_{unif}^d(f)|\le O(n^{-1/4})$ and we can conclude through the previous theorem. We have:
\begin{align*}
|\cL_{unif}^d(f) - \hat{\cL}_{unif}^d(f)| &= \left|\log \frac{1}{n(n-1)} \sum_{i,j=1}^n\exp(-||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}||^2) - \bbE_{p(\bar{x})p(\bar{x}')}e^{-||\mu_{\bar{x}}-\mu_{\bar{x}'}||^2}\right|\\
&\le \left|\log \frac{1}{n(n-1)} \sum_{i,j=1}^n\exp(-||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}||^2) - \log\frac{1}{n(n-1)}e^{-||\mu_{\bar{x}_i}-\mu_{\bar{x}_j}||^2}\right| \\
&+ \left|\log\frac{1}{n(n-1)}e^{-||\mu_{\bar{x}_i}-\mu_{\bar{x}_j}||^2} - \bbE_{p(\bar{x})p(\bar{x}')}e^{-||\mu_{\bar{x}}-\mu_{\bar{x}'}||^2}\right|
\end{align*}
The second term in last inequality is bounded by $O(\frac{1}{\sqrt{n}})$ according to property~\ref{prop:decoupled_unif_estim}. As for the first term, we use the fact that $\log$ is $k$-Lipschitz continuous on $[e^{-4}, 1]$ and $\exp$ is $k'$-Lipschitz continuous on $[-4, 0]$ so:
\begin{align*}
\left|\log \frac{1}{n(n-1)} \sum_{i,j=1}^n e^{-||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}||^2} - \log\frac{1}{n(n-1)}e^{-||\mu_{\bar{x}_i}-\mu_{\bar{x}_j}||^2}\right| &\le \frac{k}{n(n-1)}\left| \sum_{i,j=1}^n e^{-||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}||^2} - e^{-||\mu_{\bar{x}_i}-\mu_{\bar{x}_j}||^2} \right| \\
&\le \frac{kk'}{n(n-1)}\left| \sum_{i,j=1}^n ||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}||^2 - ||\mu_{\bar{x}_i}-\mu_{\bar{x}_j}||^2 \right|
\end{align*}
Finally, we conclude using the boundness of $\hat{\mu}_{\bar{x}}$ and $\mu_{\bar{x}}$ by a constant $C$:
\begin{align*}
||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}||^2 - ||\mu_{\bar{x}_i}-\mu_{\bar{x}_j}||^2 &= (||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}|| + ||\mu_{\bar{x}_i}-\mu_{\bar{x}_j}||)(||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}|| - ||\mu_{\bar{x}_i}-\mu_{\bar{x}_j}||)\\
&\le 4C (||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}|| - ||\mu_{\bar{x}_i}-\mu_{\bar{x}_j}||)\\
&\le 4C ||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j} - (\mu_{\bar{x}_i}-\mu_{\bar{x}_j})||\\
&\le 4C(||\hat{\mu}_{\bar{x}_i}-\mu_{\bar{x}_i}|| + ||\hat{\mu}_{\bar{x}_j}-\mu_{\bar{x}_j}||)\\
&= O\left(\frac{1}{n^{-1/4}}\right)
\end{align*}
\end{proof}
\section*{Checklist}
The checklist follows the references. Please
read the checklist guidelines carefully for information on how to answer these
questions. For each question, change the default \answerTODO{} to \answerYes{},
\answerNo{}, or \answerNA{}. You are strongly encouraged to include a {\bf
justification to your answer}, either by referencing the appropriate section of
your paper or providing a brief inline description. For example:
\begin{itemize}
\item Did you include the license to the code and datasets? \answerYes{See Appendix}
\item Did you include the license to the code and datasets? \answerNo{The code and the data are proprietary.}
\item Did you include the license to the code and datasets? \answerNA{}
\end{itemize}
Please do not modify the questions and only use the provided macros for your
answers. Note that the Checklist section does not count towards the page
limit. In your paper, please delete this instructions block and only keep the
Checklist section heading above along with the questions/answers below.
\begin{enumerate}
\item For all authors...
\begin{enumerate}
\item Do the main claims made in the abstract and introduction accurately reflect the paper's contributions and scope?
\answerYes{}
\item Did you describe the limitations of your work?
\answerYes{}
\item Did you discuss any potential negative societal impacts of your work?
\answerYes{}
\item Have you read the ethics review guidelines and ensured that your paper conforms to them?
\answerYes{}
\end{enumerate}
\item If you are including theoretical results...
\begin{enumerate}
\item Did you state the full set of assumptions of all theoretical results?
\answerYes{}
\item Did you include complete proofs of all theoretical results?
\answerYes{}
\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?
\answerYes{}
\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{We only used publicly available data}
\item Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content?
\answerNA{We only used publicly available data}
\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{Introduction}
\begin{figure}[h!]
\centering
\includegraphics[width=\linewidth]{results/Contrastive_Learning_Graphs-1.png}
\caption{Illustration of the proposed method. Each point is an original image $\bar{x}$. Two points are connected if they can be transformed into the same augmented image using a distribution of augmentations $\cA$. Colors represent semantic (unknown) classes and light disks represent the support of augmentations for each sample $\bar{x}$, $\cA(\cdot|\bar{x})$.
From an incomplete augmentation graph (1) where intra-class samples are not connected (e.g. augmentations are insufficient or not adapted), we reconnect them using a kernel defined on prior information (either learnt with generative model or given as auxiliary attributes). The extended augmentation graph (3) is the union between the (incomplete) augmentation graph (1) and the kernel graph (2). In (2), the gray disk indicates the set of points $\bar{x}'$ that are close to the anchor (blue star) in the kernel space.}
\label{fig:extended_aug_graph}
\end{figure}
Contrastive Learning (CL)\cite{oord_representation_2019, bachman2019learning, becker1992self, bromley1993signature, chen_simple_2020} is a paradigm designed for representation learning which has been applied to unsupervised \cite{chen_simple_2020, chen2020improved}, weakly supervised\cite{tsai2022conditional, dufumier_contrastive_2021} and supervised problems \cite{khosla_supervised_2020}. It gained popularity during the last years by achieving impressive results in the unsupervised setting on standard vision datasets (\textit{e.g.} ImageNet) where it almost matched the performance of its supervised counterpart \cite{chen_simple_2020, he_momentum_2020}.
The objective in CL is to increase the similarity in the representation space between \textit{positive} samples (semantically close) while decreasing the similarity between semantically distinct \textit{negative} samples. Despite its simple formulation, it requires the definition of a similarity function (that can be seen as an energy term \cite{lecun2005loss}), positives and negatives. Similarity functions are defined on latent representations of an encoder $f\in \cF$ (CNN \cite{chen_big_2020} or Transformer~\cite{caron2021emerging} for vision datasets) and and is usually expressed as a Euclidean scalar product (\textit{e.g.} InfoNCE\cite{oord_representation_2019}).
In supervised learning~\cite{khosla_supervised_2020}, positives are simply images belonging to the same class while negatives are images belonging to different classes. In unsupervised learning~\cite{chen_simple_2020}, since labels are unknown, positives are usually defined as transformed versions (\textit{views}) of the same original image (a.k.a. the anchor) and negatives are the transformed versions of all other images. As a result, the augmentation distribution $\cA$ used to sample both positives and negatives is crucial~\cite{chen_simple_2020} and it conditions the quality of the learnt representation. The most-used augmentations for visual representations involve aggressive crop and color distortion. Cropping induces representations with high occlusion invariance~\cite{purushwalkam2020demystifying} while color distortion may avoids the encoder $f$ to take a shortcut \cite{chen_simple_2020} while aligning positive sample representations and fall into the simplicity bias \cite{shah2020pitfalls}.
Nevertheless, learning a representation that mainly relies on augmentations comes at a cost: both crop and color distortion induce strong biases in the final representation~\cite{purushwalkam2020demystifying}. Specifically, dominant objects inside images can prevent the model from learning features of smaller objects~\cite{chen_intriguing_2021} (which is not apparent in object-centric datasets such as ImageNet) and few, irrelevant and easy-to-learn features, that are shared among views, are sufficient to collapse the representation~\cite{chen_intriguing_2021} (a.k.a feature suppression).
Finding the right augmentations in other visual domains, such as medical imaging, remains an open challenge~\cite{dufumier_contrastive_2021} since the anatomical differences between two classes (e.g., pathological and healthy) can be quite subtle and difficult to capture with usual transformations.
If the augmentations are too weak or inadequate to remove irrelevant signal w.r.t. a discrimination task, then how can we define positive samples?
In our work, we propose to integrate \textit{prior information}, learnt from generative models or given as auxiliary attributes, into contrastive learning, to make it less dependent on data augmentation. Using the theoretical understanding of CL through the augmentation graph, we make the connection with kernel theory and introduce a novel loss with theoretical guarantees on downstream performance. Prior information is integrated into the proposed contrastive loss using a kernel. In the unsupervised setting, we leverage pre-trained generative models, such as GAN~\cite{goodfellow2014generative} and VAE~\cite{kingma2013auto}, to learn \textit{a prior representation} of the data. We provide a
solution to the feature suppression issue in CL~\cite{chen_intriguing_2021} and also demonstrate SOTA results with weaker augmentations on visual benchmarks. In the weakly supervised setting, we use instead auxiliary/prior information, such as image attributes (e.g. birds color or size) and we show better performance than previous conditional formulations based on these attributes~\cite{tsai2022conditional}.
In summary, we make the following contributions:
\phantom{x} 1. We propose a new framework for contrastive learning allowing the integration of prior information, learnt from generative models or given as auxiliary attributes, into the positive sampling\\
\phantom{x} 2. We derive theoretical bounds on the downstream classification risk that rely on weaker assumptions for data augmentations than previous works on CL\\
\phantom{x} 3. We empirically show that our framework can benefit from the latest advances of generative models to learn a better representation while relying on less augmentations\\
\phantom{x} 4. We show that we achieve SOTA results in the unsupervised and weakly supervised setting
\section{Related Works}
In a weakly supervised setting, recent studies~\cite{dufumier_contrastive_2021, tsai2022conditional} have shown that positive samples can be defined conditionally to an auxiliary attribute in order to improve the final representation, in particular for medical imaging \cite{dufumier_contrastive_2021}. From an information bottleneck perspective, these approaches essentially compress the representation to be only predictive of the auxiliary attributes. This might harm the performance of the model when these attributes are too noisy to accurately approximate the true semantic labels for a given downstream task. Furthermore, the benefit of adding data augmentations when conditioning with respect to these attributes is not theoretically discussed.
In an unsupervised setting, recent approaches \cite{dwibedi2021little, zheng2021weakly, zheng2021ressl, li2020prototypical} used the encoder $f$, learnt during optimization, to extend the positive sampling procedure to other views of different instances (\textit{i.e.} distinct from the anchor) that are close to the anchor in the latent space. In order to avoid representation collapse, a support set~\cite{dwibedi2021little}, a momentum encoder~\cite{li2020prototypical} or another small network~\cite{zheng2021weakly} can be used to select the positive samples. In clustering approaches~\cite{li2020prototypical, caron2020unsupervised}, distinct instances with close semantics are attracted in the latent space using prototypes. These prototypes can be estimated through K-means~\cite{li2020prototypical} or Sinkhorn-Knopp algorithm~\cite{caron2020unsupervised}. All these methods rely on the past representation of a network to improve the current one.
They require strong augmentations and they essentially assume that the closest points in the representation space belong to the same latent class in order to to better select the positives. This inductive bias is still poorly understood theoretically~\cite{saunshi2022understanding} and may depend on the visual domain.
Our work also relates to generative models for learning representations. VAE~\cite{kingma2013auto} learns the data distribution by mapping each input to a Gaussian distribution that we can easily sample to reconstruct the original image. GAN~\cite{goodfellow2014generative} instead sample directly from a Gaussian distribution to generate images that are classified by a discriminator in a min-max game. The discriminator representation can then be used~\cite{radford2015unsupervised} as feature extractor. Other models (ALI~\cite{dumoulin2016adversarially}, BiGAN~\cite{donahue2016adversarial} and BigBiGAN\cite{donahue2019large}) learn simultaneously a generator and an encoder that can be used directly for representation learning. All these models do not require particular augmentations to model the data distribution but they perform generally poorer than recent discriminative approaches~\cite{chen_big_2020} for representation learning. A first connection between generative models and contrastive learning has emerged very recently~\cite{jahanian2021generative}. In~\cite{jahanian2021generative}, authors study the feasibility of learning effective visual representations using only generated samples, and not real ones, with a contrastive loss. Their empirical analysis is complementary to our work. Here, we leverage the representation capacity of the generative models, rather than their generative power, to learn prior representation of the data.
\section{Constrastive Learning with Decoupled Uniformity}
\subsection{Problem setup}
The general problem in contrastive learning is to learn a data representation using an encoder $f\in \cF: \cX \rightarrow \bbS^{d-1}$ that is pre-trained with a set of $n$ original samples $(\bar{x}_i)_{i\in [1..n]}\in \bar{\cX}$, sampled from the data distribution $p(\bar{x})$\footnote{With an abuse of notation, we define it as $p(\bar{x})$ instead than $p_{\bar{X}}$ to simplify the presentation, as it is common in the literature}
These samples are transformed to generate \textit{positive samples} (\textit{i.e.}, semantically similar to $\bar{x}$) in $\cX$, space of augmented images, using a distribution of augmentations $\cA(\cdot |\bar{x})$. Concretely, for each $\bar{x}_i$, we can sample views of $\bar{x}_i$ using $x\sim \cA(\cdot |\bar{x}_i)$ (\textit{e.g.}, by applying color jittering, flip or crop with a given probability). For consistency, we assume $\cA(\bar{x})=p(\bar{x})$ so that the distributions $\cA(\cdot |\bar{x})$ and $p(\bar{x})$ induce a marginal distribution $p(x)$ over $\cX$. Given an anchor $\bar{x}_i$, all views $x\sim\cA(\cdot |\bar{x}_j)$ from different samples $\bar{x}_{j\neq i}$ are considered as \textit{negatives}.
Once pre-trained, the encoder $f$ is fixed and its representation $f(\bar{\cX})$ is evaluated through linear evaluation on a classification task using a labeled dataset $\cD=\{(\bar{x}_i, y_i)\}\in \bar{\cX}\times \cY$ where $\cY=[1..K]$, with $K$ the number of classes.\\
\textbf{Linear evaluation.} To evaluate the representation of $f$ on a classification task,
we train a linear classifier $g(\bar{x})=Wf(\bar{x})$ ($f$ is fixed) that minimizes the multi-class classification error.
\subsection{Objective}
The popular InfoNCE loss~\cite{poole_variational_2019, oord_representation_2019}, often used in CL, imposes 1) alignment between positives and 2) uniformity between the views ($x \overset{\text{i.i.d.}}{\sim} \cA(\cdot|\bar{x})$) of all instances $\bar{x}$~\cite{wang_understanding_2020}-- two properties that correlate well with downstream performance. However, by imposing uniformity between \textit{all} views, we essentially try to both attract (alignment) and repel (uniformity) positive samples and therefore we cannot achieve a perfect alignment \textit{and} uniformity, as noted in~\cite{wang_understanding_2020}. Moreover, InfoNCE has been originally designed for only two views (i.e., one couple of positive) and its extension to multiple views is not straightforward.
Previous works have proposed a solution to either the first~\cite{tian_contrastive_2020} or second~\cite{yeh2021decoupled} issue. Here, we propose a modified version of the uniformity loss, presented in ~\cite{wang_understanding_2020}, that solves both issues since it: i) decouples positives from negatives, similarly to~\cite{yeh2021decoupled} and ii) is generalizable to multi-views as in~\cite{tian_contrastive_2020}. We introduce the Decoupled Uniformity loss as:
\begin{equation}
\cL_{unif}^d(f) = \log \bbE_{p(\bar{x})p(\bar{x}')}e^{-||\mu_{\bar{x}}-\mu_{\bar{x}'}||^2}
\label{def:decoupled_unif}
\end{equation}
where $\mu_{\bar{x}}=\bbE_{\cA(x|\bar{x})}f(x)$ is called a \textit{centroid} of the views of $\bar{x}$. This loss essentially repels distinct centroids $\mu_{\bar{x}}$ through an average pairwise Gaussian potential. Interestingly, it implicitly optimizes alignment between positives through the maximization of $||\mu_{\bar{x}}||$\footnote{By Jensen's inequality $||\mu_{\bar{x}}||\le\bbE_{\cA(x|\bar{x})}||f(x)||=1$ with equality iff $f$ is constant on $\supp\cA(\cdot|\bar{x})$.}, so we do not need to explicitly add an alignment term. It can be shown (see Appendix), that minimizing this loss brings to a representation space where the sum of similarities between views of the same sample is greater than the sum of similarities between views of different samples. From a physics point-of-view, we are trying to find the equilibrium state of $|\bar{\cX}|$ particles linked with a pair Gaussian potential energy. We will study its main properties hereafter and we will see that \textit{prior} information can be added during the estimation step of these centroids.
\subsection{Geometrical Analysis of Decoupled Uniformity}
\begin{definition}(Finite-samples estimator)
For $n$ samples $(\bar{x}_i)_{i\in [1..n]}\overset{i.i.d.}{\sim} p(\bar{x})$, the (biased) empirical estimator of $\cL_{unif}^d(f)$ is: $\hat{\cL}_{unif}^d(f) = \log \frac{1}{n(n-1)}\sum_{i\neq j} e^{-||\mu_{\bar{x}_i} - \mu_{\bar{x}_j}||^2}$. It converges to $\cL_{unif}^d(f)$ with rate $O\left(\frac{1}{\sqrt{n}}\right)$. Proof in Appendix
\end{definition}
\begin{theorem}(Optimality of Decoupled Uniformity)
Given $n$ points $(\bar{x}_i)_{i\in [1..n]}$ such that $n\le d+1$, any optimal encoder $f^*$ minimizing $\hat{\cL}_{unif}^d$ achieves a representation s.t.:\\
1. (Perfect uniformity) All centroids $(\mu_{\bar{x}_i})_{i\in [1..n]}$ make a regular simplex on the hyper-sphere $\bbS^{d-1}$\\
2. (Perfect alignment) $f^*$ is perfectly aligned, i.e $\forall x, x'\sim \cA(\cdot|\bar{x}_i), f^*(x)=f^*(x')$ for all $i\in [1..n]$.\\
Proof in Appendix.
\label{th:optimal_decoupled_unif}
\end{theorem}
Theorem~\ref{th:optimal_decoupled_unif} gives a complete geometrical characterization when the batch size $n$ set during training is not too large compared to the representation space dimension $d$. By removing the coupling between positives and negatives, we see that Decoupled Uniformity can realize both perfect alignment and uniformity, contrary to InfoNCE.\\
\textbf{Remark.} The assumption $n \le d+1$ is crucial to have the existence of a regular simplex on the hypersphere $\bbS^{d-1}$. In practice, this condition is not always full-filled (e.g SimCLR~\cite{chen_simple_2020} with $d=128$ and $n=4096$). Characterizing the optimal solution of $\cL_{unif}^d$ for any $n>d+1$ is still an open problem \cite{borodachov2019discrete} but theoretical guarantees can be obtained in the limit case $n\rightarrow \infty$ (see below).
\begin{theorem}(Asymptotical Optimality)
When the number of samples is infinite $n\rightarrow \infty$, then for any perfectly aligned encoder $f\in \cF$ that minimizes $\mathcal{L}_{unif}^d$, the centroids $\mu_{\bar{x}}$ for $\bar{x}\sim p(\bar{x})$ are uniformly distributed on the hypersphere $\bbS^{d-1}$. Proof in Appendix.
\end{theorem}
Empirically, we observe that minimizers $f$ of $\hat{\cL}_{unif}^d$ remain well-aligned when $n>d+1$ on real-world vision datasets (see Appendix). Decoupled uniformity thus optimizes two properties that are nicely correlated with downstream classification performance~\cite{wang_understanding_2020}--that is alignment and uniformity between centroids. However, as noted in~\cite{wang2022chaos, saunshi2022understanding}, optimizing these two properties is necessary but not sufficient to guarantee a good classification accuracy. In fact, the accuracy can be arbitrary bad even for perfectly aligned and uniform encoders~\cite{saunshi2022understanding}.
Most recent theories about CL~\cite{wang2022chaos, haochen2021provable} make the
hypothesis that samples from the same semantic class have overlapping augmented views to provide guarantees on the downstream task when optimizing InfoNCE \cite{chen_simple_2020} or Spectral Contrastive loss \cite{haochen2021provable}. This assumption, known as intra-class connectivity hypothesis, is very strong and only relies on the augmentation distribution $\cA$. In particular, augmentations should not be "too weak", so that all intra-class samples are connected among them, and at the same time not "too strong", to prevent connections between inter-class samples and thus preserve the semantic information. Here, we prove that we can relax this hypothesis if we can provide a kernel (viewed as a similarity function between original samples $\bar{x}$) that is "good enough" to relate intra-class samples not connected by the augmentations (see Fig.~\ref{fig:extended_aug_graph}). In practice, we show that generative models can define such kernel.
We first recall the definition of the augmentation graph~\cite{wang2022chaos}, and intra-class connectivity hypothesis before presenting our main theorems. For simplicity, we assume that the set of images $\bar{\cX}$ is finite (similarly to~\cite{wang2022chaos, haochen2021provable}). Our bounds and theoretical guarantees will never depend on the cardinality $|\bar{\cX}|$.
\subsection{Intra-class connectivity hypothesis}
\begin{definition}(Augmentation graph~\cite{haochen2021provable, wang2022chaos})
Given a set of original images $\bar{\cX}$, we define the augmentation graph $G_{\cA}(V, E)$ for an augmentation distribution $\cA$ through 1) a set of vertices $V=\bar{\cX}$ and 2) a set of edges $E$ such that $(\bar{x},\bar{x}')=e\in E$ if the two original images $\bar{x}, \bar{x}'$ can be transformed into the same augmented image through $\cA$, i.e $\supp\cA(\cdot |\bar{x})\cap \supp \cA(\cdot |\bar{x}') \neq \emptyset$.
\end{definition}
Previous analysis in CL make the hypothesis that it exists an optimal (accessible) augmentation module $\cA^*$ that fulfills:
\begin{assumption}(Intra-class connectivity \cite{wang2022chaos})
For a given downstream classification task $\cD=\bar{\cX}\times \cY \quad \forall y\in \cY$, the augmentation subgraph, $G_y\subset G_{\cA^*}$ containing images only from class $y$, is connected.
\label{hyp:embed_intra_class_connect}
\end{assumption}
Under this hypothesis, Decoupled Uniformity loss can also tightly bound the downstream supervised risk for a bigger class of encoders than prior work~\cite{wang2022chaos}. To show it, we define a measure of the risk on a downstream task $\cD$. While previous analysis~\cite{wang2022chaos, arora_theoretical_2019} generally used the mean cross-entropy loss (as it has closer analytic form with InfoNCE), we use a supervised loss closer to decoupled uniformity with the same guarantees as the mean cross-entropy loss (see Appendix). Notably, the geometry of the representation space at optimum is the same as cross-entropy and SupCon~\cite{khosla_supervised_2020} and we can theoretically achieve perfect linear classification.
\begin{definition}(Downstream supervised loss)
For a given downstream task $\cD = \bar{\cX} \times \cY$, we define the classification loss as: $\mathcal{L}_{sup}(f) = \log \bbE_{y, y'\sim p(y)p(y')}e^{-||\mu_y - \mu_{y'}||^2}$, where $\mu_y = \bbE_{p(\bar{x}|y)} \mu_{\bar{x}}$.
\end{definition}
\paragraph{Remark.} This loss depends on centroids $\mu_{\bar{x}}$ rather than $f(\bar{x})$. Empirically, it has been shown~\cite{foster2020improving} that performing feature averaging gives better performance on the downstream task.
\begin{definition}(Weak-aligned encoder)
An encoder $f\in \cF$ is $\epsilon'$-weak ($\epsilon'\ge0$) aligned on $\cA$ if:
\begin{equation*}
||f(x)-f(x')||\le \epsilon' \quad \quad \forall \bar{x}\in \bar{\cX}, \forall x,x' \overset{i.i.d.}{\sim} \cA(\cdot|\bar{x})
\end{equation*}
\end{definition}
\begin{theorem} (Guarantees with $\cA^*$)
Given an optimal augmentation module $\cA^*$, for any $\epsilon$-weak aligned encoder $f\in \cF$ we obtain: $\cL_{unif}^d(f) \le \cL_{sup}(f) \le 8D\epsilon + \cL_{unif}^{d}(f)$ where $D$ is the maximum diameter of all intra-class graphs $G_y$ ($y\in \cY$). Proof in the Appendix.
\label{th:boundness_intra_class_hyp}
\end{theorem}
In practice, the diameter $D$ can be controlled by a small constant in some cases~\cite{wang2022chaos} (typically $\le 4$) but it remains specific to the dataset at hand. Furthermore, we observe (see Appendix) that $f$ realizes alignment with small error $\epsilon$ during optimization of $\cL_{unif}^d(f)$ for augmentations close to the sweet spot $\cA^*$~\cite{tian_contrastive_2020} on CIFAR-10 and CIFAR-100.
In the next section, we study the case when $\cA^*$ is not accessible or very hard to find.
\section{Reconnect the disconnected: extending the augmentation graph with kernel}
Having access to optimal augmentations is a strong assumption and, for many real-world applications (e.g medical imaging~\cite{dufumier_contrastive_2021}), it may not be accessible. If we have only weak augmentations (\textit{e.g.}, $\supp\cA(\cdot |\bar{x}) \subsetneq \supp\cA^*(\cdot|\bar{x})$ for any $\bar{x}$), then some intra-class points might not be connected and we would need to reconnect them to ensure good downstream accuracy (see Theorem~\ref{th:downstream_gen} in Appendix).
Augmentations are intuitive and they have been hand-crafted for decades by using human perception (\textit{e.g.}, a rotated chair remains a chair and a gray-scale dog is still a dog). However, we may know other \textit{prior information} about objects that are difficult to transfer through invariance to augmentations (\textit{e.g.}, chairs should have 4 legs). This prior information can be either given as image attributes (\textit{e.g.}, age or sex of a person, color of a bird, etc.) or, in an unsupervised setting, directly learnt through a generative model (\textit{e.g.}, GAN or VAE). Now, we ask: how can we integrate this information inside a contrastive framework to reconnect intra-class images that are actually disconnected in $G_{\cA}$?
We rely on conditional mean embedding theory and use a kernel defined on the prior representation/information. This allows us to estimate a better configuration of the centroids in the representation space, with respect to the downstream task, and, ultimately, provide theoretical guarantees on the classification risk.
\subsection{$\epsilon$-Kernel Graph}
\begin{definition}(RKHS on $\bar{\cX}$)
We define the RKHS $(\cH_{\bar{\cX}}, K_{\bar{\cX}})$ on $\bar{\cX}$ associated with a kernel $K_{\bar{\cX}}$.
\end{definition}
\textbf{Example.} If we work with large natural images, assuming that we know a prior $z(\bar{x})$ about our images (\textit{e.g.}, given by a generative model), we can compute $K_{\bar{\cX}}$ using $z$ through $K_{\bar{\cX}}(\bar{x}, \bar{x}')=\tilde{K}(z(\bar{x}), z(\bar{x}'))$ where $\tilde{K}$ is a standard kernel (\textit{e.g.}, Gaussian or Cosine).
To link kernel theory with the previous augmentation graph, we need to define a \textit{kernel graph} that connects images with high similarity in the kernel space.
\begin{definition}($\epsilon$-Kernel graph)
Let $\epsilon>0$. We define the $\epsilon$-kernel graph $G_{K_{\bar{\cX}}}^\epsilon(V, E_K)$ for the kernel $K_{\bar{\cX}}$ on $\bar{\cX}$ through 1) a set of vertices $V=\bar{\cX}$ and 2) a set of edges $E_{K_{\bar{\cX}}}$ such that $e\in E_{K_{\bar{\cX}}}$ between $\bar{x}, \bar{x}'\in \bar{\cX}$ iff $\max(K(\bar{x}, \bar{x}), K(\bar{x}', \bar{x}')) - K(\bar{x}, \bar{x}')\le \epsilon$.
\end{definition}
The condition $\max(K(\bar{x}, \bar{x}), K(\bar{x}', \bar{x}')) - K(\bar{x}, \bar{x}')\le \epsilon$ implies that $d_K(\bar{x}, \bar{x}')\le 2\epsilon$ where $d_K(\bar{x}, \bar{x}') = K(\bar{x}, \bar{x}) + K(\bar{x}', \bar{x}')-2K(\bar{x}, \bar{x'})$ is the kernel distance. For kernels with constant norm (\textit{e.g.}, the standard Gaussian, Cosine or Laplacian kernel), it is in fact an equivalence. Intuitively, it means that we connect two original points in the kernel graph if they have small distance in the kernel space.
We give now our main assumption to derive a better estimator of the centroid $\mu_{\bar{x}}$ in the insufficient augmentation regime.
\begin{assumption}(Extended intra-class connectivity)
For a given task $\cD=\bar{\cX} \times \cY$, the extended graph $\tilde{G}=G_{\cA} \cup G_{K_{\bar{\cX}}}^\epsilon = (V, E\cup E_{K_{\bar{\cX}}})$ (union between augmentation graph and $\epsilon$-kernel graph) is class-connected for all $y\in \cY$.
\label{hyp:extended_intra_class_connectivity}
\end{assumption}
This assumption is notably weaker than Assumption~\ref{hyp:embed_intra_class_connect} w.r.t augmentation distribution $\cA$. Here, we do not need to find the optimal distribution $\cA^*$ as long as we have a kernel $K_{\bar{\cX}}$ such that disconnected points in the augmentation graph are connected in the $\epsilon$-kernel graph. If $K$ is not well adapted to the data-set (i.e it gives very low values for intra-class points), then $\epsilon$ needs to be large to re-connect these points and we will see that the classification error will be high. In practice, this means that we need to tune the hyper-parameter of the kernel (i.e., $\sigma$ for a RBF kernel) so that all intra-class points are reconnected with a small $\epsilon$.
\subsection{ Conditional Mean Embedding}
Decoupled Uniformity loss includes no kernel in its raw form. It only depends on centroids $\mu_{\bar{x}}=\bbE_{\cA(x|\bar{x})} f(x)$.
Here, we show that another consistent estimator of these centroids can be defined, using the previous kernel $K_{\bar{\cX}}$. To show it, we \textbf{fix} an encoder $f\in \cF$ and require the following technical assumption in order to apply conditional mean embedding theory~\cite{song2013kernel, klebanov2020rigorous}.
\begin{assumption}(Expressivity of $K_{\bar{\cX}}$)
The (unique) RKHS $(\cH_{f}, K_{f})$ defined on $\cX$ with kernel $K_{f} = \langle f(\cdot), f(\cdot)\rangle_{\bbR^d}$ fulfills $\forall g\in \cH_{f}, \bbE_{\cA(x|\cdot)}g(x) \in \cH_{\bar{\cX}}$
\label{hyp:kernel_expressivity}
\end{assumption}
\begin{theorem}(Centroid estimation)
Let $(x_i, \bar{x}_i)_{i\in [1..n]}\overset{iid}{\sim} \cA(x, \bar{x})$. Assuming~\ref{hyp:kernel_expressivity}, a consistent estimator of the centroid is:
\begin{align}
\forall \bar{x}\in \bar{\cX}, \hat{\mu}_{\bar{x}} = \sum_{i=1}^n \alpha_i(\bar{x}) f(x_i)
\end{align}
where $\alpha_i(\bar{x})=\sum_{j=1}^n [(K_n+n\lambda\mathbf{I}_n)^{-1}]_{ij}K_{\bar{\cX}}(\bar{x}_j, \bar{x})$ and $K_n=[K_{\bar{\cX}}(\bar{x}_i, \bar{x}_j)]_{i,j\in [1..n]}$. It converges to $\mu_{\bar{x}}$ with the $\ell_2$ norm at a rate $O(n^{-1/4})$ for $\lambda=O(\frac{1}{\sqrt{n}})$. Proof in the Appendix.
\label{th:cond_mean_embed_estim}
\end{theorem}
\textbf{Intuition.} This theorem says that we can use
representations of images close to an anchor $\bar{x}$, according to our prior information, to accurately estimate $\mu_{\bar{x}}$. Consequently, if
the prior is "good enough" to connect intra-class images disconnected in the augmentation graph (i.e. fulfills Assumption \ref{hyp:extended_intra_class_connectivity}), then this estimator allows us to tightly control the classification risk .
From this theorem, we naturally derive the empirical Kernel Decoupled Uniformity loss using the previous estimator.
\begin{definition}(Empirical Kernel Decoupled Uniformity Loss)
Let $(x_i, \bar{x}_i)_{i\in [1..n]}\overset{iid}{\sim} \cA(x, \bar{x})$. Let $\hat{\mu}_{\bar{x}_j}=\sum_{i=1}^n \alpha_{i,j}f(x_i)$ with $\alpha_{i,j}=((K_n+\lambda n \mathbf{I}_n)^{-1} K_n)_{ij}$, $\lambda=O(\frac{1}{\sqrt{n}})$ a regularization constant and $K_n=[K_{\bar{\cX}}(\bar{x}_i, \bar{x}_j)]_{i,j\in [1..n]}$. We define the empirical kernel decoupled uniformity loss as:
\begin{equation}
\hat{\cL}_{unif}^d(f)\defeq \log \frac{1}{n(n-1)} \sum_{i,j=1}^n\exp(-||\hat{\mu}_{\bar{x}_i}-\hat{\mu}_{\bar{x}_j}||^2)
\end{equation}
\end{definition}
\paragraph{Extension to multi-views.} If we have $V$ views $(x_i^{(v)})_{v\in [1..V]}$ for each $\bar{x}_i$, we can easily extend the previous estimator with $\hat{\mu}_{\bar{x}_i}=\frac{1}{V}\sum_{v=1}^V \hat{\mu}_{\bar{x}_j}^{(v)}$ where $\hat{\mu}_{\bar{x}_j}=\sum_{i=1}^n \alpha_{i,j}f(x_i^{(v)})$.
The computational cost added is roughly $O(n^3)$ (to compute the inverse matrix of size $n\times n$) but it remains negligible compared to the back-propagation time using classical stochastic gradient descent. Importantly, the gradients associated to $\alpha_{i,j}$ are not computed.
\subsection{Contrastive Learning with Kernel}
We show here that $\hat{\cL}_{unif}^d(f)$ can tightly bound the supervised classification risk for well-aligned encoders $f\in \cF$.
\begin{theorem}
We assume \ref{hyp:extended_intra_class_connectivity} and \ref{hyp:kernel_expressivity} hold for a reproducible kernel $K_{\bar{\cX}}$ and augmentation distribution $\cA$. Let $(x_i, \bar{x}_i)_{i\in [1..n]}\overset{iid}{\sim} \cA(x, \bar{x})$. For any $\epsilon'$-weak aligned encoder $f\in \cF$:
\begin{equation}
\hat{\cL}_{unif}^d(f) - O\left(\frac{1}{n^{1/4}}\right) \le \cL_{sup}(f) \le \hat{\cL}_{unif}^d(f)+ 4D(2\epsilon'+\beta_n(K_{\bar{\cX}})\epsilon) + O\left(\frac{1}{n^{1/4}}\right)
\end{equation}
where $\beta_n(K_{\bar{\cX}}) = (\lambda_{min}(K_n) + \sqrt{n}\lambda)^{-1} =O(1)$ for $\lambda= O(\frac{1}{\sqrt{n}})$, $K_n=(K_{\bar{\cX}}(\bar{x}_i, \bar{x}_j))_{i,j\in [1..n]}$and $D$ is the maximal diameter of all sub-graphs $\tilde{G}_y\subset \tilde{G}$ where $y\in \cY$. We noted $\lambda_{min}(K_n)>0$ the minimal eigenvalue of $K_n$.
\label{th:final_bound_decoupled}
\end{theorem}
\textbf{Interpretation.} Theorem \ref{th:final_bound_decoupled} gives a tight bound on the classification loss $\cL_{sup}(f)$ with few assumptions. In the special case $\epsilon=0$ and $\cA=\cA^*$ (i.e the augmentation graph is class-connected, a stronger assumption than~\ref{hyp:extended_intra_class_connectivity}), we retrieve the standard bounds of Theorem~\ref{th:boundness_intra_class_hyp}. As before, we don't require perfect alignment for $f\in \cF$ and we don't have class collision term (even if the extended augmentation graph may contain edges between inter-class samples), contrarily to \cite{arora_theoretical_2019}. Also, the estimation error doesn't depend on the number of views (which is low in practice))--as it was always the case in previous formulations~\cite{wang2022chaos, arora_theoretical_2019, haochen2021provable} -- but rather on the batch size $n$.
Contrarily to CCLK~\cite{tsai2022conditional}, we don't condition our representation to weak attributes but rather we provide better estimation of the conditional mean embedding conditionally to the original image. Our loss remains in an unconditional contrastive framework driven by the augmentations $\cA$ and the prior $K_{\bar{\cX}}$ on input images.
\section{Experiments}
Here, we study several problems where current contrastive frameworks fail at learning robust visual representations. In unsupervised learning, we show that we can leverage generative models to outperform current self-supervised models when the augmentations are insufficient to remove irrelevant signal from images. In weakly supervised, we demonstrate the superiority of our unconditional formulation when noisy auxiliary attributes are available. Implementation details in Appendix.
\subsection{Generative models as prior - Evading feature suppression}
Previous investigations~\cite{chen_intriguing_2021} have shown that a few easy-to-learn irrelevant features not removed by augmentations can prevent the model from learning all semantic features inside images. We propose here a first solution to this issue.\\
\textbf{RandBits dataset~\cite{chen_intriguing_2021}.} We build a RandBits dataset based on CIFAR-10. For each image, we add a random integer sampled in $[0, 2^k-1]$ where $k$ is a controllable number of bits. To make it easy to learn, we take its binary representation and repeat it to define $k$ channels that are added to the original RGB channels. Importantly, these channels will not be altered by augmentations, so they will be shared across views. We train a ResNet18 on this dataset with standard SimCLR augmentations~\cite{chen_simple_2020} and varying $k$. For kernel decoupled uniformity, we use a $\beta$-VAE representation (ResNet18 backbone, $\beta=1$) to define $K_{VAE}(\bar{x},\bar{x}')=K(\mu(\bar{x}), \mu(\bar{x}'))$ where $\mu(\cdot)$ is the mean Gaussian distribution of $\bar{x}$ in the VAE latent space and $K$ is a standard RBF kernel.
\begin{table}[h!]
\begin{adjustbox}{max width=\textwidth}
\begin{tabular}{c c c c c}
\toprule
Loss & 0 bits & 5 bits & 10 bits & 20 bits\\
\midrule
SimCLR~\cite{chen_simple_2020} & 79.4 & 68.74 & 13.67 & 10.07 \\
BYOL~\cite{grill2020bootstrap} & 80.14 & 19.98 & 10.33 & 10.00 \\
$\beta$-VAE ($\beta=1$) & 41.37 & 43.32 & 42.94 & 43.1 \\
$\beta$-VAE ($\beta=2$) & 42.28 & 43.89 & 43.11 & 42.19 \\
$\beta$-VAE ($\beta=4$) & 42.5 & 42.5 & 42.5 & 39.87 \\
Decoupled Unif (ours) & 82.43 & 53.45 & 10.08 & 9.64 \\
$K_{VAE}$ Decoupled Unif (ours) & $\textbf{82.74}_{\pm 0.18}$ & $\textbf{68.75}_{\pm 0.24}$ & $\textbf{68.42}_{\pm 0.51}$ & $\textbf{68.58}_{\pm 0.17}$ \\
\bottomrule
\end{tabular}
\end{adjustbox}
\caption{Linear evaluation accuracy (in $\%$) after training on RandBits-CIFAR10 with ResNet18 for 200 epochs. For VAE, we also use a ResNet18 backbone. Once trained, we use its representation to define the kernel $K_{VAE}$ in kernel decoupled uniformity loss.}
\vspace{-0.5cm}
\label{tab:randbits_main}
\end{table}
\begin{minipage}{0.60\textwidth}
Table~\ref{tab:randbits_main} shows the linear evaluation accuracy computed on a fixed encoder trained with various contrastive (SimCLR, Decoupled Uniformity and Kernel Decoupled Uniformity) and non-contrastive (BYOL and $\beta$-VAE) methods. As noted previously~\cite{chen_intriguing_2021}, $\beta$-VAE is the only method insensitive to the number of added bits, but its representation quality remains low compared to other discriminative approaches. All contrastive approaches fail for $k\ge 10$ bits. This can be explained by noticing that, as the number of bits $k$ increases, the number of edges between intra-class images in the augmentation graph $G_{\cA}$ decreases. For $k$ bits, on average $N/2^k$ images share the same random bits ($N=50000$ is the dataset size). So only these images can be connected in $G_{\cA}$. For $k=20$ bits, $<1$ image share the same bits which means that they are almost all disconnected, and it explains why standard contrastive approaches fail. Same trend is observed for non-contrastive approaches (\textit{e.g.} BYOL) with a degradation in performance even faster than SimCLR. Interestingly, encouraging a disentangled representation by imposing higher $\beta>1$ in $\beta$-VAE does not help. Only our $K_{VAE}$ Decoupled Uniformity loss obtains good scores, regardless of the number of bits.
\end{minipage}\hfill
\begin{minipage}{0.35\textwidth}
\includegraphics[width=\linewidth]{results/eps_vs_accuracy.png}
\captionof{figure}{Empirical verification of our theory. The optimal $\epsilon^*$ to add 100 edges between intra-class images is correlated with the downstream accuracy, as suggested by Theorem~\ref{th:final_bound_decoupled}. We use $k=20$ bits and an RBF kernel.}
\label{fig:eps_vs_accuracy}
\end{minipage}
\subsubsection{Towards weaker augmentations}
Color distortion (including color jittering and gray-scale) and crop are the two most important augmentations for SimCLR and other contrastive models to ensure a good representation on ImageNet~\cite{chen_simple_2020}. Whether they are best suited for other datasets (e.g medical imaging~\cite{dufumier_contrastive_2021} or multi-objects images~\cite{chen_intriguing_2021}) is still an open question. Here, we ask: can generative models remove the need for such strong augmentations ?
We use standard benchmarking datasets (CIFAR-10, CIFAR-100 and STL-10) and we study the case where augmentations are too weak to connect all intra-class points. We use a trained VAE to define $K_{VAE}$ as before and a trained DCGAN~\cite{radford2015unsupervised} $K_{GAN}(\bar{x}, \bar{x}')\defeq K(z(\bar{x}), z(\bar{x}'))$ where $z(\cdot)$ denotes the discriminator output of the penultimate layer.
\begin{table}[h!]
\centering
\begin{adjustbox}{max width=\textwidth}
\begin{tabular}{c c c c c c c c}
\toprule
Loss & \multicolumn{2}{c}{CIFAR-10} & \multicolumn{2}{c}{CIFAR-100} & \multicolumn{2}{c}{STL-10} \\
& w/o Color & w/o Color+Crop & w/o Color & w/o Color+Crop & w/o Color & w/o Color+Crop\\
\midrule
SimCLR~\cite{chen_simple_2020} & 62.56 & 34.07 & 38.27 & 15.28 & 59.01 & 39.56 \\
BYOL~\cite{grill2020bootstrap} & 64.86 & 45.88 & 35.61 & 22.48 & 65.36 & 11.28 \\
VAE$^*$~\cite{kingma2013auto} & 41.37 & 41.37 & 14.34 & 14.34 & 42.17 & 42.17 \\
DCGAN$^*$~\cite{radford2015unsupervised}& 66.71 & 66.71 & 26.17 & 26.17 & 70.06 & \textbf{70.06} \\
Decoupled Unif & 60.45 & 39.18 & 34.16 & 14.58 & 54.53 & 36.81 \\
$K_{VAE}$ Decoupled Unif & 72.92 & 50.52 & 45.59 & 28.24 & 61.39 & 45.64 \\
$K_{GAN}$ Decoupled Unif & \textbf{77.16} & \textbf{69.19} & \textbf{50.07} & \textbf{35.98} & \textbf{71.44} & 68.11 \\
\bottomrule
\end{tabular}
\end{adjustbox}
\caption{When augmentation overlap hypothesis is not full-filled, generative models can provide a good kernel to connect intra-class points not connected by augmentations. $^*$ For VAE and DCGAN, we did not use augmentations during training since they model the true data distribution.}
\label{tab:insufficient_data_aug}
\end{table}
In Table~\ref{tab:insufficient_data_aug}, we observe that our contrastive framework with DCGAN representation as prior is able to match the performance of SimCLR on CIFAR100 within 200 epochs by applying only crop augmentations and flip. Additionally, when removing almost all augmentations (crop and color distortion), we approach the performance of the prior representations of the generative models. This is expected by our theory since we have an augmentation graph that is almost disjoint for all points and thus we only rely on the prior to reconnect them.
\begin{minipage}{0.59\textwidth}
\paragraph{ImageNet100.} Since we are still not matching supervised performance on ImageNet using contrastive models, it means the augmentation graph is not entirely class-connected and there is still room for improvement. We show that BigBiGAN representation~\cite{donahue2019large} provides a way to improve the performance of our contrastive model with standard SimCLR augmentations. First, to provide empirical evidence that decoupled uniformity loss (without kernel) is on par with current SOTA models, we optimize $\cL_{unif}^d$ on random 100-class subset of ImageNet
(following ~\cite{tian_contrastive_2020}) in the multi-view setting. Then, we show that BigBiGAN encoder~\cite{donahue2019large} pre-trained on ImageNet can define a kernel $K_{GAN}(\bar{x}, \bar{x}')=K(z(\bar{x}), z(\bar{x}'))$ ($K$ an RBF kernel) to improve contrastive-based model representation.
\end{minipage}\hfill
\begin{minipage}{0.40\textwidth}
\centering
\begin{adjustbox}{max width=\textwidth}
\begin{tabular}{c c c}
\toprule
Model & epochs & ImageNet100 \\
\midrule
SimCLR (repro) & 400 & 66.52 \\
BYOL (repro) & 400 & 72.26 \\
CMC~\cite{tian_contrastive_2020} & 400 & 73.58 \\
DCL~\cite{chuang_debiased_2020} & 400 & 74.6 \\
AlignUnif~\cite{wang_understanding_2020} & 240 & 74.6\\
Decoupled Unif (4 views) & 200 & 72.08 \\
Decoupled Unif (4 views) & 400 & 74.70 \\
\textit{Pretrained ImageNet} \\
BigBiGAN~\cite{donahue2019large} & - & 72.0\\
$K_{GAN}$ Decoupled Unif (4 views) & 200 & 74.32 \\
\midrule
Supervised & 100 & $82.1_{\pm 0.59}$\\
\bottomrule
\end{tabular}
\end{adjustbox}
\captionof{table}{Unsupervised Representation Learning using BigBiGAN representation trained on ImageNet as prior information for Decoupled Uniformity. We use ResNet50 trained on 200 epochs. }
\end{minipage}
\subsection{Filling the gap for medical imaging}
\begin{minipage}{0.64\textwidth}
Data augmentations on natural images have been handcrafted over decades to achieve current performance on ImageNet. However, they are not always adapted to medical datasets~\cite{dufumier_contrastive_2021}. We study bipolar disorder detection (BD), a challenging binary classification task, on the brain MRI dataset BIOBD~\cite{hozer2021lithium}. It contains 356 healthy controls (HC) and 306 patients with BD. We use BHB~\cite{dufumier_contrastive_2021} as a large pre-training dataset containing 10k 3D images of healthy subjects. While reconstruction-based model such as Model Genesis~\cite{zhou2021models} is SOTA for medical images, we show that contrastive approaches combined with VAE provide a new way to tackle hard classification problems.
\end{minipage}\hfill
\begin{minipage}{0.35\textwidth}
\begin{adjustbox}{max width=\textwidth}
\begin{tabular}{c c c c}
\toprule
Model & BD vs HC \\
\midrule
SimCLR~\cite{chen_simple_2020} & $60.46_{\pm 1.23}$\\
BYOL ~\cite{grill2020bootstrap}& $58.81_{\pm 0.91}$ \\
MoCo v2~\cite{he_momentum_2020} & $59.27_{\pm 1.50}$ \\
Model Genesis~\cite{zhou2021models} & $59.94_{\pm 0.81}$ \\
VAE & $52.86_{\pm 1.24}$ \\
$K_{VAE}$ Decoupled Unif (ours) & $\mathbf{62.19}_{\pm 1.58}$ \\
\midrule
Supervised & $67.42_{\pm 0.31}$ \\
\bottomrule
\end{tabular}
\end{adjustbox}
\captionof{table}{We report linear evaluation AUC($\%$) using a 5-fold leave-site-out CV scheme to avoid possible bias on acquisition site.}
\label{tab:medical_imaging}
\end{minipage}
\subsection{Weakly Supervised Learning}
\begin{minipage}{0.64\textwidth}
Now we assume to have access to image attributes that correlate well with true semantic labels (e.g birds color or size for birds classification). We use three datasets: CUB-200-2011~\cite{welinder2010caltech}, ImageNet100~\cite{tian_contrastive_2020} and UTZappos~\cite{yu2014fine}, following~\cite{tsai2022conditional}. CUB-200-2011 contains 11788 images of 200 bird species with 312 binary attributes available (encoding size, wing shape, color, etc.). UTZappos contains 50025 images of shoes from several brands sub-categorized into 21 groups that we use as downstream classification labels. It comes with 7 attributes. Finally, for ImageNet100 we follow~\cite{tsai2022conditional} and use the pre-trained CLIP~\cite{radford2021learning} model (trained on pairs (text, image)) to extract 512-d features considered as prior information. We compare our method with CCLK, a conditional contrastive model that defines positive samples only according to the conditioning attributes.
\end{minipage}
\begin{minipage}{0.35\textwidth}
\begin{adjustbox}{max width=\textwidth}
\begin{tabular}{c c c c}
\toprule
Loss & CUB & ImageNet100 & UT-Zappos\\
\midrule
SimCLR & 17.48 & 65.30 & 84.08 \\
BYOL & 16.82 & 72.20 & 85.48 \\
\midrule
CosKernel CCLK~\cite{tsai2022conditional} & 15.61 & 74.34 & 83.23\\
RBFKernel CCLK~\cite{tsai2022conditional} & 30.49 & 77.24 & 84.65 \\
CosKernel Decoupled Unif & 27.77 & \textbf{78.8} & \textbf{85.56} \\
RBFKernel Decoupled Unif & \textbf{32.87} & 76.34 & 84.78 \\
\bottomrule
\end{tabular}
\end{adjustbox}
\captionof{table}{If images attributes are accessible (e.g birds color or size for CUB200), they can be leveraged as prior in our framework to improve the representation.}
\end{minipage}
\section{Conclusion}
In this work, we have showed that we can integrate prior information into CL to improve the final representation. In particular, we draw connections between kernel theory and CL to build our theoretical framework. We demonstrate tight bounds on downstream classification performance with weaker assumptions than previous works.
Empirically, we show that generative models provide a good prior when augmentations are too weak or insufficient to remove easy-to-learn noisy features. We also show applications in medical imaging and in the weakly supervised setting. We hope that CL will benefit from the future progress in generative modelling with our theoretical framework.
\bibliographystyle{plain}
| {'timestamp': '2022-06-06T02:16:39', 'yymm': '2206', 'arxiv_id': '2206.01646', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01646'} | arxiv |
\section{Theoretical Guarantees}
\label{sec:theory}
In this section we analyze the theoretical performance of \texttt{DORIS}\xspace in decentralized policy learning and self-play setting. We first introduce a new complexity measure for function classes and policy classes, called Bellman Evaluation Eluder (BEE) dimension, and then illustrate the regret and sample complexity bounds based on this new measure.
\subsection{Bellman Evaluation Eluder Dimension}
Motivated from Bellman Eluder (BE) dimension in classic MDPs and its variants in MGs \citep{jin2021bellman,jin2021power,huang2021towards}, we propose a new measure specifically tailored to the decentralized policy learning setting, called Bellman Evaluation Eluder (BEE) dimension. First, for any function class $\mathcal{F}$, we define $(\mathcal{I}-\mathcal{T}^{\Pi,\Pi'}_h)\mathcal{F}$ to be the Bellman residuals induced by the policies in $\Pi$ and $\Pi'$:
\begin{align*}
\label{eq:def bee}
(\mathcal{I}-\mathcal{T}^{\Pi,\Pi'}_h)\mathcal{F}:=\{f_h-\mathcal{T}^{\mu,\nu}_hf_{h+1}:f\in\mathcal{F},\mu\in\Pi,\nu\in\Pi'\}.
\end{align*}
Then Bellman Evaluation Eluder (BEE) dimension is the DE dimension of the Bellman residuals induced by the policy class $\Pi$ and $\Pi'$ on function class $\mathcal{F}$:
\begin{definition}
\label{def:BEE}
The $\epsilon$-Bellman Evaluation Eluder dimension of function class $\mathcal{F}$ on distribution family $\mathcal{Q}$ with respect to the policy class $\Pi\times\Pi'$ is defined as follows:
\begin{equation*}
\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi',\mathcal{Q}):=\max_{h\in[H]}\mathrm{dim}_{\mathrm{DE}}((\mathcal{I}-\mathcal{T}^{\Pi,\Pi'}_h)\mathcal{F},\mathcal{Q}_h,\epsilon).
\end{equation*}
\end{definition}
BEE dimension is able to capture the generalization error of evaluating value function $V^{\mu\times\nu}$ where $\mu\in\Pi,\nu\in\Pi'$, which is one of the most essential tasks in decentralized policy space optimization as shown in \texttt{DORIS}\xspace. Similar to \cite{jin2021bellman,jin2021power}, we mainly consider two distribution families for $\mathcal{Q}$: \begin{itemize}
\item $\mathcal{Q}^1=\{\mathcal{Q}^1_h\}_{h\in[H]}$: the collection of all probability measures over $\mathcal{S}\times\mathcal{A}\times\mathcal{B}$ at each step when executing $(\mu,\nu)\in\Pi\times\Pi'$.
\item $\mathcal{Q}^2=\{\mathcal{Q}^2_h\}_{h\in[H]}$: the collection of all probability measures that put measure 1 on a single state-action pair $(s,a,b)$ at each step.
\end{itemize}
We also use $\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi')$ to denote $\min\{\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi',\mathcal{Q}^1),\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\break\Pi,\Pi',\mathcal{Q}^2)\}$ for simplicity in the following discussion.
\paragraph{Relation with Eluder dimension.}
To illustrate the generality of BEE dimension, we show that all function classes with low Eluder dimension also have low BEE dimension, as long as completeness (Assumption~\ref{ass:complete self}) is satisfied. More specifically, we have the following proposition and its proof is deferred to Appendix~\ref{proof prop BEE}:
\begin{proposition}
\label{prop:BEE}
Assume $\mathcal{F}$ satisfies completeness, i.e., $\mathcal{T}^{\mu,\nu}_hf_{h+1}\in\mathcal{F}_h,\forall f\in\mathcal{F},\mu\in\Pi,\nu\in\Pi',h\in[H]$. Then for all $\epsilon>0$, we have
\begin{equation}
\label{eq:prop 1}
\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi')\leq\max_{h\in[H]}\mathrm{dim}_{\mathrm{E}}(\mathcal{F}_h,\epsilon).
\end{equation}
\end{proposition}
Inequality (\ref{eq:prop 1}) shows that BEE dimension is always upper bounded by Eluder dimension when completeness is satisfied. With Proposition~\ref{prop:BEE}, Appendix~\ref{sec:example} validates that kernel Markov games (including tabular Markov games and linear Markov games) and generalized linear complete models all have small Bellman Evaluation Eluder Dimension. Furthermore, in this case the upper bound of BEE dimension does not depend on $\Pi$ and $\Pi'$, which is a desirable property when $\Pi$ and $\Pi'$ is large.
\section{Extension: Vector-valued Markov Decision process}
\label{sec:vmdp}
Another setting where \texttt{DORIS}\xspace can play a role is the approachability task for vector-valued Markov decision process (VMDP) \citep{miryoosefi2019reinforcement,yu2021provably,miryoosefi2021simple}. Similar to CMDP, we convert it into a zero-sum Markov game by Fenchel's duality and then adapt \texttt{DORIS}\xspace properly to solve it.
\paragraph{Vector-valued Markov decision process.} Consider the Vector-valued Markov decision process (VMDP) \citep{yu2021provably} $\mathcal{M}_{\text{VMDP}}=(\mathcal{S},\mathcal{A},\{P_h\}_{h=1}^H,\boldsymbol{r},H)$ where $\boldsymbol{r}=\{\boldsymbol{r}_h:\mathcal{S}\times\mathcal{A}\to[0,1]^d\}_{h=1}^H$ is a collection of $d$-dimensional reward functions and the rest of the components are defined the same as in Section~\ref{sec:cmdp}. Then given a policy $\mu\in\Pi$, we can define the corresponding $d$-dimensional value function $\boldsymbol{V}^{\mu}_h:\mathcal{S}\to[0,H]^d$ and action-value function $\boldsymbol{Q}^{\mu}_h:\mathcal{S}\times\mathcal{A}\to[0,H]^d$ as follows:
\begin{align*}
&\boldsymbol{V}_h^{\mu}(s)=\mathbb{E}_{\mu}\bigg[\sum_{t=h}^H \boldsymbol{r}_t(s_t,a_t)\bigg|s_h=s\bigg],\quad\boldsymbol{Q}_h^{\mu}(s,a)=\mathbb{E}_{\mu}\bigg[\sum_{t=h}^H \boldsymbol{r}_t(s_t,a_t)\bigg|s_h=s,a_h=a\bigg].
\end{align*}
\paragraph{Learning objective.} In this paper we study the approachability task \citep{miryoosefi2019reinforcement} in VMDP where the player needs to learn a policy whose expected cumulative reward vector lies in a convex target set $\mathcal{C}$. We consider a more general agnostic version \citep{yu2021provably,miryoosefi2021simple} where we do not assume the existence of such policies and the player learns to minimize the Euclidean distance between expected reward and the target set $\mathcal{C}$:
\begin{problem}[Approachability for VMDP]
\label{prob:vmdp}
\begin{align*}
\min_{\mu\in\Pi} \mathrm{dist}(\boldsymbol{V}^{\mu}_1(s_1),\mathcal{C}),
\end{align*}
where $\mathrm{dist}(\boldsymbol{x},\mathcal{C})$ is the Euclidean distance between point $\boldsymbol{x}$ and set $\mathcal{C}$.
\end{problem}
The approachability for VMDP is a natural objective in multi-task reinforcement learning where each dimension of the reward can be regarded as a task. It is important in many practical domains such as robotics, autonomous vehicles and recommendation systems \citep{yu2021provably}. Therefore, finding the optimal policy for Problem~\ref{prob:vmdp} efficiently is of great significance in modern reinforcement learning.
\subsection{Algorithm: \texttt{DORIS-V}\xspace}
To deal with Probelm~\ref{prob:vmdp}, we first convert Problem~\ref{prob:vmdp} into a Markov game as we have done in Section~\ref{sec:cmdp}. By Fenchel's duality of the distance function, we know Problem~\ref{prob:vmdp} is equivalent to the following minimax problem:
\begin{align*}
\min_{\mu\in\Pi}\max_{\boldsymbol{\theta}\in\mathbb{B}(1)} \mathcal{L}_{\mathrm{VMDP}}(\mu,\boldsymbol{\theta}):=\langle \boldsymbol{\theta},\boldsymbol{V}^{\mu}_1(s_1)\rangle-\max_{\boldsymbol{x}\in\mathcal{C}}\langle\boldsymbol{\theta},\boldsymbol{x}\rangle,
\end{align*}
where $\mathbb{B}(r)$ is the $d$-dimensional Euclidean ball of radius $r$ centered at the origin. Regarding $\mu$ as the player's policy and $\boldsymbol{\theta}$ as the opponent, we can again view this minimax problem as a Markov game where the reward function for the player is $\langle \boldsymbol{\theta},\boldsymbol{r}_h(s,a)\rangle$. Consider the general function approximation case that the player is given function classes $\mathcal{F}:=\{\mathcal{F}^j_{h}\}_{h,j=1}^{H,d},\mathcal{G}:=\{\mathcal{G}^j_{h}\}_{h,j=1}^{H,d}$ to approximate $\boldsymbol{Q}_h^{\mu}$ where $\mathcal{F}^j_h$ and $\mathcal{G}^j_h$ are the $j$-th dimension of $\mathcal{F}_h$ and $\mathcal{G}_h$, then we can run \texttt{DORIS}\xspace for the player while the opponent will update $\boldsymbol{\theta}$ with online projected gradient ascent just like \texttt{DORIS-C}\xspace.
We call this new algorithm \texttt{DORIS-V}\xspace, which is shown in Algorithm~\ref{alg:VMDP} and also consists of three steps in each iteration. For the policy evaluation task here, we apply \texttt{OptLSPE-V}\xspace and construct a confidence set for each dimension of the function class separately, and let the final confidence set be their intersection. Therefore the construction rule for $\mathcal{B}_{\mathcal{D}}(\mu)$ is given as:
\begin{align}
\label{eq:vmdp eva}
\mathcal{B}_{\mathcal{D}}(\mu)\gets\{f\in\mathcal{F}:\mathcal{L}_{\mathcal{D}^j}(f^j_{h},f^j_{h+1},\mu)\leq\inf_{g\in\mathcal{G}}\mathcal{L}_{\mathcal{D}^j}(g^j_{h},f^j_{h+1},\mu)+\beta,\forall h\in[H],j\in[d]\},
\end{align}
where for any $j\in[d]$ and $h\in[H]$,
\begin{align*} \mathcal{L}_{\mathcal{D}^j}(\xi^j_{h},\zeta^j_{h+1},\mu)=\sum_{(s_h,a_h,r^j_{h},s_{h+1})\in\mathcal{D}}[\xi^j_{h}(s_h,a_h)-r^j_{h}-\zeta^j_{h+1}(s_{h+1},\mu)]^2,
\end{align*}
and $r^j_{h}$ is the $j$-the dimension of $\boldsymbol{r}_h$. In addition, since here we want to minimize the distance, \texttt{OptLSPE-V}\xspace will output a pessimistic estimate of the target value function instead of an optimistic one.
\begin{itemize}
\item The player plays a policy $\mu^t$ sampled from its hyperpolicy $p^t$ and collects a trajectory.
\item The player runs \texttt{OptLSPE-V}\xspace to obtain pessimistic value function estimations $\langle\boldsymbol{\theta}^t,\underline{\boldsymbol{V}}^t(\mu)\rangle$ for all $\mu\in\Pi$ and updates the hyperpolicy using Hedge.
\item The dual variable is updated using online projected gradient ascent.
\end{itemize}
\begin{algorithm}[h]
\caption{\textbf{\texttt{DORIS-V}\xspace}}
\label{alg:VMDP}
\begin{algorithmic}
\State \textbf{Input}: learning rate $\eta,\alpha_t$, confidence parameter $\beta$.
\State Initialize $p^1\in\mathbb{R}^{|\Pi|}$ to be uniform over $\Pi$, $\boldsymbol{\theta}_1\gets 0$.
\For{$t=1,\cdots,K$}
\State \textbf{Collect samples:}
\State The learner samples $\mu^t$ from $p^t$.
\State Run $\mu^t$ and collect $\mathcal{D}_{t}=\{s^t_1,a^t_1,\boldsymbol{r}^t_{1},\cdots,s^t_{H+1}\}$.
\State \textbf{Update policy distribution:}
\State $\underline{\boldsymbol{V}}^t(\mu)\gets\textbf{\texttt{OptLSPE-V}\xspace}(\mu,\mathcal{D}_{1:t-1},\mathcal{F},\mathcal{G},\beta,\boldsymbol{\theta}^t),\quad\forall\mu\in\Pi$.
\State $p^{t+1}(\mu)\propto p^{t}(\mu)\cdot\exp(-\eta\langle\underline{\boldsymbol{V}}^t(\mu),\boldsymbol{\theta}^t\rangle),\quad\forall\mu\in\Pi$.
\State \textbf{Update dual variable:}
\State
$\boldsymbol{\theta}_{t+1}\gets\text{Proj}_{\mathbb{B}(1)}(\boldsymbol{\theta}_t+\alpha_t(\underline{\boldsymbol{V}}^t(\mu_t)-\arg\max_{\boldsymbol{x}\in\mathcal{C}}\langle\boldsymbol{\theta}_t,\boldsymbol{x}\rangle))$.
\EndFor
\State\textbf{Output}: $\widehat{\mu}$ uniformly sampled from $\mu^1,\cdots,\mu^K$.
\end{algorithmic}
\end{algorithm}
\begin{algorithm}[h]
\caption{$\textbf{\texttt{OptLSPE-V}\xspace}(\mu,\mathcal{D},\mathcal{F},\mathcal{G},\beta,\boldsymbol{\theta})$}
\label{alg:VGOLF}
\begin{algorithmic}
\State \textbf{Construct} $\mathcal{B}_{\mathcal{D}}(\mu)$ based on $\mathcal{D}$ via (\ref{eq:vmdp eva}).
\State \textbf{Select} $\underline{\boldsymbol{V}}\gets f_1(s_1,\mu)$, where $f=\arg
\min_{f'\in\mathcal{B}_{\mathcal{D}}(\mu)} \langle f'_1(s_1,\mu),\boldsymbol{\theta}\rangle$.
\State \Return $\underline{\boldsymbol{V}}$.
\end{algorithmic}
\end{algorithm}
\subsection{Theoretical Guarantees}
In this subsection, we still consider finite policy class $\Pi$. Notice that in the fictitious MG of VMDP, the policy class of the opponent is also infinite, i.e., $\mathbb{B}(1)$. However, since the player only needs to estimate $\boldsymbol{V}^{\mu}_1(s_1)$, which is independent of $\boldsymbol{\theta}$, \texttt{DORIS-V}\xspace can also circumvent the union bound on $\boldsymbol{\theta}$ just like \texttt{DORIS-C}\xspace.
In addition, we need to introduce the realizability and generalized completeness assumptions in this specific setting, which is simply a vectorized version as before:
\begin{assumption}[Realizability and generalized completeness in VMDP]
\label{ass:realize v}
Assume that for any $h\in[H],j\in[d],\mu\in\Pi,f_{h+1}\in\mathcal{F}_{h+1}$, we have $Q^{\mu,j}_{h}\in\mathcal{F}_{h,j},\mathcal{T}_h^{\mu,j}f^j_{h+1}\in\mathcal{G}^j_{h}$,
where $Q_{h}^{\mu,j}$ is the $j$-the dimension of $\boldsymbol{Q}_h^{\mu}$ and $\mathcal{T}_h^{\mu,j}$ is the $j$-th dimensional Bellman operator at step $h$ defined in (\ref{eq:vmdp bellman}).
\end{assumption}
Here $\mathcal{T}_h^{\mu,j}$ is defined as:
\begin{align}
\label{eq:vmdp bellman}
(\mathcal{T}_h^{\mu,j}f^j_{h+1})(s,a):=r^j_{h}(s,a)+\mathbb{E}_{s'\sim P(\cdot|s,a)}f^j_{h+1}(s',\mu).
\end{align}
In addition, the BEE dimension for VMDP can be defined as the maximum BEE dimension among all $d$ dimensions:
\begin{definition}
The $d$-dimensional $\epsilon$-Bellman Evaluation Eluder dimension of function class $\mathcal{F}$ on distribution family $\mathcal{Q}$ with respect to the policy class $\Pi$ is defined as follows:
\begin{equation*}
\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\mathcal{Q}):=\max_{j\in[d],h\in[H]}\mathrm{dim}_{\mathrm{DE}}((\mathcal{I}-\mathcal{T}^{\Pi,j}_h)\mathcal{F}^j,\mathcal{Q}_{h},\epsilon),
\end{equation*}
where $(\mathcal{I}-\mathcal{T}^{\Pi,j}_h)\mathcal{F}^j:=\{f^j_{h}-\mathcal{T}^{\mu,j}_hf^j_{h+1}:f\in\mathcal{F},\mu\in\Pi\}$.
\end{definition}
We also use $\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi)$ to denote $\min\{\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\mathcal{Q}^1),\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\mathcal{Q}^2)\}$ as before.
The next theorem shows that \texttt{DORIS-V}\xspace is able to find a near optimal policy for Problem~\ref{prob:vmdp} with polynomial samples, where we use the following notations to simplify writing:
\begin{align*}
d_{\mathrm{BEE,V}}:=\mathrm{dim}_{\mathrm{BEE}}\big(\mathcal{F},\sqrt{{1}/{K}},\Pi\big),\quad\mathcal{N}_{\mathrm{cov,V}}:=\max_{j\in[d]}\mathcal{N}_{\mathcal{F}^j\cup\mathcal{G}^j}(H/K)KH.
\end{align*}
\begin{theorem}
\label{thm:vmdp}
Under Assumption \ref{ass:player},\ref{ass:realize v}, there exists an absolute constant $c$ such that for any $\delta\in(0,1]$, $K\in\mathbb{N}$, if we choose $\beta=cH^2\log(\mathcal{N}_{\mathrm{cov,V}}|\Pi|d/\delta)$, $\alpha_t={2}/({H\sqrt{dt}})$, and $\eta=\sqrt{{\log|\Pi|}/({KH^2d})}$ in \texttt{DORIS-V}\xspace, then with probability at least $1-\delta$, we have:
\begin{align}
\label{eq:thm4}
\mathrm{dist}(\boldsymbol{V}^{\widehat{\mu}}_1(s_1),\mathcal{C})\leq\min_{\mu\in\Pi}\mathrm{dist}(\boldsymbol{V}^{\mu}_1(s_1),\mathcal{C})+\mathcal{O}\Big(H^2\sqrt{d}\cdot\sqrt{{d_{\mathrm{BEE,V}}\log\left(\mathcal{N}_{\mathrm{cov,V}}|\Pi|d/\delta\right)}/{K}}\Big).
\end{align}
\end{theorem}
The bound in (\ref{eq:thm4}) shows that for any $\epsilon>0$, if $K\geq\widetilde{\mathcal{O}}(d/\epsilon^2)$, $\widehat{\mu}$ will be an $\epsilon$ near-optimal policy with high probability. Compared to the results in Theorem~\ref{thm:oblivious} and Theorem~\ref{thm:adaptive}, there is an additional term $d$. This is because the reward is $d$-dimensional and we are indeed evaluating $d$ scalar value functions in \texttt{OptLSPE-V}\xspace.
The proof is similar to that of Theorem~\ref{thm:cmdp} and utilizes the fact that both $\mu$ and $\boldsymbol{\theta}$ are updated via no-regret online learning algorithms (Hedge for $\mu$ and online projected gradient ascent for $\boldsymbol{\theta}$). See Appendix~\ref{proof:thm vmdp} for more details.
\paragraph{Comparison with existing algorithms.} \cite{yu2021provably} has also proposed algorithms for approachability tasks in tabular cases and achieve the same sub-optimality gap with respect to $d$ and $K$ as Theorem~\ref{thm:vmdp}. \cite{miryoosefi2021simple} studies the tabular and linear approximation cases, achieving $\sqrt{K}$ regret as well. Their sample complexity does not scale with $d$ because they have normalized the reward vector to lie in $\mathbb{B}(1)$ in tabular cases and $\mathbb{B}(\sqrt{d_{\mathrm{lin}}})$ in $d_{\mathrm{lin}}$-dimensional linear VMDPs. Compared to the above works, \texttt{DORIS-V}\xspace is able to tackle the more general cases with nonlinear function approximation and policy classes while retaining the sample efficiency.
\section{Algorithm: \texttt{DORIS}\xspace}
\label{sec:alg}
\paragraph{Policy revealing setting.} Recall that in decentralized policy learning setting, the player is also able to observe some information of the opponent, denoted by $\mathcal{J}_h$, aside from its own actions and rewards. There have been works studying the case where $\mathcal{J}_h=\emptyset$ \citep{tian2021online} and $\mathcal{J}_h=b_h$ \citep{jin2021power,huang2021towards} in two-player zero-sum games. However, their benchmark is the Nash value of the Markov game, i.e., $V^{\mu^*\times\nu^*}_1(s_1)$ where $\mu^*\times\nu^*$ is an NE, which is strictly weaker than our benchmark $\max_{\mu\in\Pi}\sum_{t=1}^KV^{\mu\times\nu^t}_1(s_1)$ in two-player zero-sum games. In fact, \cite{liu2022learning} have showed achieving a low regret under Definition~\ref{def:regret} is exponentially hard in tabular cases when the opponent's policy is not revealed. Therefore in this paper we let $\mathcal{J}_h=\{b_h,\nu_h\}$ just like \cite{liu2022learning} and call this information structure \textit{policy revealing} setting.
That said, even in policy revealing setting, the challenge of nonstationarity still exists because the opponent's policy can be adversarial and only gets revealed after the player plays a policy. Thus from the perspective of the player, the transition kernel $P^{\nu}_h(\cdot|s,a):=\mathbb{E}_{b\sim\nu_h(s)}P_h(\cdot|s,a,b)$ still changes in an unpredictable way across episodes. In addition, the problem of how to balance exploration and exploitation with general function approximation also remains due to the unknown transition probability. In this section we propose \texttt{DORIS}\xspace, an algorithm that is capable of handling all these challenges and achieving a $\sqrt{K}$ regret upper bound in the policy revealing setting.
\paragraph{\texttt{DORIS}\xspace.} Intuitively, our algorithm is an actor-critic / mirror descent (Hedge) algorithm where each policy $\mu$ in $\Pi$ is regarded as an expert and the performance of each expert at episode $t$ is given by the value function of $V^{\nu\times\nu^t}_1(s_1)$. We call it \underline{D}ecentralized \underline{O}ptimistic hype\underline{R}policy m\underline{I}rror de\underline{S}cent (\texttt{DORIS}\xspace). \texttt{DORIS}\xspace possesses three important features, whose details are shown in Algorithm~\ref{alg:MDPS}:
\begin{itemize}
\item \textbf{Hyperpolicy and Hedge:} Motivated from the adversarial bandit literature \citep{anderson2008theory,hazan2016introduction,lattimore2020bandit}, \texttt{DORIS}\xspace maintains a distribution $p$ over the policies in $\Pi$, which we call \textit{hyperpolicy}, to combat the nonstaionarity. The hyperpolicy is updated using Hedge, with the reward of each policy $\mu$ being an estimation of the value function $V^{\mu\times\nu^t}_1(s_1)$. This is equivalent to running mirror ascent algorithm over the policy space $\Pi$ with the gradient being $V^{\mu\times\nu^t}_1(s_1)$.
\item \textbf{Optimism:} However, we do not have access to the exact value function since the transition probability is unknown, which forces us to deal with the exploration-exploitation tradeoff. Here we utilize the \textit{Optimism in the Face of Uncertainty} principle \citep{azar2017minimax,jin2020provably,jin2021bellman,jin2021power,huang2021towards} and choose our estimation $\overline{V}^t(\mu)$ to be optimistic with respect to the true value $V^{\mu\times\nu^t}_1(s_1)$. In this way \texttt{DORIS}\xspace will prefer policies with more uncertainty and thus encourage exploration in the Markov game.
\item \textbf{Optimistic policy evaluation with general function approximation:} Finally we need to design an efficient method to obtain such optimistic estimation $\overline{V}^t(\mu)$ with general function approximation. Here we propose \texttt{OptLSPE}\xspace to accomplish this task. In short, \texttt{OptLSPE}\xspace constructs a confidence set for the target action-value function $Q^{\mu\times\nu}$ based on the player's local information and chooses an optimistic estimation from the confidence set, as shown in Algorithm~\ref{alg:GOLF}. The construction of the confidence set utilizes the fact that $Q^{\mu\times\nu}_{h}$ satisfies the Bellman equation \citep{puterman1994markov}:
\begin{align*}
Q^{\mu\times\nu}_{h}(s,a,b)=(\mathcal{T}^{\mu,\nu}_h Q^{\mu\times\nu}_{h+1})(s,a,b):=r_h(s,a,b)+\mathbb{E}_{s'\sim P_h(\cdot|s,a,b)}[Q^{\mu\times\nu}_{h+1}(s',\mu,\nu)],
\end{align*}
where $Q^{\mu\times\nu}_{h+1}(s',\mu,\nu)=\mathbb{E}_{a'\sim\mu(\cdot|s'),b'\sim\nu(\cdot|s')}[Q^{\mu\times\nu}_{h+1}(s',a',b')]$. We call $\mathcal{T}^{\mu,\nu}_h$ the Bellman operator induced by $\mu\times\nu$ at $h$-th step. Then the construction rule of $\mathcal{B}_{\mathcal{D}}(\mu,\nu)$ is based on least-squared policy evaluation with slackness $\beta$ as below:
\begin{align}
\label{eq:eva}
\mathcal{B}_{\mathcal{D}}(\mu,\nu)\gets \Big \{f\in\mathcal{F}:\mathcal{L}_{\mathcal{D}}(f_h,f_{h+1},\mu,\nu)\leq\inf_{g\in\mathcal{G}}\mathcal{L}_{\mathcal{D}}(g_h,f_{h+1},\mu,\nu)+\beta,\forall h\in[H] \Big \},
\end{align}
where $\mathcal{L}_{\mathcal{D}}$ is the empirical Bellman residuals on $\mathcal{D}$:
\begin{align*} \mathcal{L}_{\mathcal{D}}(\xi_h,\zeta_{h+1},\mu,\nu)=\sum_{(s_h,a_h,b_h,r_h,s_{h+1})\in\mathcal{D}}[\xi_h(s_h,a_h,b_h)-r_h-\zeta_{h+1}(s_{h+1},\mu,\nu)]^2.
\end{align*}
\end{itemize}
\begin{algorithm}[h]
\caption{\textbf{\texttt{DORIS}\xspace}}
\label{alg:MDPS}
\begin{algorithmic}
\State \textbf{Input}: learning rate $\eta$, confidence parameter $\beta$.
\State Initialize $p^1\in\Delta_{\Pi}$ to be uniform over $\Pi$.
\For{$t=1,\cdots,K$}
\State \textbf{Collect samples:}
\State The player samples $\mu^t$ from $p^t$.
\State Run $\pi^t=\mu^t\times\nu^t$ and collect $\mathcal{D}_{t}=\{s^t_1,a^t_1,b^t_1,r^t_1,\cdots,s^t_{H+1}\}$.
\State \textbf{Update policy distribution:}
\State The opponent reveals its policy $\nu^t$ to the player.
\State $\overline{V}^t(\mu)\gets\textbf{\texttt{OptLSPE}\xspace}(\mu,\nu^t,\mathcal{D}_{1:t-1},\mathcal{F},\mathcal{G},\beta),\quad\forall\mu\in\Pi$.
\State $p^{t+1}(\mu)\propto p^{t}(\mu)\cdot\exp(\eta\cdot\overline{V}^t(\mu)),\quad\forall\mu\in\Pi$.
\EndFor
\end{algorithmic}
\end{algorithm}
\begin{algorithm}[h]
\caption{$\textbf{\texttt{OptLSPE}\xspace}(\mu,\nu,\mathcal{D},\mathcal{F},\mathcal{G},\beta)$}
\label{alg:GOLF}
\begin{algorithmic}
\State \textbf{Construct} $\mathcal{B}_{\mathcal{D}}(\mu,\nu)$ based on $\mathcal{D}$ via (\ref{eq:eva}).
\State \textbf{Select} $\bar{V}\gets\max_{f\in\mathcal{B}_{\mathcal{D}}(\mu,\nu)} f(s_1,\mu,\nu)$.
\State \Return $\bar{V}$.
\end{algorithmic}
\end{algorithm}
\paragraph{Decentralized Algorithm.} Here we want to highlight that \texttt{DORIS}\xspace is a decentralized algorithm because the player can run \texttt{DORIS}\xspace based only on its local information, i.e., $\{s_h,a_h,\mathcal{J}_h,r_h\}$, and we do not make any assumptions on the behavior of the opponent.
\subsection{\texttt{DORIS}\xspace in Self-Play Setting}
Apart from decentralized learning setting with a possibly adversarial opponent, we are also interested in the self-play setting where we can control all the agents and need to find an equilibrium for the $n$-agent general-sum Markov game. Inspired by the existing relationships between no-regret learning and CCE in matrix games \citep{fudenberg1991game,blum2007learning,daskalakis2011near}, a natural idea is to simply let all agents run \texttt{DORIS}\xspace independently. To achieve this, we assume each agent $i$ is given a value function class $\mathcal{F}_i=\mathcal{F}_{1,i}\times\cdots\times\mathcal{F}_{H,i}$ and an auxiliary function class $\mathcal{G}_i=\mathcal{G}_{1,i}\times\cdots\times\mathcal{G}_{H,i}$ as in \texttt{DORIS}\xspace, and run \texttt{DORIS}\xspace by viewing the other agents as its opponent. Suppose the policies played by agent $i$ during $K$ episodes are $\{\mu^t_{i}\}_{t=1}^{K}$, then we output the final joint policy as a uniform mixture of them:
\begin{align*}
\widehat{\pi}\sim\mathrm{Unif}\Big(\Big \{ {\textstyle \prod_{i\in[n]}}~ \mu^1_{i},\cdots,{\textstyle \prod_{i\in[n]}}~ \mu^K_{i} \Big\} \Big ).
\end{align*}
See Algorithm~\ref{alg:MDPS self} for more details.
\begin{algorithm}[h]
\caption{\textbf{\texttt{DORIS}\xspace} in self-play setting}
\label{alg:MDPS self}
\begin{algorithmic}
\State \textbf{Input}: learning rate $\{\eta_i\}_{i=1}^n$, confidence parameter $\{\beta_i\}_{i=1}^n$.
\State Initialize $p^1_i\in\Delta_{|\Pi_i|}$ to be uniform over $\Pi_i$ for all $i\in[n]$.
\For{$t=1,\cdots,K$}
\State \textbf{Collect samples:}
\State Agent $i$ samples $\mu^t_i$ from $p^t_i$.
\State Run $\mu^t=\prod_{i=1}^n\mu^t_i$ and collect $\mathcal{D}_{t,i}=\{s^t_1,\boldsymbol{a}^t_1,r^t_{1,i},\cdots,s^t_{H+1}\}$ for each agent $i$.
\State \textbf{Update policy distribution:}
\State All agents reveal their policies $\mu^t_i$.
\State $\overline{V}^t_i(\mu_i)\gets\textbf{\texttt{OptLSPE}\xspace}(\mu_i,\mu^t_{-i},\mathcal{D}_{1:t-1,i},\mathcal{F}_i,\mathcal{G}_i,\beta_i),\quad\forall\mu_i\in\Pi_i,i\in[n]$.
\State $p^{t+1}_i(\mu_i)\propto p^{t}_i(\mu_i)\cdot\exp(\eta_i\cdot\overline{V}^t_i(\mu_i)),\quad\forall\mu_i\in\Pi_i,i\in[n]$.
\EndFor
\State \textbf{Output}: $\widehat{\pi}\sim\text{Unif}(\{\prod_{i\in[n]}\mu^1_{i},\cdots,\prod_{i\in[n]}\mu^K_{i}\})$.
\end{algorithmic}
\end{algorithm}
\begin{remark}
Algorithm~\ref{alg:MDPS self} is also a decentralized algorithm since every agent runs their local algorithm independently without coordination. The only step that requires centralized control is the output process where all the agents need to share the same iteration index, which is also required in the existing decentralized algorithms \citep{mao2021on,jin2021v}.
\end{remark}
\subsection{Decentralized Policy Learning Regret}
\label{sec:main result}
Next we present the regret analysis for \texttt{DORIS}\xspace in decentralized policy learning setting. Notice that when $\Pi$ is infinite, the lower bound in \cite{liu2022learning} indicates that the regret will scale with $|\Pi'|$ in tabular cases, suggesting the hardness of efficient learning for infinite policy class $\Pi$. Therefore we focus on finite $\Pi$ here:
\begin{assumption}[Finite player's policy class]
\label{ass:player}
We assume $\Pi$ is finite.
\end{assumption}
We consider two cases, the oblivious opponent (i.e., the opponent determines $\{\nu^t\}_{t=1}^K$ secretly before the game starts) and the adaptive opponent (i.e., the opponent determines its policy adaptively as the game goes on) separately. The difference between these two cases lies in the policy evaluation step of \texttt{DORIS}\xspace. The policy $\nu^t$ of an oblivious opponent does not depend on the collected dataset $\mathcal{D}_{1:t-1}$ and thus $V^{\mu,\nu^t}$ is easier to evaluate. However, for an adaptive opponent, $\nu^t$ will be chosen adaptively based on $\mathcal{D}_{1:t-1}$ and we need to introduce an additional union bound over $\Pi'$ when analyzing the evaluation error of $V^{\mu,\nu^t}$.
\paragraph{Oblivious opponent.} To attain accurate value function estimation and thus low regrets, we first need to introduce two standard assumptions, realizability and generalized completeness, on $\mathcal{F}$ and $\mathcal{G}$ \citep{jin2021bellman,jin2021power}. Here realizability refers to that all the ground-truth action value functions belong to $\mathcal{F}$ and generalized completeness means that $\mathcal{G}$ contains all the results of applying Bellman operator to the functions in $\mathcal{F}$.
\begin{assumption}[Realizability and generalized completeness]
\label{ass:realize}
Assume that for any $h\in[H],\mu\in\Pi,\nu\in\{\nu^1,\cdots,\nu^K\},f_{h+1}\in\mathcal{F}_{h+1}$, we have $Q^{\mu\times\nu}_{h}\in\mathcal{F}_h,\mathcal{T}_h^{\mu,\nu}f_{h+1}\in\mathcal{G}_{h}$.
\end{assumption}
\begin{remark}
Some existing works \citep{xie2021bellman,huang2021towards} assume the completeness assumption, which can also be generalized to our setting:
\begin{assumption}
\label{ass:complete self}
Assume that for any $ h\in[H],\mu\in\Pi,\nu\in\Pi',f_{h+1}\in\mathcal{F}_{h+1}$, we have $\mathcal{T}_h^{\mu,\nu}f_{h+1}\in\mathcal{F}_{h}$.
\end{assumption}
We want to clarify that Assumption~\ref{ass:complete self} is stronger than generalized completeness in Assumption~\ref{ass:realize} since if Assumption~\ref{ass:complete self} holds, we can simply let $\mathcal{G}=\mathcal{F}$ to satisfy generalized completeness.
\end{remark}
Appendix~\ref{sec:realize} shows that realizability and generalized completeness are satisfied in many examples including tabular MGs, linear MGs and kernel MGs with proper function classes. With the above assumptions, we have Theorem~\ref{thm:oblivious} to characterize the regret of \texttt{DORIS}\xspace when the opponent is oblivious, whose proof sketch is deferred to Section~\ref{sec:proof sketch}. To simplify writing, we use the following notations in Theorem~\ref{thm:oblivious}:
\begin{align*}
d_{\mathrm{BEE}}:=\mathrm{dim}_{\mathrm{BEE}}\big(\mathcal{F},\sqrt{1/ K },\Pi,\Pi'\big),\quad\mathcal{N}_{\mathrm{cov}}:=\mathcal{N}_{\mathcal{F}\cup\mathcal{G}}(V_{\max}/K)KH.
\end{align*}
\begin{theorem}[Regret of Oblivious Adversary]
\label{thm:oblivious}
Under Assumption~\ref{ass:player},\ref{ass:realize}, there exists an absolute constant $c$ such that for any $\delta\in(0,1]$, $K\in\mathbb{N}$, if we choose $\beta=cV_{\max}^2\log(\mathcal{N}_{\mathrm{cov}}|\Pi|/\delta)$ and $\eta=\sqrt{\log|\Pi|/(KV_{\max}^2)}$ in \texttt{DORIS}\xspace, then with probability at least $1-\delta$, we have:
\begin{align}
\label{eq:thm1}
\text{Regret}(K)\leq\mathcal{O}\big(HV_{\max}\sqrt{Kd_{\mathrm{BEE}}\log\left(\mathcal{N}_{\mathrm{cov}}|\Pi|/\delta\right)}\big).
\end{align}
\end{theorem}
The $\sqrt{K}$ bound on the regret in Theorem~\ref{thm:oblivious} is consistent with the rate in tabular case \citep{liu2022learning} and suggests that the uniform mixture of the output policies $\{\mu^t\}_{t=1}^K$ is an $\epsilon$-approximate best policy in hindsight when $K=\widetilde{\mathcal{O}}(1/\epsilon^2)$. The complexity of the problem affects the regret bound through the covering number and the BEE dimension, implying that BEE dimension indeed captures the essence of this problem. Further, in oblivious setting, the regret bound in (\ref{eq:thm1}) does not depend on $\Pi'$ directly (the upper bound of the BEE dimension is also independent of $\Pi'$ in some special cases as shown in Proposition~\ref{prop:BEE}) and thus Theorem~\ref{thm:oblivious} can still hold when $\Pi'$ is infinite, as long as Assumptions~\ref{ass:realize} is satisfied.
\paragraph{Adaptive Opponent.}
In the adaptive setting, the analysis in the oblivious setting can still work but requires slight modifications. We first need to modify Assumption~\ref{ass:realize} to hold for all $\nu\in\Pi'$ since $\nu^t$ is no longer predetermined:
\begin{assumption}[Uniform realizability and generalized completeness]
\label{ass:realize adapt}
Assume that for any $h\in[H],\mu\in\Pi,\nu\in\Pi',f_{h+1}\in\mathcal{F}_{h+1}$, we have $Q^{\mu\times\nu}_{h}\in\mathcal{F}_h,\mathcal{T}_h^{\mu,\nu}f_{h+1}\in\mathcal{G}_{h}$.
\end{assumption}
Further, as we have mentioned before, we need to introduce a union bound over the policies in $\Pi'$ in our analysis and thus we also assume $\Pi'$ to be finite for simplicity.
\begin{assumption}[Finite opponent's policy class]
\label{ass:opponent}
We assume $\Pi'$ is finite.
\end{assumption}
\begin{remark}
When $\Pi'$ is infinite, it is straightforward to generalize our analysis by replacing $|\Pi'|$ with the covering number of $\Pi'$. However, the regret will still depend on the size of $\Pi'$, which is not the case in tabular setting \cite{liu2022learning}. This dependency originates from our model-free type of policy evaluation algorithm (Algorithm~\ref{alg:GOLF}) and thus is inevitable for \texttt{DORIS}\xspace in general. That said, when the Markov game has special structures (e.g., see the Markov game in Section~\ref{sec:cmdp} and Section~\ref{sec:vmdp}), we can avoid this dependency.
\end{remark}
With the above assumptions, we have Theorem~\ref{thm:adaptive} to show that \texttt{DORIS}\xspace can still achieve sublinear regret in adaptive setting, whose proof is deferred to Section~\ref{sec:proof sketch}:
\begin{theorem}[Regret of Adaptive Adversary]
\label{thm:adaptive}
Under Assumption~\ref{ass:player},\ref{ass:realize adapt},\ref{ass:opponent}, there exists an absolute constant $c$ such that for any $\delta\in(0,1]$, $K\in\mathbb{N}$, choosing $\beta=cV_{\max}^2\log(\mathcal{N}_{\mathrm{cov}}|\Pi||\Pi'|/\delta)$ and $\eta=\sqrt{\log|\Pi|/(KV_{\max}^2)}$ in \texttt{DORIS}\xspace, then with probability at least $1-\delta$ we have:
\begin{align}
\label{eq:thm2}
\text{Regret}(K)\leq\mathcal{O}\big(HV_{\max}\sqrt{Kd_{\mathrm{BEE}}\log\left(\mathcal{N}_{\mathrm{cov}}|\Pi||\Pi'|/\delta\right)}\big).
\end{align}
\end{theorem}
We can see that in adaptive setting the regret also scales with $\sqrt{K}$, implying that \texttt{DORIS}\xspace can still find an $\epsilon$-approximate best policy in hindsight with $\widetilde{\mathcal{O}}(1/\epsilon^2)$ episodes even when the opponent is adaptive. Compared to Theorem~\ref{thm:oblivious}, Theorem~\ref{thm:adaptive} has an additional $\log|\Pi'|$ in the upper bound (\ref{eq:thm2}), which comes from the union bound over $\Pi'$ in the analysis.
\paragraph{Intuitions on the regret bounds.} The regrets in Theorem~\ref{thm:oblivious} and Theorem~\ref{thm:adaptive} can be decomposed to two parts, the online learning error incurred by Hedge and the cumulative value function estimation error incurred by \texttt{OptLSPE}\xspace. From the online learning literature \citep{hazan2016introduction}, the online learning error is $\mathcal{O}(V_{\max}\sqrt{K\log|\Pi|})$ by viewing the policies in $\Pi$ as experts and $\overline{V}^t(\mu)$ as the reward function of expert $\mu$. For the estimation error, we utilize BEE dimensions to bridge $\overline{V}^t(\mu^t)-V_1^{\pi^t}(s_1)$ with the function's empirical Bellman residuals on $\mathcal{D}_{1:t-1}$. This further incurs $\widetilde{\mathcal{O}}(V_{\max}\sqrt{Kd_{\mathrm{BEE}}})$ in the results. Our technical contribution mainly lies in bounding the cumulative value function estimation error with the newly proposed BEE dimensions, which is different from \cite{jin2021bellman} where they focus on bounding the cumulative distance from the optimal value function.
\paragraph{Comparison with existing works.} There have been works studying decentralized policy learning. However, most of them (e.g., \cite{tian2021online,jin2021power,huang2021towards}) only compete against the Nash value in a two-player zero-sum games, which is a much weaker baseline than ours. \cite{liu2022learning} can achieve a $\sqrt{K}$ regret upper bound under Definition~\ref{def:regret}, but their theory is restricted to the tabular case and seems unable to deal with more complicated cases. For example, when applying the algorithm in \citep{liu2022learning} to a linear MG, the regret scales with $|\mathcal{S}|$ and $|\mathcal{A}|$, which becomes vacuous in the face of large state and action space. However, for the case of a linear MG, \texttt{DORIS}\xspace can achieve a regret bound that depends on the size of the state-action space through the dimension $d$, rather than $|\mathcal{S}|$ and $|\mathcal{A}|$. Thus \texttt{DORIS}\xspace is able to handle large or even infinite state and action space. In summary, \texttt{DORIS}\xspace can achieve a $\sqrt{K}$ regret under Definition~\ref{def:regret} with general function approximation, capable of tackling all models with low BEE dimension, including linear MGs, kernel MGs and generalized linear complete models (Appendix~\ref{sec:example}).
\section{Proofs of Lemmas in Section~\ref{sec:proof sketch}}
\subsection{Proof of Lemma~\ref{lem:optimism}}
\label{proof lemma optimism}
Let $\mathcal{V}_{\rho}$ be a $\rho$-cover of $\mathcal{G}$ with respect to $\Vert\cdot\Vert_{\infty}$. Consider an arbitrary fixed tuple $(\mu,t,h,g)\in\Pi\times[K]\times[H]\times\mathcal{G}$. Define $W_{t,k}(h,g,\mu)$ as follows:
\begin{align*}
W_{t,k}(h,g,\mu):=&(g_h(s^k_h,a^k_h,b_h^k)-r_h^k-Q^{\mu,\nu^t}_{h+1}(s^k_{h+1},\mu,\nu^t))^2\notag\\
&-(Q^{\mu,\nu^t}_{h}(s_h^k,a_h^k,b_h^k)-r_h^k-Q^{\mu,\nu^t}_{h+1}(s^k_{h+1},\mu,\nu^t))^2,
\end{align*}
and $\mathfrak{F}_{k,h}$ be the filtration induced by $\{\nu^1,\cdots,\nu^K\}\cup\{s^i_1,a^i_1,b^i_1,r^i_1,\cdots,s^i_{H+1}\}_{i=1}^{k-1}\cup\break\{s^k_1,a^k_1,b^k_1,r^k_1,\cdots,s^k_h,a^k_h,b^k_h\}$. Then we have for all $k\leq t-1$,
\begin{align*}
\mathbb{E}[W_{t,k}(h,g,\mu)|\mathfrak{F}_{k,h}]=[(g_h-Q^{\mu,\nu^t}_h)(s_h^k,a_h^k,b_h^k)]^2,
\end{align*}
and
\begin{align*}
\text{Var}[W_{t,k}(h,g,\mu)|\mathfrak{F}_{k,h}]\leq 4V_{\max}^2\mathbb{E}[W_{t,k}(h,g,\mu)|\mathfrak{F}_{k,h}].
\end{align*}
By Freedman's inequality, with probability at least $1-\delta/4$, we have
\begin{align*}
&\bigg|\sum_{k=1}^{t-1}W_{t,k}(h,g,\mu)-\sum_{k=1}^{t-1}[(g_h-Q^{\mu,\nu^t}_h)(s_h^k,a_h^k,b_h^k)]^2\bigg|\notag\\
&\leq\ \mathcal{O}\Bigg(V_{\max}\sqrt{\log\frac{1}{\delta}\cdot\sum_{k=1}^{t-1}[(g_h-Q^{\mu,\nu^t}_h)(s_h^k,a_h^k,b_h^k)]^2}+V_{\max}^2\log\frac{1}{\delta}\Bigg).
\end{align*}
By taking union bound over $\Pi\times[K]\times[H]\times\mathcal{V}_{\rho}$ and the non-negativity of $\sum_{k=1}^{t-1}[(g_h-Q^{\mu,\nu^t}_h)(s_h^k,a_h^k,b_h^k)]^2$, we have with probability at least $1-\delta/4$, for all $(\mu,k,h,g)\in\Pi\times[K]\times[H]\times\mathcal{V}_{\rho}$,
\begin{equation*}
-\sum_{k=1}^{t-1}W_{t,k}(h,g,\mu)\leq\mathcal{O}(V_{\max}^2\iota),
\end{equation*}
where $\iota=\log({HK|\mathcal{V}_{\rho}||\Pi|}/{\delta})$. This implies for all $(\mu,t,h,g)\in\Pi\times[K]\times[H]\times\mathcal{G}$,
\begin{align*}
&\sum_{k=1}^{t-1}(Q^{\mu,\nu^t}_{h}(s_h^k,a_h^k,b_h^k)-r_h^k-Q^{\mu,\nu^t}_{h+1}(s^k_{h+1},\mu,\nu^t))^2\notag\\
&\qquad\leq\sum_{k=1}^{t-1}(g_h(s^k_h,a^k_h,b_h^k)-r_h^k-Q^{\mu,\nu^t}_{h+1}(s^k_{h+1},\mu,\nu^t))^2+\mathcal{O}(V_{\max}^2\iota+V_{\max} t\rho).
\end{align*}
Choose $\rho=V_{\max}/K$ and we know that with probability at least $1-\delta$ for all $\mu\in\Pi$ and $t\in[K]$, $Q^{\mu,\nu^t}\in\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu,\nu^t)$. This concludes our proof.
\subsection{Proof of Lemma~\ref{lem:bounded error}}
\label{proof lemma bounded error}
Let $\mathcal{Z}_{\rho}$ be a $\rho$-cover of $\mathcal{F}$ with respect to $\Vert\cdot\Vert_{\infty}$. Consider an arbitrary fixed tuple $(\mu,t,h,f)\in\Pi\times[K]\times[H]\times\mathcal{F}$. Let
\begin{align*}
X_{t,k}(h,f,\mu):=&(f_h(s^k_h,a^k_h,b_h^k)-r_h^k-f_{h+1}(s^k_{h+1},\mu,\nu^t))^2\notag\\
&-((\mathcal{T}^{\mu,\nu^t}_{h}f_{h+1})(s_h^k,a_h^k,b_h^k)-r_h^k-f_{h+1}(s^k_{h+1},\mu,\nu^t))^2,
\end{align*}
and $\mathfrak{F}_{k,h}$ be the filtration induced by $\{\nu^1,\cdots,\nu^K\}\cup\{s^i_1,a^i_1,b^i_1,r^i_1,\cdots,s^i_{H+1}\}_{i=1}^{k-1}\cup\break\{s^k_1,a^k_1,b^k_1,r^k_1,\cdots,s^k_h,a^k_h,b^k_h\}$. Then we have for all $k\leq t-1$,
\begin{align*}
\mathbb{E}[X_{t,k}(h,f,\mu)|\mathfrak{F}_{k,h}]=[(f_h-\mathcal{T}^{\mu,\nu^t}_{h}f_{h+1})(s_h^k,a_h^k,b_h^k)]^2,
\end{align*}
and
\begin{align*}
\text{Var}[X_{t,k}(h,f,\mu)|\mathfrak{F}_{k,h}]\leq 4V_{\max}^2\mathbb{E}[X_{t,k}(h,f,\mu)|\mathfrak{F}_{k,h}].
\end{align*}
By Freedman's inequality, with probability at least $1-\delta$,
\begin{align*}
&\bigg|\sum_{k=1}^{t-1}X_{t,k}(h,f,\mu)-\sum_{k=1}^{t-1}[(f_h-\mathcal{T}^{\mu,\nu^t}_{h}f_{h+1})(s_h^k,a_h^k,b_h^k)]^2\bigg|\notag\\
&\qquad\leq\ \mathcal{O}\Bigg(V_{\max}\sqrt{\log\frac{1}{\delta}\cdot\sum_{k=1}^{t-1}[(f_h-\mathcal{T}^{\mu,\nu^t}_{h}f_{h+1})(s_h^k,a_h^k,b_h^k)]^2}+V_{\max}^2\log\frac{1}{\delta}\Bigg).
\end{align*}
By taking union bound over $\Pi\times[K]\times[H]\times\mathcal{Z}_{\rho}$, we have with probability at least $1-\delta$, for all $(\mu,t,h,f)\in\Pi\times[K]\times[H]\times\mathcal{Z}_{\rho}$,
\begin{align}
&\bigg|\sum_{k=1}^{t-1}X_{t,k}(h,f,\mu)-\sum_{k=1}^{t-1}[(f_h-\mathcal{T}^{\mu,\nu^t}_{h}f_{h+1})(s_h^k,a_h^k,b_h^k)]^2\bigg|\notag\\
&\qquad\leq\ \mathcal{O}\Bigg(V_{\max}\sqrt{\iota\cdot\sum_{k=1}^{t-1}[(f_h-\mathcal{T}^{\mu,\nu^t}_{h}f_{h+1})(s_h^k,a_h^k,b_h^k)]^2}+V_{\max}^2\iota\Bigg).\label{eq:conc-1}
\end{align}
where $\iota=\log({HK|\mathcal{Z}_{\rho}||\Pi|}/{\delta})$.
Conditioned on the above event being true, we consider an arbitrary pair $(h,t,\mu)\in[H]\times[K]\times\Pi$. By the definition of $\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu,\nu^t)$ and Assumption~\ref{ass:realize}, we have:
\begin{align*}
\sum_{k=1}^{t-1}X_{t,k}(h,f^{t,\mu},\mu)=&\sum_{k=1}^{t-1}(f_h(s^k_h,a^k_h,b_h^k)-r_h^k-f_{h+1}(s^k_{h+1},\mu,\nu^t))^2\notag\\
&-((\mathcal{T}^{\mu,\nu^t}_{h}f_{h+1})(s_h^k,a_h^k,b_h^k)-r_h^k-f_{h+1}(s^k_{h+1},\mu,\nu^t))^2\\
\leq&\sum_{k=1}^{t-1}(f_h(s^k_h,a^k_h,b_h^k)-r_h^k-f_{h+1}(s^k_{h+1},\mu,\nu^t))^2\notag\\
&-\inf_{g\in\mathcal{G}}(g_h(s_h^k,a_h^k,b_h^k)-r_h^k-f_{h+1}(s^k_{h+1},\mu,\nu^t))^2\\
\leq&\beta.
\end{align*}
Let $l^{t,\mu}=\arg\min_{l\in\mathcal{Z}_{\rho}}\max_{h\in[H]}\Vert f^{t,\mu}_h-l^{t,\mu}_h\Vert_{\infty}$. By the definition of $\mathcal{Z}_{\rho}$, we have
\begin{align}
\label{eq:bounded-1}
\sum_{k=1}^{t-1}X_{t,k}(h,l^{t,\mu},\mu)\leq \mathcal{O}(V_{\max} t\rho+\beta).
\end{align}
By (\ref{eq:conc-1}), we know:
\begin{align}
&\bigg|\sum_{k=1}^{t-1}X_{t,k}(h,l^{t,\mu},\mu)-\sum_{k=1}^{t-1}[(l^{t,\mu}_h-\mathcal{T}^{\mu,\nu^t}_{h}l^{t,\mu}_{h+1})(s_h^k,a_h^k,b_h^k)]^2\bigg|\notag\\
&\qquad\leq\ \mathcal{O}\Bigg(V_{\max}\sqrt{\iota\cdot\sum_{k=1}^{t-1}[(l^{t,\mu}_h-\mathcal{T}^{\mu,\nu^t}_{h}l^{t,\mu}_{h+1})(s_h^k,a_h^k,b_h^k)]^2}+V_{\max}^2\iota\Bigg).\label{eq:bounded-2}
\end{align}
Combining (\ref{eq:bounded-1}) and (\ref{eq:bounded-2}), we obtain
\begin{align*}
\sum_{k=1}^{t-1}[(l^{t,\mu}_h-\mathcal{T}^{\mu,\nu^t}_{h}l^{t,\mu}_{h+1})(s_h^k,a_h^k,b_h^k)]^2\leq\mathcal{O}(V_{\max}^2\iota+V_{\max} t\rho+\beta).
\end{align*}
This implies that
\begin{align*}
\sum_{k=1}^{t-1}[(f^{t,\mu}_h-\mathcal{T}^{\mu,\nu^t}_{h}f^{t,\mu}_{h+1})(s_h^k,a_h^k,b_h^k)]^2\leq\mathcal{O}(V_{\max}^2\iota+V_{\max} t\rho+\beta).
\end{align*}
Choose $\rho=V_{\max}/K$ and we can obtain (b). For (a), simply let $\mathfrak{F}_{k,h}$ be the filtration induced by $\{\nu^1,\cdots,\nu^K\}\cup\{\mu^i,s^i_1,a^i_1,b^i_1,r^i_1,\cdots,s^i_{H+1}\}_{i=1}^{k-1}\cup\mu^k$ and repeat the above arguments, which concludes our proof.
\subsection{Proof of Lemma~\ref{lem:performance}}
\label{proof lemma performance}
First notice that $\overline{V}^t(\mu^t)=f^{t,\mu^t}_1(s_1,\mu^t,\nu^t)$. Therefore, we have
\begin{align*}
&\overline{V}^t(\mu^t)-V^{\pi^t}_1(s_1)=\mathbb{E}_{a_1\sim\mu^t(\cdot|s_1),b_1\sim\nu^t(\cdot|s_1)}[f^{t,\mu^t}_1(s_1,a_1,b_1)-Q^{\pi^t}_1(s_1,a_1,b_1)]\\
&\qquad=\mathbb{E}_{a_1\sim\mu^t(\cdot|s_1),b_1\sim\nu^t(\cdot|s_1)}\big[\mathbb{E}_{s_2\sim P_1(\cdot|s_1,a_1,b_1)}[f^{t,\mu^t}_2(s_2,\mu^t,\nu^t)]-\mathbb{E}_{s_2\sim P_1(\cdot|s_1,a_1,b_1)}[V^{\pi^t}_2(s_2)]\big]\\
&\qquad\quad+\mathbb{E}_{a_1\sim\mu^t(\cdot|s_1),b_1\sim\nu^t(\cdot|s_1)}[(f^{t,\mu^t}_1-\mathcal{T}^{\mu^t,\nu^t}_1f_{2}^{t,\mu^t})(s_1,a_1,b_1)]\\
&\qquad=\mathbb{E}_{s_2\sim\pi^t}[f^{t,\mu^t}_2(s_2,\mu^t,\nu^t)-V^{\pi^t}_2(s_2)]+\mathbb{E}_{\pi^t}[(f^{t,\mu^t}_1-\mathcal{T}^{\mu^t,\nu^t}_1f_{2}^{t,\mu^t})(s_1,a_1,b_1)].
\end{align*}
Repeat the above procedures and we can obtain Lemma~\ref{lem:performance}. This concludes our proof.
\section{Proofs of Proposition~\ref{prop:BEE}}
\label{proof prop BEE}
From the completeness assumption, we know that there exists $g_h\in\mathcal{F}_h$ such that $g_h=\mathcal{T}^{\mu,\nu}_hf_{h+1}$,
which implies that
\begin{align*}
f_h-\mathcal{T}^{\mu,\nu}_hf_{h+1}\in\mathcal{F}_h-\mathcal{F}_h,\forall f\in\mathcal{F}, \mu\in\Pi,\nu\in\Pi'.
\end{align*}
In other words, $(I-\mathcal{T}^{\Pi,\Pi'}_h)\mathcal{F}\subseteq\mathcal{F}_h-\mathcal{F}_h$. Therefore, from the definition of $\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\break\Pi,\Pi')$ we have
\begin{align*}
\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi')&\leq\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi',\mathcal{Q}^2)=\max_{h\in[H]}\mathrm{dim}_{\mathrm{DE}}((I-\mathcal{T}^{\Pi,\Pi'}_h)\mathcal{F},\mathcal{Q}^2_h,\epsilon)\\
&\leq\max_{h\in[H]}\mathrm{dim}_{\mathrm{DE}}((\mathcal{F}_h-\mathcal{F}_h),\mathcal{Q}^2_h,\epsilon)=\max_{h\in[H]}\mathrm{dim}_{\mathrm{E}}(\mathcal{F}_h,\epsilon),
\end{align*}
where the last step comes from the definition of $\mathrm{dim}_{\mathrm{E}}$ and $\mathcal{Q}^2_h$ is the dirac distribution family. This concludes our proof.
\section{Proof of Theorem~\ref{thm:cmdp}}
\label{proof:thm cmdp}
In this section we present the proof for Theorem~\ref{thm:cmdp}. Our proof mainly consists of four steps:
\begin{itemize}
\item Prove $\overline{V}^t_r(\mu)$ and $\overline{V}^t_g(\mu)$ are optimistic estimations of $ V_{r,1}^{\mu}(s_1)$ and $V_{g,1}^{\mu}(s_1)$ for all $t\in[K]$ and $\mu\in\Pi$.
\item Bound the total estimation error $\sum_{t=1}^K\overline{V}^t_r(\mu^t)-V_{r,1}^{\mu^t}(s_1)$ and $\sum_{t=1}^K\overline{V}^t_g(\mu^t)-V_{g,1}^{\mu^t}(s_1)$.
\item Bound the regret by decomposing it into estimation error and online learning error induced by Hedge.
\item Bound the constraint violation by strong duality.
\end{itemize}
\paragraph{Step 1: Prove optimism.}
First we can show that the constructed set $\mathcal{B}_{\mathcal{D}^r_{1:t-1}}(\mu)$ ($\mathcal{B}_{\mathcal{D}^g_{1:t-1}}(\mu)$) is not vacuous in the sense that the true action-value function $Q_{r}^{\mu}$ ($Q_{g}^{\mu}$) belongs to it with high probability:
\begin{lemma}
\label{lem:optimism single}
With probability at least $1-{\delta}/{4}$, we have for all $t\in[K]$ and $\mu\in\Pi$,
\begin{align*}
Q_{r}^{\mu}\in\mathcal{B}_{\mathcal{D}^r_{1:t-1}}(\mu), Q_{g}^{\mu}\in\mathcal{B}_{\mathcal{D}^g_{1:t-1}}(\mu).
\end{align*}
\end{lemma}
\begin{proof}
The proof is almost the same as Lemma~\ref{lem:optimism} and thus is omitted here.
\end{proof}
Then since $\overline{V}^t_r(\mu)=\max_{f\in\mathcal{B}_{\mathcal{D}^g_{1:t-1}}(\mu)}f(s_1,\mu)$, we know for all $t\in[K]$ and $\mu\in\Pi$,
\begin{align*}
\overline{V}^t_r(\mu)\geq Q_{r}^{\mu}(s_1,\mu)=V_{r,1}^{\mu}(s_1).
\end{align*}
Similarly, we know $\overline{V}^t_g(\mu)\geqV_{g,1}^{\mu}(s_1)$.
\paragraph{Step 2: Bound estimation error.}
Next we need to show the estimation error $\sum_{t=1}^K\overline{V}^t_r(\mu^t)-V_{r,1}^{\mu^t}(s_1)$ and $\sum_{t=1}^K\overline{V}^t_g(\mu^t)-V_{g,1}^{\mu^t}(s_1)$ are small. Let $f^{t,\mu,r}=\arg\max_{f\in\mathcal{B}_{\mathcal{D}^r_{1:t-1}}(\mu)}f(s_1,\mu)$ and $f^{t,\mu,g}=\arg\max_{f\in\mathcal{B}_{\mathcal{D}^g_{1:t-1}}(\mu)}f(s_1,\mu)$. Then we have
\begin{lemma}
\label{lem:bounded error single}
With probability at least $1-{\delta}/{4}$, we have for all $t\in[K]$, $h\in[H]$ and $\mu\in\Pi$,
\begin{align*}
(a)\quad&\sum_{k=1}^{t-1}\mathbb{E}_{\mu^k}\bigg[\Big(f^{t,\mu,r}_h(s_h,a_h)-(\mathcal{T}^{\mu,r}_h f^{t,\mu,r}_{h+1})(s_h,a_h)\Big)^2\bigg]\leq\mathcal{O}(\beta_r),\\
&\sum_{k=1}^{t-1}\mathbb{E}_{\mu^k}\bigg[\Big(f^{t,\mu,g}_h(s_h,a_h)-(\mathcal{T}^{\mu,g}_h f^{t,\mu,g}_{h+1})(s_h,a_h)\Big)^2\bigg]\leq\mathcal{O}(\beta_g),\\
(b)\quad&\sum_{k=1}^{t-1}\Big(f^{t,\mu,r}_h(s_h^k,a_h^k)-(\mathcal{T}^{\mu,r}_h f^{t,\mu,r}_{h+1})(s_h^k,a_h^k)\Big)^2\leq\mathcal{O}(\beta_r),\\
&\sum_{k=1}^{t-1}\Big(f^{t,\mu,g}_h(s_h^k,a_h^k)-(\mathcal{T}^{\mu,g}_h f^{t,\mu,g}_{h+1})(s_h^k,a_h^k)\Big)^2\leq\mathcal{O}(\beta_g).
\end{align*}
\end{lemma}
\begin{proof}
The proof is almost the same as Lemma~\ref{lem:bounded error} and thus is omitted here.
\end{proof}
Besides, using performance difference lemma we can easily bridge $\overline{V}^t_r(\mu^t)-V_{r,1}^{\mu^t}(s_1)$ and $\overline{V}^t_g(\mu^t)-V_{g,1}^{\mu^t}(s_1)$ with Bellman residuals, whose proof is also omitted:
\begin{lemma}
\label{lem:performance single}
For any $t\in[K]$, we have
\begin{align*}
&\overline{V}^t_r(\mu^t)-V_{r,1}^{\mu^t}(s_1)=\sum_{h=1}^{H}\mathbb{E}_{\mu^t}[(f^{t,\mu^t,r}_h-\mathcal{T}^{\mu^t,r}f^{t,\mu^t,r}_{h+1})(s_h,a_h)],\\
&\overline{V}^t_g(\mu^t)-V_{g,1}^{\mu^t}(s_1)=\sum_{h=1}^{H}\mathbb{E}_{\mu^t}[(f^{t,\mu^t,g}_h-\mathcal{T}^{\mu^t,g}f^{t,\mu^t,g}_{h+1})(s_h,a_h)].
\end{align*}
\end{lemma}
Therefore, from Lemma~\ref{lem:performance single} we can obtain for any $t\in[K]$,
\begin{align*}
\overline{V}^t_r(\mu^t)-V_{r,1}^{\mu^t}(s_1)=\sum_{h=1}^{H}\mathbb{E}_{\mu^t}[(f^{t,\mu^t,r}_h-\mathcal{T}^{\mu^t,r}f^{t,\mu^t,r}_{h+1})(s_h,a_h)],
\end{align*}
which implies
\begin{align}
\label{eq:regret-bellman cmdp}
\sum_{t=1}^K\overline{V}^t_r(\mu^t)-V_{r,1}^{\mu^t}(s_1)=\sum_{h=1}^{H}\sum_{t=1}^K\mathbb{E}_{\mu^t}[(f^{t,\mu^t,r}_h-\mathcal{T}_h^{\mu^t,r}f^{t,\mu^t,r}_{h+1})(s_h,a_h)].
\end{align}
Similar to Section~\ref{sec:proof sketch}, from Lemma~\ref{lem:BEE}, conditioning on the event in Lemma~\ref{lem:bounded error single} holds true, we have with probability at least $1-\delta/4$
\begin{align*}
&\sum_{t=1}^K\mathbb{E}_{\mu^t}[(f^{t,\mu^t,r}_h-\mathcal{T}^{\mu^t,r}_hf^{t,\mu^t,r}_{h+1})(s_h,a_h)]\notag\\
&\qquad\leq\mathcal{O}\bigg(\sqrt{H^2K\mathrm{dim}_{\mathrm{BEE}}\Big(\mathcal{F},\sqrt{{1}/{K}},\Pi,r\Big)\log(\mathcal{N}_{\mathcal{F}^r\cup\mathcal{G}^r}(H/K)KH|\Pi|/\delta)}\bigg).
\end{align*}
Substitute the above bounds into (\ref{eq:regret-bellman cmdp}) and we have:
\begin{align}
&\sum_{t=1}^K\overline{V}^t_r(\mu^t)-V_{r,1}^{\mu^t}(s_1)\notag\\
&\qquad\leq\mathcal{O}\bigg(H^2\sqrt{K\mathrm{dim}_{\mathrm{BEE}}\Big(\mathcal{F}^r,\sqrt{{1}/{K}},\Pi,r\Big)\log(\mathcal{N}_{\mathcal{F}^r\cup\mathcal{G}^r}(H/K)KH|\Pi|/\delta)}\bigg). \label{eq:estimation r}
\end{align}
Similarly, we have
\begin{align}
&\sum_{t=1}^K\overline{V}^t_g(\mu^t)-V_{g,1}^{\mu^t}(s_1)\notag\\
&\qquad\leq\mathcal{O}\bigg(H^2\sqrt{K\mathrm{dim}_{\mathrm{BEE}}\Big(\mathcal{F}^g,\sqrt{{1}/{K}},\Pi,g\Big)\log(\mathcal{N}_{\mathcal{F}^g\cup\mathcal{G}^g}(H/K)KH|\Pi|/\delta)}\bigg).\label{eq:estimation g}
\end{align}
\paragraph{Step 3: Bound the regret.}
Now we can bound the regret. We first decompose the fictitious total regret $\sum_{t=1}^{K}(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)+Y_t\overline{V}^t_g(\mu^*_{\text{CMDP}}))-\sum_{t=1}^{K}(V_{r,1}^{\mu^t}(s_1)+Y_t\overline{V}^t_g(\mu^t))$ to the following terms:
\begin{align*}
&\sum_{t=1}^{K}(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)+Y_t\overline{V}^t_g(\mu^*_{\text{CMDP}}))-\sum_{t=1}^{K}(V_{r,1}^{\mu^t}(s_1)+Y_t\overline{V}^t_g(\mu^t))\notag\\
&\qquad=\bigg(\underbrace{\sum_{t=1}^{K}V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-\sum_{t=1}^{K}\overline{V}^t_r(\mu^*_{\text{CMDP}})}_{(1)}\bigg)\\
&\qquad\quad+\bigg(\underbrace{\sum_{t=1}^{K}(\overline{V}^t_r(\mu^*_{\text{CMDP}})+Y_t\overline{V}^t_g(\mu^*_{\text{CMDP}}))-\sum_{t=1}^{K}\langle\overline{V}^t_r+Y_t\overline{V}^t_g,p^t\rangle}_{(2)}\bigg)\notag\\
&\qquad\quad+\bigg(\underbrace{\sum_{t=1}^{K}\langle\overline{V}^t_r+Y_t\overline{V}^t_g,p^t\rangle-\sum_{t=1}^{K}(\overline{V}^t_r(\mu^t)+Y_t\overline{V}^t_g(\mu^t))}_{(3)}\bigg)\notag\\
&\qquad\quad+\bigg(\underbrace{\sum_{t=1}^{K}\overline{V}^t_r(\mu^t)-\sum_{t=1}^{K}V_{r,1}^{\mu^t}(s_1)}_{(4)}\bigg).
\end{align*}
From Lemma~\ref{lem:optimism single}, we know $(1)\leq0$. Since $p^t$ is updated using Hedge with loss function $\overline{V}^t$, we have $(2)\leq H(1+\rchi)\sqrt{K\log|\Pi|}$. $(3)$ is a martingale difference sequence, which implies $(3)\leq\mathcal{O}\big(H(1+\rchi)\sqrt{K\log(1/\delta)}\big)$ with probability at least $1-\delta/4$. Finally, Step 2 has bounded term $(4)$ in (\ref{eq:estimation r}), which implies
\begin{align}
&\sum_{t=1}^{K}(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)+Y_t\overline{V}^t_g(\mu^*_{\text{CMDP}}))-\sum_{t=1}^{K}(V_{r,1}^{\mu^t}(s_1)+Y_t\overline{V}^t_g(\mu^t))\notag\\
&\qquad\leq\mathcal{O}\bigg(\bigg(H^2+\frac{H^2}{\lambda_{\mathrm{sla}}}\bigg)\sqrt{Kd_{\mathrm{BEE},r}\log\left(\mathcal{N}_{\mathrm{cov},r}|\Pi|/\delta\right)}\bigg)\label{eq:regrets-1}.
\end{align}
Now we only need to bound $-\sum_{t=1}^K Y_t(\overline{V}^t_g(\mu^*_{\text{CMDP}})-\overline{V}^t_g(\mu^t))$ if we want to bound the regret $\sum_{t=1}^K(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-V_{r,1}^{\mu^t}(s_1))$. In fact, updating the dual variable $Y^t$ with projected gradient descent guarantees us the following lemma:
\begin{lemma}
\label{lem:dual 1}
Suppose the events in Lemma~\ref{lem:optimism single} hold true, we have
\begin{align*}
-\sum_{t=1}^K Y_t(\overline{V}^t_g(\mu^*_{\text{CMDP}})-\overline{V}^t_g(\mu^t))\leq\frac{\alpha H^2K}{2}=\frac{H^2\sqrt{K}}{2}.
\end{align*}
\end{lemma}
\begin{proof}
See Appendix~\ref{proof lemma dual 1}.
\end{proof}
Substituting Lemma~\ref{lem:dual 1} into (\ref{eq:regrets-1}), we can obtain the bound on $\text{Regret}(K)$:
\begin{align*}
&\sum_{t=1}^K(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-V_{r,1}^{\mu^t}(s_1))\leq\mathcal{O}\bigg(\bigg(H^2+\frac{H^2}{\lambda_{\mathrm{sla}}}\bigg)\sqrt{Kd_{\mathrm{BEE},r}\log\left(\mathcal{N}_{\mathrm{cov},r}|\Pi|/\delta\right)}\bigg).
\end{align*}
\paragraph{Step 4: Constraint Violation Analysis.}
Next we need to bound the constraint violation. First notice that $\sum_{t=1}^K Y_t(b-\overline{V}^t_g(\mu^t))$ is indeed not far from $\sum_{t=1}^K Y(b-\overline{V}^t_g(\mu^t))$ for any $Y\in[0,\rchi]$, as shown in the following lemma whose proof is deferred to Appendix~\ref{proof lemma dual 2}:
\begin{lemma}
\label{lem:dual 2}
For any $Y\in[0,\rchi]$, we have
\begin{align*}
\sum_{t=1}^K (Y-Y_t)(b-\overline{V}^t_g(\mu^t))\leq\frac{(H^2+\rchi^2)\sqrt{K}}{2}.
\end{align*}
\end{lemma}
Substituting Lemma~\ref{lem:dual 2} into (\ref{eq:regrets-1}) and notice that $b\leqV_{g,1}^{\mu^*_{\text{CMDP}}}(s_1)\leq\overline{V}^t_g(\mu^*_{\text{CMDP}})$, we have for any $Y\in[0,\rchi]$,
\begin{align*}
&\sum_{t=1}^K(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-V_{r,1}^{\mu^t}(s_1))+Y\sum_{t=1}^K(b-\overline{V}^t_g(\mu^t))\notag\\
&\qquad\leq\mathcal{O}\bigg(\bigg(H^2+\frac{H^2}{\lambda_{\mathrm{sla}}^2}\bigg)\sqrt{Kd_{\mathrm{BEE},r}\log\left(\mathcal{N}_{\mathrm{cov},r}|\Pi|/\delta\right)}\bigg).
\end{align*}
Combining the above inequality with (\ref{eq:estimation g}), we have
\begin{align*}
\sum_{t=1}^K(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-V_{r,1}^{\mu^t}(s_1))+Y\sum_{t=1}^K(b-V_{g,1}^{\mu^t}(s_1))\leq\mathcal{O}\bigg(\bigg(\frac{H^2}{\lambda_{\mathrm{sla}}^2}+\frac{H^3}{\lambda_{\mathrm{sla}}}\bigg)\sqrt{K\eps_{\text{BEE}}}\bigg),
\end{align*}
where
\begin{align*} \eps_{\text{BEE}}=\max\bigg\{&\mathrm{dim}_{\mathrm{BEE}}\Big(\mathcal{F}^r,\sqrt{{1}/{K}},\Pi,r\Big)\log(\mathcal{N}_{\mathcal{F}^r\cup\mathcal{G}^r}(H/K)KH|\Pi|/\delta),\notag\\
&\mathrm{dim}_{\mathrm{BEE}}\Big(\mathcal{F}^g,\sqrt{{1}/{K}},\Pi,g\Big)\log(\mathcal{N}_{\mathcal{F}^g\cup\mathcal{G}^g}(H/K)KH|\Pi|/\delta)\bigg\}.
\end{align*}
Choose $Y$ as
\begin{align*}
Y=
\begin{cases}
0 & \text{if } \sum_{t=1}^K(b-V_{g,1}^{\mu^t}(s_1))<0,\\
\rchi & \text{otherwise}.
\end{cases}
\end{align*}
then we can bound the summation of regret and constraint violation as follows:
\begin{align}
&\bigg(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-\frac{1}{K}\sum_{t=1}^KV_{r,1}^{\mu^t}(s_1)\bigg)+\rchi\bigg[b-\frac{1}{K}\sum_{t=1}^KV_{g,1}^{\mu^t}(s_1)\bigg]_{+}\notag\\
&\qquad\leq\mathcal{O}\bigg(\bigg(\frac{H^2}{\lambda_{\mathrm{sla}}^2}+\frac{H^3}{\lambda_{\mathrm{sla}}}\bigg)\sqrt{{\eps_{\text{BEE}}}/{K}}\bigg).\label{eq:cmdp4}
\end{align}
Further, when Assumption~\ref{ass:strong duality} and Assumption~\ref{ass:slater} hold, we have the following lemma showing that an upper bound on $(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-\frac{1}{K}\sum_{t=1}^KV_{r,1}^{\mu^t}(s_1))+\rchi[b-\frac{1}{K}\sum_{t=1}^KV_{g,1}^{\mu^t}(s_1)]_{+}$ implies an upper bound on $[b-\frac{1}{K}\sum_{t=1}^KV_{g,1}^{\mu^t}(s_1)]_{+}$:
\begin{lemma}
\label{lem:dual 3}
Suppose Assumption~\ref{ass:strong duality} and Assumption~\ref{ass:slater} hold and $2Y^*\leq C^*$. If $\{\mu^t\}_{t=1}^K\subseteq\Pi$ satisfies
\begin{align*}
\bigg(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-\frac{1}{K}\sum_{t=1}^KV_{r,1}^{\mu^t}(s_1)\bigg)+C^*\bigg[b-\frac{1}{K}\sum_{t=1}^KV_{r,1}^{\mu^t}(s_1)\bigg]_{+}\leq\delta,
\end{align*}
Then
\begin{align*}
\bigg[b-\frac{1}{K}\sum_{t=1}^KV_{r,1}^{\mu^t}(s_1)\bigg]_{+}\leq\frac{2\delta}{C^*}.
\end{align*}
\end{lemma}
See Appendix~\ref{proof lemma dual 3} for the proof. Combining Lemma~\ref{lem:dual 3}, Lemma~\ref{lem:duality} and (\ref{eq:cmdp4}), we have
\begin{align*}
\bigg[\sum_{t=1}^K(b-V_{g,1}^{\mu^t}(s_1))\bigg]_{+}\leq\mathcal{O}\bigg(\bigg(H^2+\frac{H}{\lambda_{\mathrm{sla}}}\bigg)\sqrt{K\eps_{\text{BEE}}}\bigg).
\end{align*}
This concludes our proof.
\subsection{Proof of Lemma~\ref{lem:duality}}
\label{proof lemma duality}
Notice that $D(Y^*)=V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)$, which suggests:
\begin{align*}
V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)&=D(Y^*)\geq\mathcal{L}_{\mathrm{CMDP}}(\widetilde{\mu},Y^*)\\
&=V_{r,1}^{\widetilde{\mu}}(s_1)+Y^*(V_{g,1}^{\widetilde{\mu}}(s_1)-b)\geqV_{r,1}^{\widetilde{\mu}}(s_1)+Y^*\lambda_{\mathrm{sla}}.
\end{align*}
This implies that
\begin{align*}
Y^*\leq\frac{V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-V_{r,1}^{\widetilde{\mu}}(s_1)}{\lambda_{\mathrm{sla}}}\leq\frac{H}{\lambda_{\mathrm{sla}}},
\end{align*}
which concludes our proof.
\subsection{Proof of Lemma~\ref{lem:dual 1}}
\label{proof lemma dual 1}
Notice that we have:
\begin{align*}
0&\leq Y_{K+1}^2=\sum_{t=1}^K\left(Y_{t+1}^2-Y_t^2\right)\\
&=\sum_{t=1}^K\left(\left(\text{Proj}_{[0,\rchi]}(Y_t+\alpha(b-\overline{V}^t_g(\mu^t)))\right)^2-Y_t^2\right)\\
&\leq\sum_{t=1}^K\left((Y_t+\alpha(b-\overline{V}^t_g(\mu^t)))^2-Y_t^2\right)\\
&=\sum_{t=1}^K 2\alpha Y_t(b-\overline{V}^t_g(\mu^t))+\sum_{t=1}^K\alpha^2(b-\overline{V}^t_g(\mu^t))^2\\
&\leq\sum_{t=1}^K 2\alpha Y_t(\overline{V}^t_g(\mu^*_{\text{CMDP}})-\overline{V}^t_g(\mu^t))+\alpha^2KH^2,
\end{align*}
where the last step is due to optimism and $V_{g,1}^{\mu^*_{\text{CMDP}}}(s_1)\geq b$. This implies that
\begin{align*}
-\sum_{t=1}^K Y_t(\overline{V}^t_g(\mu^*_{\text{CMDP}})-\overline{V}^t_g(\mu^t))\leq\frac{\alpha H^2K}{2}=\frac{H^2\sqrt{K}}{2}.
\end{align*}
This concludes our proof.
\subsection{Proof of Lemma~\ref{lem:dual 2}}
\label{proof lemma dual 2}
Notice that we have for any $t\in[K]$ and $Y\in[0,\rchi]$:
\begin{align*}
|Y_{t+1}-Y|^2&\leq|Y_t+\alpha(b-\overline{V}^t_g(\mu^t))-Y|^2\\
&=(Y_t-Y)^2+2\alpha(b-\overline{V}^t_g(\mu^t))(Y_t-Y)+\alpha^2H^2.
\end{align*}
Repeating the above expansion procedures, we have
\begin{align*}
0\leq|Y_{K+1}-Y|^2\leq(Y_1-Y)^2+2\alpha\sum_{t=1}^K(b-\overline{V}^t_g(\mu^t))(Y_t-Y)+\alpha^2H^2K,
\end{align*}
which is equivalent to
\begin{align*}
\sum_{t=1}^K(b-\overline{V}^t_g(\mu^t))(Y-Y_t)\leq\frac{1}{2\alpha}(Y_1-Y)^2+\frac{\alpha}{2}H^2K\leq\frac{(H^2+\rchi^2)\sqrt{K}}{2}.
\end{align*}
This concludes our proof.
\subsection{Proof of Lemma~\ref{lem:dual 3}}
\label{proof lemma dual 3}
First we extend $\Pi$ in a reasonable way to make the policy class more structured while not changing its optimal policy. Define the set of state-action visitation distributions induced by the policy $\Pi$ as follows:
\begin{align*}
\mathcal{P}_{\Pi}=\{(d^{\mu}_h(s,a))_{h\in[H],s\in\mathcal{S},a\in\mathcal{A}}\in(\Delta_{|\mathcal{S}|\times|\mathcal{A}|})^H:\mu\in\Pi\}.
\end{align*}
Let $\mathrm{conv}(\mathcal{P}_{\Pi})$ denote the convex hull of $\mathcal{P}_{\Pi}$, i.e., for any $d\in\mathrm{conv}(\mathcal{P}_{\Pi})$, there exists $\{w_{\mu}\}_{\mu\in\Pi}\geq0$ such that for any $h\in[H],s\in\mathcal{S}.a\in\mathcal{A}$, we have
\begin{align*}
d_h(s,a)=\sum_{\mu\in\Pi}w_{\mu}d^{\mu}_h(s,a),\sum_{\mu\in\Pi}w_{\mu}=1.
\end{align*}
As a special case, there exists $d'_h(s,a)\in\mathrm{conv}(\mathcal{P}_{\Pi})$ such that for any $h\in[H],s\in\mathcal{S}.a\in\mathcal{A}$,
\begin{align*}
d'_h(s,a)=\frac{1}{K}\sum_{t=1}^Kd^{\mu^t}_h(s,a).
\end{align*}
Notice that there exists a one-to-one mapping from state-action visitation distributions to policies \citep{puterman1994markov}. Let $\mathrm{conv}(\Pi)$ denote the policy class that induces $\mathrm{conv}(\mathcal{P}_{\Pi})$, and then there exists $\mu'$ such that $d'=d^{\mu'}$, which implies
\begin{align*}
V_{r,1}^{\mu'}(s_1)=\frac{1}{K}\sum_{t=1}^KV_{r,1}^{\mu^t}(s_1),V_{g,1}^{\mu'}(s_1)=\frac{1}{K}\sum_{t=1}^KV_{g,1}^{\mu^t}(s_1).
\end{align*}
Therefore, the condition of this lemma says
\begin{align}
\label{eq:dual-4}
(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-V_{r,1}^{\mu'}(s_1))+C^*[b-V_{g,1}^{\mu'}(s_1)]_{+}\leq\delta.
\end{align}
Next we show that $\mu^*_{\text{CMDP}}$ is still the optimal policy in $\mathrm{conv}(\Pi)$ when Assumption~\ref{ass:strong duality}, i.e., strong duality, holds. First notice that
\begin{align}
\label{eq:dual-1}
\max_{\mu\in\mathrm{conv}(\Pi)}\min_{Y\geq0}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y)\leq\min_{Y\geq0}\max_{\mu\in\mathrm{conv}(\Pi)}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y)=\min_{Y\geq0}\max_{d\in\mathrm{conv}(\mathcal{P}_{\Pi})}\mathcal{L}_{\mathrm{CMDP}}(d,Y).
\end{align}
However, given $Y\geq0$,$\mathcal{L}_{\mathrm{CMDP}}(d,Y)$ is linear in $d$, which means the maximum is always attained at the vertices of $\mathrm{conv}(\mathcal{P}_{\Pi})$, i.e., $\mathcal{P}_{\Pi}$. Therefore we know
\begin{align*}
\max_{\mu\in\mathrm{conv}(\Pi)}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y)=D(Y),
\end{align*}
which suggests
\begin{align}
\label{eq:dual-2}
\min_{Y\geq0}\max_{d\in\mathrm{conv}(\mathcal{P}_{\Pi})}\mathcal{L}_{\mathrm{CMDP}}(d,Y)=\min_{Y\geq0}\max_{d\in\mathcal{P}_{\Pi}}\mathcal{L}_{\mathrm{CMDP}}(d,Y)=\min_{Y\geq0}\max_{\mu\in\Pi}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y).
\end{align}
By strong duality, we have
\begin{align}
\label{eq:dual-3}
\min_{Y\geq0}\max_{\mu\in\Pi}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y)=\max_{\mu\in\Pi}\min_{Y\geq0}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y)\leq\max_{\mu\in\mathrm{conv}(\Pi)}\min_{Y\geq0}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y).
\end{align}
Combining (\ref{eq:dual-1}),(\ref{eq:dual-2}) and (\ref{eq:dual-3}), we know all the inequalities have to take equality, which implies
\begin{align*}
\mu^*_{\text{CMDP}}=\arg\max_{\mu\in\mathrm{conv}(\Pi)}\min_{Y\geq0}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y), Y^*=\arg\min_{Y\geq0}\max_{\mu\in\mathrm{conv}(\Pi)}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y).
\end{align*}
Besides, strong duality also holds for $\max_{\mu\in\mathrm{conv}(\Pi)}\min_{Y\geq0}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y)$.
Now let $v(\tau):=\max_{\mu\in\mathrm{conv}(\Pi)}\{V_{r,1}^{\mu}(s_1)|V_{g,1}^{\mu}(s_1)\geq b+\tau\}$, then we have for any $\mu\in\mathrm{conv}(\Pi)$,
\begin{align*}
\mathcal{L}_{\mathrm{CMDP}}(\mu,Y^*)&\leq\max_{\mu\in\mathrm{conv}(\Pi)}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y^*)=D(Y^*)=V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1),
\end{align*}
where the third step comes from strong duality. Therefore, for any $\mu\in\mathrm{conv}(\Pi)$ and $\tau\in\mathbb{R}$ which satisfies $V_{g,1}^{\mu}(s_1)\geq b+\tau$, we have
\begin{align*}
V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-\tau Y^*&\geq\mathcal{L}_{\mathrm{CMDP}}(\mu,Y^*)-\tau Y^*\\
&=V_{r,1}^{\mu}(s_1)+Y^*(V_{g,1}^{\mu}(s_1)-b-\tau)\geqV_{r,1}^{\mu}(s_1).
\end{align*}
This implies that for any $\tau\in\mathbb{R}$, $V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-\tau Y^*\geq v(\tau)$. Pick $\tau=\widetilde{\tau}:=-[b-V_{g,1}^{\mu'}(s_1)]_+$, then we have
\begin{align*}
V_{r,1}^{\mu'}(s_1)-V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)\leq -\widetilde{\tau} Y^*.
\end{align*}
On the other hand, (\ref{eq:dual-4}) is equivalent to
\begin{align*}
V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-V_{r,1}^{\mu'}(s_1)-C^*\widetilde{\tau}\leq\delta.
\end{align*}
Thus we have $(C^*-Y^*)|\widetilde{\tau}|\leq\delta$, which means that
\begin{align*}
[b-V_{g,1}^{\mu'}(s_1)]_+\leq\frac{\delta}{C^*-Y^*}\leq\frac{2\delta}{C^*}.
\end{align*}
Recall that $V_{g,1}^{\mu'}(s_1)=\frac{1}{K}\sum_{t=1}^KV_{g,1}^{\mu^t}(s_1)$, which concludes our proof.
\section{Proof of Corollary~\ref{cor:selfplay}}
\label{proof corollary selfplay}
From Theorem~\ref{thm:adaptive}, we have with probability at least $1-{\delta}$, for all $i\in[n]$
\begin{align*}
\max_{\mu_i\in\Pi_i}\frac{1}{K}\sum_{t=1}^KV_{1,i}^{\mu_i\times\mu_{-i}^t}(s_1)\leq\frac{1}{K}\sum_{t=1}^KV_{1,i}^{\mu_i^t\times\mu_{-i}^t}(s_1)+{\epsilon}.
\end{align*}
By the definition of $\widehat{\pi}$, this is equivalent to
\begin{align*}
\max_{\mu_i\in\Pi_i}V_{1,i}^{\mu_i\times\widehat{\mu}_{-i}}(s_1)\leq V_{1,i}^{\widehat{\pi}}(s_1)+{\epsilon},
\end{align*}
where $\widehat{\mu}_{-i}$ is uniformly sampled from $\{\mu^t_{-i}\}_{t=1}^K$ and thus is the marginal distribution of $\widehat{\pi}$ over the agents other than $i$. Therefore, by the definition of CCE in (\ref{eq:def cce}), $\widehat{\pi}$ is $\epsilon$-approximate CCE with probability at least $1-\delta$, which concludes our proof.
\section{Examples for BEE Dimension}
\label{sec:example}
In this section we will show that kernel MGs (including tabular MGs and linear MGs) and generalized linear complete models have low BEE dimensions.
\subsection{Kernel MGs}
Consider the kernel MG defined in Definition~\ref{def:kernel MG} and $\mathcal{F}_h=\{\phi_h(\cdot)^{\top}w|w\in\mathcal{B}_{\mathcal{H}}(H-h+1)\}$, then we have the following proposition showing that the BEE dimension of a kernel MG is upper bounded by its effective dimension (Definition~\ref{def:effect}):
\begin{proposition}
\label{prop:BEE kernel}
If the kernel MG has effective dimension $d(\epsilon)$, then for any policy classes $\Pi$ and $\Pi'$, we have $d_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi')\leq d({\epsilon}/{2H})$.
\end{proposition}
\begin{proof}
First in Appendix~\ref{sec:realize} we have showed that $\mathcal{F}$ satisfies completeness. By Proposition~\ref{prop:BEE}, we have $d_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi')\leq\max_{h\in[H]}\mathrm{dim}_{\mathrm{E}}(\mathcal{F}_h,\epsilon)$. Therefore we only need to bound $\mathrm{dim}_{\mathrm{E}}(\mathcal{F}_h,\epsilon)$ for each $h\in[H]$. Suppose $\mathrm{dim}_{\mathrm{E}}(\mathcal{F}_h,\epsilon)=k>d({\epsilon}/{2H})$. Then by the definition of Eluder dimension, there exists a sequence $\phi_1,\cdots,\phi_k$ and $\{w_{1,i}\}_{i=1}^k,\{w_{2,i}\}_{i=1}^k$ where $\phi_i\in\mathcal{X}_h=\{\phi_h(s,a,b):(s,a,b)\in\mathcal{S}\times\mathcal{A}\times\mathcal{B}\}, w_{1,i},w_{2,i}\in\mathcal{B}_{\mathcal{H}}(H-h+1)$ for all $i$ such that for any $t\in[k]$:
\begin{align}
&\sum_{i=1}^{t-1}(\langle \phi_i,w_{1,t}-w_{2,t}\rangle)^2\leq(\epsilon')^2,\label{eq:eg 1}\\
&|\langle\phi_t,w_{1,t}-w_{2,t}\rangle|\geq\epsilon'\label{eq:eg 2},
\end{align}
where $\epsilon'\geq\epsilon$. Let $\Sigma_t$ denote $\sum_{i=1}^{t-1}\phi_i\phi_i^{\top}+\frac{\epsilon^2}{4H^2}\cdot I$. Then we have for any $t\in[k]$
\begin{align*}
\Vert w_{1,t}-w_{2,t}\Vert_{\Sigma_t}^2\leq(\epsilon')^2+\epsilon^2.
\end{align*}
On the other hand, by Cauchy-Schwartz inequality we know
\begin{align*}
\Vert \phi_t\Vert_{\Sigma_t^{-1}}\Vert w_{1,t}-w_{2,t}\Vert_{\Sigma_t}\geq|\langle\phi_t,w_{1,t}-w_{2,t}\rangle|\geq\epsilon'.
\end{align*}
This implies for all $t\in[k]$
\begin{align*}
\Vert \phi_t\Vert_{\Sigma_t^{-1}}\geq\frac{\epsilon'}{\sqrt{\epsilon^2+(\epsilon')^2}}\geq\frac{1}{\sqrt{2}}.
\end{align*}
Therefore, applying elliptical potential lemma (e.g., Lemma~5.6 and Lemma~F.3 in \cite{du2021bilinear}), we have for any $t\in[k]$
\begin{align*}
\log\det\bigg(I+\frac{4H^2}{\epsilon^2}\sum_{i=1}^{t}\phi_i\phi_i^{\top}\bigg)=\sum_{i=1}^t\log(1+\Vert \phi_i\Vert_{\Sigma_i^{-1}}^2)\geq t\cdot\log\frac{3}{2}.
\end{align*}
However, by the definition of effective dimension, we know when $n=d_{\mathrm{eff}}(\mathcal{X}_h,\frac{\epsilon}{2H})$,
\begin{align*}
\sup_{\phi_1,\cdots,\phi_n}\log\det\bigg(I+\frac{4H^2}{\epsilon^2}\sum_{i=1}^n\phi_i\phi_i^{\top}\bigg)\leq ne^{-1}.
\end{align*}
This is a contradiction since $n\leq d({\epsilon}/{2H})<k$ and $\log\frac{3}{2}>e^{-1}$. Therefore we have $\mathrm{dim}_{\mathrm{E}}(\mathcal{F}_h,\epsilon)\leq d({\epsilon}/{2H})$ for all $h\in[H]$, which implies
\begin{align*}
d_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi')\leq d({\epsilon}/{2H}).
\end{align*}
This concludes our proof.
\end{proof}
\paragraph{Tabular MGs.} Tabular MGs are a special case of kernel MGs where the feature vectors are $|\mathcal{S}||\mathcal{A}||\mathcal{B}|$-dimensional one-hot vectors. From the standard elliptical potential lemma, we know $d(\epsilon)=\widetilde{\mathcal{O}}(|\mathcal{S}||\mathcal{A}||\mathcal{B}|)$ for tabular MDPs, suggesting their BEE dimension is also upper bounded $\widetilde{\mathcal{O}}(|\mathcal{S}||\mathcal{A}||\mathcal{B}|)$.
\paragraph{Linear MGs.} When the feature vectors are $d$-dimensional, we can recover linear MGs. Similarly, by the standard elliptical potential lemma, we have the BEE dimension of linear MGs is upper bounded $\widetilde{\mathcal{O}}(d)$.
\subsection{Generalized Linear Complete Models}
An important variant of linear MDPs is the generalized linear complete models proposed by \cite{wang2019optimism}. Here we also generalize it into Markov games:
\begin{definition}[Generalized linear complete models]
In $d$-dimensional generalized linear complete models, for each step $h\in[H]$, there exists a feature mapping $\phi_{h}:\mathcal{S}\times\mathcal{A}\times\mathcal{B}\mapsto\mathbb{R}^d$ and a link function $\sigma$ such that:
\begin{itemize}
\item for the generalized linear function class $\mathcal{F}_h=\{\sigma(\phi_h(\cdot)^{\top}w)|w\in\mathcal{W}\}$ where $\mathcal{W}\subset\mathbb{R}^d$, realizability and completeness are both satisfied;
\item the link function is strictly monotone, i.e., there exist $0<c_1<c_2<\infty$ such that $\sigma'\in[c_1,c_2]$.
\item $\phi_h,w$ satisfy the regularization conditions: $\Vert\phi_h(s,a,b)\Vert\leq R, \Vert w\Vert\leq R$ for all $s,a,b,h$ where $R>0$ is a constant.
\end{itemize}
\end{definition}
When the link function is $\sigma(x)=x$, the generalized linear complete models reduce to the linear complete models, which contain instances such as linear MGs and LQRs. The following proposition shows that generalized linear complete models also have low BEE dimensions:
\begin{proposition}
\label{prop:BEE generalized}
If a generalized linear complete model has dimension $d$, then for any policy classes $\Pi$ and $\Pi'$, its BEE dimension can be bounded as follows:
\begin{align*}
d_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi')\leq \widetilde{\mathcal{O}}(d{c_2^2}/{c_1^2}).
\end{align*}
\end{proposition}
\begin{proof}
The proof is similar to Proposition~\ref{prop:BEE kernel}, except (\ref{eq:eg 1}) and (\ref{eq:eg 2}) become
\begin{align*}
&\sum_{i=1}^{t-1}c_1^2(\langle \phi_i,w_{1,t}-w_{2,t}\rangle)^2\leq\sum_{i=1}^{t-1}(\sigma(\phi_i^{\top} w_{1,t})-\sigma(\phi_i^{\top} w_{2,t}))^2\leq(\epsilon')^2,\\\
&c_2|\langle\phi_t,w_{1,t}-w_{2,t}\rangle|\geq|\sigma(\phi_t^{\top} w_{1,t})-\sigma(\phi_t^{\top} w_{2,t})|\geq\epsilon'.
\end{align*}
Then repeat the arguments in the proof of Proposition~\ref{prop:BEE kernel}, we have $\mathrm{dim}_{\mathrm{E}}(\mathcal{F}_h,\epsilon)\leq\widetilde{\mathcal{O}}(d{c_2^2}/{c_1^2})$ for all $h\in[H]$. Since $\mathcal{F}$ satisfies completeness, we can use Proposition~\ref{prop:BEE} and obtain
\begin{align*}
d_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,\Pi')\leq \widetilde{\mathcal{O}}(d{c_2^2}/{c_1^2}).
\end{align*}
\end{proof}
\section{Examples for Realizability, Generalized Completeness and Covering Number}
\label{sec:realize}
In this section we illustrate practical examples where realizability and generalized completeness hold while the covering number is upper bounded at the same time. More specifically, we will consider tabular MGs, linear MGs and kernel MGs.
\subsection{Tabular MGs}
For tabular MGs, we let $\mathcal{F}_h=\{f|f:\mathcal{S}\times\mathcal{A}\times\mathcal{B}\mapsto[0,V_{\max}]\}$ and $\mathcal{G}_h=\mathcal{F}_h$ for all $h\in[H]$. Then it is obvious that $Q^{\mu\times\nu}_h\in\mathcal{F}_h$ and $\mathcal{T}^{\mu,\nu}f_{h+1}\in\mathcal{G}_h$ for any $f\in\mathcal{F},h\in[H],\mu,\nu$, which implies that realizability and generalized completeness are satisfied. In addition, notice that in this case we have
\begin{align*}
\log\mathcal{N}_{\mathcal{F}_h}(\epsilon)=\log\mathcal{N}_{\mathcal{G}_h}(\epsilon)\leq|\mathcal{S}||\mathcal{A}||\mathcal{B}|\log({V_{\max}}/{\epsilon}).
\end{align*}
This suggests that the size of $\mathcal{F}$ and $\mathcal{G}$ is also not too large.
\subsection{Linear MGs}
In this subsection we consider linear MGs. Here we generalize the definition of linear MDPs in classic MDPs \citep{jin2020provably} to Markov games:
\begin{definition}[Linear MGs]
We say an MG is linear of dimension $d$ if for each $h\in[H]$, there exists a feature mapping $\phi_h:\mathcal{S}\times\mathcal{A}\times\mathcal{B}\mapsto\mathbb{R}^d$ and $d$ unknown signed measures $\psi_h=(\psi_h^{(1)},\cdots,\psi_h^{(d)})$ over $\mathcal{S}$ and an unknown vector $\theta_h\in\mathbb{R}^d$ such that $P_h(\cdot|s,a,b)=\phi_{h}(s,a,b)^{\top}\psi_h(\cdot)$ and $r_{h}(s,a,b)=\phi_h(s,a,b)^{\top}\theta_h$ for all $(s,a,b)\in\mathcal{S}\times\mathcal{A}\times\mathcal{B}$.
\end{definition}
Without loss of generality, we assume $\Vert\phi_h(s,a,b)\Vert\leq1$ for all $s\in\mathcal{S},a\in\mathcal{A},b\in\mathcal{B}$ and $\Vert\psi_h(\mathcal{S})\Vert\leq\sqrt{d},\theta_h\leq\sqrt{d}$ for all $h$. Let $\mathcal{F}_h=\mathcal{G}_h=\{\phi_h(\cdot)^{\top}w|w\in\mathbb{R}^d,\Vert w\Vert\leq (H-h+1)\sqrt{d},0\leq\phi_h(\cdot)^{\top}w\leq H-h+1\}$.
\paragraph{Realizability.}
We have for any $\mu,\nu$,
\begin{align*}
Q^{\mu\times\nu}_h(s,a,b)&=r_h(s,a,b)+\mathbb{E}_{s'\sim P(\cdot|s,a,b)}[V^{\mu\times\nu}_{h+1}(s')]\\
&=\langle \phi_h(s,a,b),\theta_h\rangle + \bigg\langle \phi_h(s,a,b),\int_{\mathcal{S}}V^{\mu\times\nu}_{h+1}(s')d\psi_h(s')\bigg\rangle\\
&=\bigg\langle \phi_h(s,a,b), \theta_h+\int_{\mathcal{S}}V^{\mu\times\nu}_{h+1}(s')d\psi_h(s')\bigg\rangle\\
&=\langle \phi_h(s,a,b), w^{\mu\times\nu}_h\rangle,
\end{align*}
where $w^{\mu\times\nu}_h=\theta_h+\int_{\mathcal{S}}V^{\mu\times\nu}_{h+1}(s')d\psi_h(s')$ and thus $\Vert w^{\mu\times\nu}_h\Vert\leq (H-h+1)\sqrt{d}$. Therefore, $Q^{\mu\times\nu}_h\in\mathcal{F}_h$, which means that realizability holds.
\paragraph{Generalized completeness.} For any $f_{h+1}\in\mathcal{F}_{h+1}$, we have
\begin{align*}
\mathcal{T}^{\mu,\nu}f_{h+1}(s,a,b)&=r_h(s,a,b)+\mathbb{E}_{s'\sim P(\cdot|s,a,b)}[f_{h+1}(s',\mu,\nu)]\\
&=\bigg\langle \phi_h(s,a,b), \theta_h+\int_{\mathcal{S}}f_{h+1}(s',\mu,\nu)d\psi_h(s')\bigg\rangle.
\end{align*}
Since $\Vert f_{h+1}\Vert_{\infty}\leq H-h$, we have $\Vert \theta_h+\int_{\mathcal{S}}f_{h+1}(s',\mu,\nu)d\psi_h(s')\Vert\leq (H-h+1)\sqrt{d}$, which indicates $\mathcal{T}^{\mu,\nu}f_{h+1}\in\mathcal{G}_h$ and thus generalized completeness is satisfied.
\paragraph{Covering number.} First notice that from the literature \citep{wainwright2019high}, the covering number of a $l_2$-norm ball can be bounded as $\log\mathcal{N}_{\mathbb{B}((H-h+1)\sqrt{d})}(\epsilon)\leq d\log({3H\sqrt{d}}/{\epsilon})$. Therefore, there exists $\mathcal{W}\subset\mathbb{B}((H-h+1)\sqrt{d})$ where $\log|\mathcal{W}|\leq d\log({3H\sqrt{d}}/{\epsilon})$ such that for any $w\in\mathbb{B}((H-h+1)\sqrt{d})$, there exists $w'\in\mathcal{W}$ satisfying $\Vert w'-w\Vert\leq \epsilon$. Now let $\mathcal{F}'_h=\{\phi_h(\cdot)^{\top}w|w\in\mathcal{W}\}$. For any $f_h\in\mathcal{F}_h$, suppose $f_h(\cdot)=\phi_h(\cdot)^{\top} w_{f_h}$. Then we know there exists $f'_h(\cdot)=\phi_h(\cdot)^{\top} w'_{f_h}\in\mathcal{F}'_h$ where $\Vert w'_{f_h}-w_{f_h}\Vert\leq \epsilon$, which implies
\begin{align*}
|f_h(s,a,b)-f'_h(s,a,b)|\leq\Vert\phi_h(s,a,b)\Vert\Vert w'_{f_h}-w_{f_h}\Vert\leq\epsilon.
\end{align*}
Therefore $\log\mathcal{N}_{\mathcal{F}_h}(\epsilon)\leq\log|\mathcal{F}'_h|=\log|\mathcal{W}|\leq d\log({3H\sqrt{d}}/{\epsilon})$.
\subsection{Kernel MGs}
In this subsection we show that kernel MGs also satisfy realizability and generalized completeness naturally. In addition, when a kernel MG has a bounded effective dimension, its covering number will also be bounded. First we generalize the definition of kernel MDPs \cite{jin2021bellman} to MGs as follows.
\begin{definition}[Kernel MGs]
\label{def:kernel MG}
In a kernel MDP, for each step $h\in[H]$, there exist feature mapping $\phi_h:\mathcal{S}\times\mathcal{A}\times\mathcal{B}\mapsto\mathcal{H}$ and $\psi_h:\mathcal{S}\mapsto\mathcal{H}$ where $\mathcal{H}$ is a separable Hilbert space such that $P_h(s'|s,a,b)=\langle\phi_h(s,a,b),\psi_h(s')\rangle_{\mathcal{H}}$ for all $s\in\mathcal{S},a\in\mathcal{A},b\in\mathcal{B},s'\in\mathcal{S}$. Besides, the reward function os linear in $\phi$, i.e., $r_h(s,a,b)=\langle \phi_h(s,a,b),\theta_h\rangle_{\mathcal{H}} $ for some $\theta_h\in\mathcal{H}$. Moreover, a kernel MG satisfies the following regularization conditions:
\begin{itemize}
\item $\Vert\theta_h\Vert_{\mathcal{H}}\leq1,\Vert\phi_h(s,a,b)\Vert_{\mathcal{H}}\leq1$, for all $ s\in\mathcal{S},a\in\mathcal{A},b\in\mathcal{B},h\in[H]$.
\item $\Vert\sum_{s\in\mathcal{S}}V(s)\psi_h(s)\Vert_{\mathcal{H}}\leq1$, for all function $V:\mathcal{S}\mapsto[0,1], h\in[H]$.
\end{itemize}
\end{definition}
\begin{remark}
It can be observed that tabular and linear MGs are special cases of kernel MGs. Therefore, the following discussion applies to tabular and linear MGs as well.
\end{remark}
Then we let $\mathcal{F}_h=\mathcal{G}_h=\{\phi_h(\cdot)^{\top}w|w\in\mathcal{B}_{\mathcal{H}}(H-h+1)\}$ where $\mathcal{B}_{\mathcal{H}}(r)$ is a ball with radius $r$ in $\mathcal{H}$. Following the same arguments in linear MGs, we can validate that realizability and generalized completeness are satisfied in kernel MGs.
\paragraph{Covering number.} Before bounding the covering number of $\mathcal{F}_h$, we need introduce a new measure to evaluate the complexity of a Hilbert space since $\mathcal{H}$ might be infinite dimensional. Here we use the effective dimension \citep{du2021bilinear,jin2021bellman}, which is defined as follows:
\begin{definition}[$\epsilon$-effective dimension of a set]
\label{def:effect}
The $\epsilon$-effective dimension of a set $\mathcal{X}$ is the minimum integer $d_{\mathrm{eff}}(\mathcal{X},\epsilon)=n$ such that
\begin{align*}
\sup_{x_1,\cdots,x_n\in\mathcal{X}}\frac{1}{n}\log\det\bigg(I+\frac{1}{\epsilon^2}\sum_{i=1}^nx_ix_i^{\top}\bigg)\leq e^{-1}.
\end{align*}
\end{definition}
\begin{remark}
When $\mathcal{X}$ is finite dimensional, suppose its dimension is $d$. Then its effective dimension can be upper bounded by $\mathcal{O}\big(d\log\big(1+{R^2}/{\epsilon}\big)\big)$ where $R$ is the norm bound of $\mathcal{X}$ \citep{du2021bilinear}. In addition, even when $\mathcal{X}$ is infinite dimensional, if the eigenspectrum of the covariance matrices concentrates in a low-dimension
subspace, the effective dimension of $\mathcal{X}$ can still be small \citep{srinivas2009gaussian}.
\end{remark}
We call a kernel MG is of effective dimension $d(\epsilon)$ if $d_{\mathrm{eff}}(\mathcal{X}_h,\epsilon)\leq d(\epsilon)$ for all $h$ and $\epsilon$ where $\mathcal{X}_h=\{\phi_h(s,a,b):(s,a,b)\in\mathcal{S}\times\mathcal{A}\times\mathcal{B}\}$. Then the following proposition shows that the covering number of $\mathcal{F}_h$ is upper bounded by the effective dimension of the kernel MG:
\begin{proposition}
\label{prop:covering}
If the kernel MG has effective dimension $d(\epsilon)$, then
\begin{align*}
\log\mathcal{N}_{\mathcal{F}_h}(\epsilon)\leq\mathcal{O}\big(d({\epsilon}/{2H})\log(1+{Hd({\epsilon}/{2H})}/{\epsilon})\big).
\end{align*}
\end{proposition}
\begin{proof}
Suppose $\mathrm{dim}_{\mathrm{E}}(\mathcal{F}_h,\epsilon)=n$. Then by the definition of Eluder dimension, there exists a sequence $\{\phi_i\}_{i=1}^n$ such that for any $w_1,w_2\in\mathbb{B}_{\mathcal{H}}(H-h+1),\phi\in\mathcal{X}_h$, if $\sum_{i=1}^n(\langle \phi_i, w_1-w_2\rangle)^2\leq\epsilon^2$, then $|\langle \phi, w_1-w_2\rangle|\leq\epsilon$. Therefore, the covering number of kernel MGs can be reduced to covering the projection of $\mathbb{B}_{\mathcal{H}}(H-h+1)$ onto the space spanned by $\{\phi_i\}_{i=1}^n$, whose dimension is at most $n$. From the literature \citep{wainwright2019high}, the covering number of such space is $\mathcal{O}\left(n\log\left(1+{nH}/{\epsilon}\right)\right)$, which implies
\begin{align*}
\log\mathcal{N}_{\mathcal{F}_h}(\epsilon)\leq\mathcal{O}\big(n\log(1+{nH}/{\epsilon})\big).
\end{align*}
Finally, by the proof of Proposition~\ref{prop:BEE kernel}, we know $n\leq d({\epsilon}/{2H})$, which concludes the proof.
\end{proof}
\section{Proof of Theorem~\ref{thm:vmdp}}
\label{proof:thm vmdp}
In this section we present the proof for Theorem~\ref{thm:vmdp}. Our proof mainly consists of four steps:
\begin{itemize}
\item Prove $\langle\underline{\boldsymbol{V}}^t(\mu),\boldsymbol{\theta}_t\rangle$ is a pessimistic estimations of $ \langle \boldsymbol{V}^{\mu}_1(s_1),\boldsymbol{\theta}_t\rangle$ for all $t\in[K]$ and $\mu\in\Pi$.
\item Bound the total estimation error $\Vert\frac{1}{K}\sum_{t=1}^K\underline{\boldsymbol{V}}^t(\mu^t)-\boldsymbol{V}_1^{\mu^t}(s_1)\Vert$.
\item Bound $\mathrm{dist}(\boldsymbol{V}^{\widehat{\mu}}_1(s_1),\mathcal{C})$.
\end{itemize}
\paragraph{Step 1: Prove pessimism.}
First we can show that the true action-value function $\boldsymbol{Q}^{\mu}$ belongs to the constructed set $\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu)$ with high probability:
\begin{lemma}
\label{lem:optimism vmdp}
With probability at least $1-{\delta}/{4}$, we have for all $t\in[K]$ and $\mu\in\Pi$, $\boldsymbol{Q}^{\mu}\in\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu)$.
\end{lemma}
\begin{proof}
Repeat the arguments in the proof of Lemma~\ref{lem:optimism} for each dimension $j\in[d]$ and the lemma follows directly.
\end{proof}
Then since $\underline{\boldsymbol{V}}^t(\mu)=f_1(s_1,\mu)$ where $f=\arg\min_{f'\in\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu)}\langle f'_1(s_1,\mu),\boldsymbol{\theta}_t\rangle$, we know for all $t\in[K]$ and $\mu\in\Pi$,
\begin{align*}
\langle\underline{\boldsymbol{V}}^t(\mu),\boldsymbol{\theta}_t\rangle\leq \langle\boldsymbol{Q}^{\mu}_1(s_1,\mu),\boldsymbol{\theta}_t\rangle=\langle\boldsymbol{V}^{\mu}_1(s_1),\boldsymbol{\theta}_t\rangle.
\end{align*}
\paragraph{Step 2: Bound estimation error.}
Next we need to show the estimation error $\Vert\frac{1}{K}\sum_{t=1}^K\break\underline{\boldsymbol{V}}^t(\mu^t)-\boldsymbol{V}_1^{\mu^t}(s_1)\Vert$ is small. Let $f^{t,\mu}=\arg\min_{f\in\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu)}\langle f_1(s_1,\mu),\boldsymbol{\theta}_t\rangle$. Let $f^{t,\mu,j}$ denotes the $j$-the dimension of $f^{t,\mu}$. Then we have
\begin{lemma}
\label{lem:bounded error vmdp}
With probability at least $1-{\delta}/{4}$, we have for all $t\in[K]$, $h\in[H]$, $j\in[d]$ and $\mu\in\Pi$,
\begin{align*}
(a)\quad&\sum_{k=1}^{t-1}\mathbb{E}_{\mu^k}\bigg[\Big(f^{t,\mu,j}_h(s_h,a_h)-(\mathcal{T}^{\mu,j}_h f^{t,\mu,j}_{h+1})(s_h,a_h)\Big)^2\bigg]\leq\mathcal{O}(\beta),\\
(b)\quad&\sum_{k=1}^{t-1}\Big(f^{t,\mu,j}_h(s_h^k,a_h^k)-(\mathcal{T}^{\mu,j}_h f^{t,\mu,j}_{h+1})(s_h^k,a_h^k)\Big)^2\leq\mathcal{O}(\beta),\\
\end{align*}
\end{lemma}
\begin{proof}
Repeat the arguments in the proof of Lemma~\ref{lem:bounded error} for each dimension $j\in[d]$ and the lemma follows directly.
\end{proof}
Besides, using performance difference lemma we have:
\begin{lemma}
\label{lem:performance vmdp}
For any $t\in[K]$ and $j\in[d]$, we have
\begin{align*}
\underline{{V}}^{t,j}(\mu^t)-V^{\mu^t,j}_{1}(s_1)=\sum_{h=1}^{H}\mathbb{E}_{\mu^t}[(f^{t,\mu^t,j}_h-\mathcal{T}^{\mu^t,j}f^{t,\mu^t,j}_{h+1})(s_h,a_h)],
\end{align*}
where $\underline{{V}}^{t,j}(\mu^t)$ is the $j$-th dimension of $\underline{\boldsymbol{V}}^t(\mu^t)$.
\end{lemma}
Therefore, from Lemma~\ref{lem:performance vmdp} we can obtain for any $t\in[K]$ and $j\in[d]$
\begin{align}
\label{eq:regret-bellman vmdp}
\sum_{t=1}^K\underline{{V}}^{t,j}(\mu^t)-V^{\mu^t,j}_{1}(s_1)=\sum_{h=1}^{H}\sum_{t=1}^K\mathbb{E}_{\mu^t}[(f^{t,\mu^t,j}_h-\mathcal{T}_h^{\mu^t,j}f^{t,\mu^t,j}_{h+1})(s_h,a_h)].
\end{align}
Similar to Section~\ref{sec:proof sketch}, from Lemma~\ref{lem:BEE}, conditioning on the event in Lemma~\ref{lem:bounded error vmdp} holds true, with probability at least $1-\delta/4$, we have for any $j\in[d]$ and $h\in[H]$,
\begin{align*}
&\bigg|\sum_{t=1}^K\mathbb{E}_{\mu^t}\big[(f^{t,\mu^t,j}_h-\mathcal{T}^{\mu^t,j}_hf^{t,\mu^t,j}_{h+1})(s_h,a_h)\big]\bigg|\leq\mathcal{O}\Big(\sqrt{H^2Kd_{\mathrm{BEE,V}}\log\left(\mathcal{N}_{\mathrm{cov,V}}|\Pi|d/\delta\right)}\Big).
\end{align*}
Substitute the above bounds into (\ref{eq:regret-bellman vmdp}) and we have for any $j\in[d]$:
\begin{align*}
\bigg|\sum_{t=1}^K\underline{{V}}^{t,j}(\mu^t)-V^{\mu^t,j}_{1}(s_1)\bigg|\leq\mathcal{O}\big(H^2\sqrt{Kd_{\mathrm{BEE,V}}\log(\mathcal{N}_{\mathrm{cov,V}}|\Pi|d/\delta)}\big),
\end{align*}
which implies if the event in Lemma~\ref{lem:bounded error vmdp} is true,
\begin{align*}
\bigg\Vert\frac{1}{K}\sum_{t=1}^K\underline{\boldsymbol{V}}^t(\mu^t)-\boldsymbol{V}^{\mu^t}_1(s_1)\bigg\Vert\leq\mathcal{O}\big(H^2\sqrt{d}\cdot\sqrt{{d_{\mathrm{BEE,V}}\log(\mathcal{N}_{\mathrm{cov,V}}|\Pi|d/\delta)}/{K}}\big).
\end{align*}
\paragraph{Step 3: Bound the distance.}
Now we can bound the distance $\mathrm{dist}(\boldsymbol{V}^{\widehat{\mu}}(s_1),\mathcal{C})$. First since $\widehat{\mu}$ is sampled uniformly from $\{\mu^t\}_{t=1}^K$, we know
\begin{align*}
\mathrm{dist}(\boldsymbol{V}^{\widehat{\mu}}_1(s_1),\mathcal{C})=\mathrm{dist}\bigg(\frac{1}{K}\sum_{t=1}^K\boldsymbol{V}^{\mu^t}_1(s_1),\mathcal{C}\bigg).
\end{align*}
By Fenchel's duality, we know
\begin{align*}
&\mathrm{dist}\bigg(\frac{1}{K}\sum_{t=1}^K\boldsymbol{V}^{\mu^t}_1(s_1),\mathcal{C}\bigg)=\max_{\boldsymbol{\theta}\in\mathbb{B}(1)}\bigg[\bigg\langle \boldsymbol{\theta},\frac{1}{K}\sum_{t=1}^K\boldsymbol{V}^{\mu^t}_1(s_1)\bigg\rangle-\max_{\boldsymbol{x}\in\mathcal{C}}\langle\boldsymbol{\theta},\boldsymbol{x}\rangle\bigg]\\
&\qquad\leq\max_{\boldsymbol{\theta}\in\mathbb{B}(1)}\bigg[\bigg\langle \boldsymbol{\theta},\frac{1}{K}\sum_{t=1}^K\underline{\boldsymbol{V}}^t(\mu^t)\bigg\rangle-\max_{\boldsymbol{x}\in\mathcal{C}}\langle\boldsymbol{\theta},\boldsymbol{x}\rangle\bigg]+\max_{\boldsymbol{\theta}\in\mathbb{B}(1)}\bigg\langle \boldsymbol{\theta},\frac{1}{K}\sum_{t=1}^K\boldsymbol{V}^{\mu^t}_1(s_1)-\underline{\boldsymbol{V}}^t(\mu^t)\bigg\rangle,
\end{align*}
where the second step is due to $\max[f_1+f_2]\leq\max f_1+\max f_2$.
Notice by Cauchy-Schwartz inequality and Step 2, we have
\begin{align*}
&\max_{\boldsymbol{\theta}\in\mathbb{B}(1)}\bigg\langle \boldsymbol{\theta},\frac{1}{K}\sum_{t=1}^K\boldsymbol{V}^{\mu^t}_1(s_1)-\underline{\boldsymbol{V}}^t(\mu^t)\bigg\rangle\leq\bigg\Vert\frac{1}{K}\sum_{t=1}^K\underline{\boldsymbol{V}}^t(\mu^t)-\boldsymbol{V}^{\mu^t}_1(s_1)\bigg\Vert\\
&\qquad\leq\mathcal{O}\big(H^2\sqrt{d}\cdot\sqrt{{d_{\mathrm{BEE,V}}\log(\mathcal{N}_{\mathrm{cov,V}}|\Pi|d/\delta}/{K}}\big).
\end{align*}
Now we only need to bound $\max_{\boldsymbol{\theta}\in\mathbb{B}(1)}\left[\langle \boldsymbol{\theta},\frac{1}{K}\sum_{t=1}^K\underline{\boldsymbol{V}}^t(\mu^t)\rangle-\max_{\boldsymbol{x}\in\mathcal{C}}\langle\boldsymbol{\theta},\boldsymbol{x}\rangle\right]$. Recall that we update $\boldsymbol{\theta}_t$ using online gradient descent. Using the conclusions from the online learning literature \citep{hazan2016introduction}, we know
\begin{align*}
&\max_{\boldsymbol{\theta}\in\mathbb{B}(1)}\bigg[\bigg\langle \boldsymbol{\theta},\frac{1}{K}\sum_{t=1}^K\underline{\boldsymbol{V}}^t(\mu^t)\bigg\rangle-\max_{\boldsymbol{x}\in\mathcal{C}}\langle\boldsymbol{\theta},\boldsymbol{x}\rangle\bigg]\\
&\qquad\leq\frac{1}{K}\sum_{t=1}^K\Big(\langle\boldsymbol{\theta}_t,\underline{\boldsymbol{V}}^t(\mu^t)\rangle-\max_{x\in\mathcal{C}}\langle\boldsymbol{\theta}_t,x\rangle\Big)+\mathcal{O}({H\sqrt{d}}/{\sqrt{K}}).
\end{align*}
Further, notice that $p^t$ is updated via Hedge with loss function being $\langle\boldsymbol{\theta}_t,\underline{\boldsymbol{V}}^t(\mu)\rangle$, similarly to the analysis in Section~\ref{sec:proof sketch}, we have with probability at least $1-\delta$,
\begin{align*}
\frac{1}{K}\sum_{t=1}^K\langle\boldsymbol{\theta}_t,\underline{\boldsymbol{V}}^t(\mu^t)\rangle\leq\frac{1}{K}\sum_{t=1}^K\langle\boldsymbol{\theta}_t,\underline{\boldsymbol{V}}^t(\mu^*_{\mathrm{VMDP}})\rangle+\mathcal{O}(H\sqrt{d}\cdot\sqrt{\log(|\Pi|/\delta) / K}),
\end{align*}
where $\mu^*_{\mathrm{VMDP}}=\arg\min_{\mu\in\Pi}\mathrm{dist}(\boldsymbol{V}^{\mu}_1(s_1),\mathcal{C})$. Let $P(\boldsymbol{V}^{\mu^*_{\mathrm{VMDP}}}_1(s_1))$ denote the projection of $\boldsymbol{V}^{\mu^*_{\mathrm{VMDP}}}_1(s_1)$ onto $\mathcal{C}$.
Conditioning on the event of Lemma~\ref{lem:optimism vmdp} holds, we have
\begin{align*}
\sum_{t=1}^K\langle\boldsymbol{\theta}_t,\underline{\boldsymbol{V}}^t(\mu^*_{\mathrm{VMDP}})\rangle\leq\sum_{t=1}^K\langle\boldsymbol{\theta}_t,\boldsymbol{V}^{\mu^*_{\mathrm{VMDP}}}_1(s_1)\rangle.
\end{align*}
Therefore we have
\begin{align*}
&\frac{1}{K}\sum_{t=1}^K\left(\langle\boldsymbol{\theta}_t,\underline{\boldsymbol{V}}^t(\mu^t)\rangle-\max_{x\in\mathcal{C}}\langle\boldsymbol{\theta}_t,x\rangle\right)\\
&\qquad \leq \frac{1}{K}\sum_{t=1}^K\left(\langle\boldsymbol{\theta}_t,\boldsymbol{V}^{\mu^*_{\mathrm{VMDP}}}_1(s_1)\rangle-\max_{x\in\mathcal{C}}\langle\boldsymbol{\theta}_t,x\rangle\right)+\mathcal{O} \bigl (H\sqrt{d}\cdot\sqrt{\log(|\Pi|/\delta) / K} \bigr)\\
&\qquad \leq \frac{1}{K}\sum_{t=1}^K\left(\langle\boldsymbol{\theta}_t,\boldsymbol{V}^{\mu^*_{\mathrm{VMDP}}}_1(s_1)\rangle-\langle\boldsymbol{\theta}_t,P(\bv^{\mu^*_{\mathrm{VMDP}}}_1(s_1))\rangle\right)+\mathcal{O} \bigl (H\sqrt{d}\cdot\sqrt{\log(|\Pi|/\delta) / K}\bigr)\\
&\qquad \leq \left\Vert\boldsymbol{V}^{\mu^*_{\mathrm{VMDP}}}_1(s_1)-P(\bv^{\mu^*_{\mathrm{VMDP}}}_1(s_1))\right\Vert+\mathcal{O} \bigl (H\sqrt{d}\cdot\sqrt{\log(|\Pi|/\delta) / K}\bigr)\\
&\qquad = \min_{\mu\in\Pi}\mathrm{dist}(\boldsymbol{V}^{\mu}_1(s_1),\mathcal{C})+\mathcal{O} \bigl (H\sqrt{d}\cdot\sqrt{\log(|\Pi|/\delta) / K} \bigr),
\end{align*}
where the second step is due to $P(\bv^{\mu^*_{\mathrm{VMDP}}}_1(s_1))\in\mathcal{C}$, the third step is from Cauchy-Schwartz inequality, and the last step is from the definition of $\mu^*_{\mathrm{VMDP}}$.
In conclusion, we have with probability at least $1-\delta$,
\begin{align*}
\mathrm{dist}(\boldsymbol{V}^{\widehat{\mu}}_1(s_1),\mathcal{C})\leq\min_{\mu\in\Pi}\mathrm{dist}(\boldsymbol{V}^{\mu}_1(s_1),\mathcal{C})+\mathcal{O}\big(H^2\sqrt{d}\cdot\sqrt{{d_{\mathrm{BEE,V}}\log\left(\mathcal{N}_{\mathrm{cov,V}}|\Pi|d/\delta\right)}/{K}}\big).
\end{align*}
This concludes our proof.
\section{Conclusion}
We study decentralized policy learning in general-sum Markov games.
Specifically, we aim to establish a no-regret online learning algorithm for a single agent based on its local information, in the presence of nonstationary and possibly adversarial opponents.
Focusing on the policy revealing setting where the opponent's previous policies are revealed to the agent, we propose a novel algorithm that achieves sublinear regret in the context of general function approximation. Moreover, when all the agents adopt this algorithm, we prove that their mixture policy constitutes an approximate CCE of the Markov game. We further demonstrate the efficacy of the proposed algorithm by applying it to constrained and vector-valued MDPs, which can be formulated as zero-sum Markov games with a fictitious opponent.
Finally, while we consider the policy revealing setting,
establishing decentralized RL algorithm for Markov games under weaker information structures seems an important future direction.
\section{Extension: Constrained Markov Decision Process}
\label{sec:cmdp}
Although \texttt{DORIS}\xspace is designed to solve Markov games, there are quite a lot of other problems where \texttt{DORIS}\xspace can tackle with small adaptation. In this section we investigate an important scenario in practice called constrained Markov decision process (CMDP). By converting CMDP into a maximin problem via Lagrangian multiplier, we will be able to view it as a zero-sum Markov game and apply \texttt{DORIS}\xspace readily.
\paragraph{Constrained Markov decision process.} Consider the Constrained Markov Decision Process (CMDP) \citep{ding2021provably} $\mathcal{M}_{\text{CMDP}}=(\mathcal{S},\mathcal{A},\{P_h\}_{h=1}^H,\{r_h\}_{h=1}^H,\{g_h\}_{h=1}^H,H)$ where $\mathcal{S}$ is the state space, $\mathcal{A}$ is the action space, $H$ is the length of each episode, $P_h: \mathcal{S}\times\mathcal{A}\to\Delta(\mathcal{S})$ is the transition function at $h$-th step, $r_h:\mathcal{S}\times\mathcal{A}\to\mathbb{R}_+$ is the reward function and $g_h:\mathcal{S}\times\mathcal{A}\to[0,1]$ is the utility function at $h$-th step. We assume the reward $r_h$ is also bounded in $[0,1]$ for simplicity and thus $V_{\max}=H$. Then given a policy $\mu=\{\mu_h:\mathcal{S}\to\Delta_{\mathcal{A}}\}_{h\in[H]}$, we can define the value function $V_{r,h}^{\mu}$ and action-value function $Q_{r,h}^{\mu}$ with respect to the reward function $r$ as follows:
\begin{align*}
V_{r,h}^{\mu}(s)=\mathbb{E}_{\mu}\bigg[\sum_{t=h}^H r_t(s_t,a_t)\bigg|s_h=s\bigg],Q_{r,h}^{\mu}(s,a)=\mathbb{E}_{\mu}\bigg[\sum_{t=h}^H r_t(s_t,a_t)\bigg|s_h=s,a_h=a\bigg].
\end{align*}
The value function $V_{g,h}^{\mu}$ and action-value function $Q_{g,h}^{\mu}$ with respect to the utility function $g$ can be defined similarly. Another related concept is the state-action visitation distribution, which can be defined as
\begin{align*}
d^{\mu}_{h}(s,a)=\text{Pr}_{\mu}[(s_h,a_h)=(s,a)],
\end{align*}
where $\text{Pr}_{\mu}$ denotes the distribution of the trajectory induced by executing policy $\mu$ in the $\mathcal{M}_{\text{CMDP}}$.
\paragraph{Learning objective.} In CMDP, the player aims to solve a constrained problem where the objective function is the expected total rewards and the constraint is on the expected total utilities:
\begin{problem}[Optimization problem of CMDP]
\label{prob:cmdp}
\begin{align}
\label{eq:prob cmdp}
\max_{\mu\in\Pi} V^{\mu}_{r,1}(s_1) \quad \text{subject to}\quad V^{\mu}_{g,1}(s_1)\geq b,
\end{align}
where $b\in(0,H]$ to avoid triviality.
\end{problem}
Denote the optimal policy for (\ref{eq:prob cmdp}) by $\mu^*_{\text{CMDP}}$, then the regret can be defined as the performance gap with respect to $\mu^*_{\text{CMDP}}$:
\begin{align}
\label{eq:cmdp regret}
\text{Regret}(K)=\sum_{t=1}^K\Big(V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-V_{r,1}^{\mu^t}(s_1)\Big).
\end{align}
However, since utility information is only revealed after a policy is decided, it is impossible for each policy to satisfy the constraints. Therefore, like \cite{ding2021provably}, we allow each policy to violate the constraint in each episode and focus on minimizing total constraint violations over $K$ episodes:
\begin{align}
\label{eq:violation}
\text{Violation}(K)=\bigg[\sum_{t=1}^K\Big(b-V_{g,1}^{\mu^t}(s_1)\Big)\bigg]_{+}.
\end{align}
Achieving sublinear violations in (\ref{eq:violation}) implies that if we sample a policy uniformly from $\{\mu^t\}_{t=1}^K$, its constraint violation can be arbitrarily small given large enough $K$. Therefore, if an algorithm can achieve sublinear regret in (\ref{eq:cmdp regret}) and sublinear violations in (\ref{eq:violation}) at the same time, this algorithm will be able to find a good approximate policy to $\mu^*_{\text{CMDP}}$.
\subsection{Algorithm: \texttt{DORIS-C}\xspace}
To solve Problem~\ref{prob:cmdp} with \texttt{DORIS}\xspace, we first need to convert it into a Markov game. A natural idea is to apply the Lagrangian multiplier $Y\in\mathbb{R}_{+}$ to Problem~\ref{prob:cmdp}, which brings about the equivalent maximin problem below:
\begin{align}
\label{prob:maximin}
\max_{\mu\in\Pi}\min_{Y\geq0} \mathcal{L}_{\mathrm{CMDP}}(\mu,Y):=V^{\mu}_{r,1}(s_1)+Y(V_{g,1}^{\mu}(s_1)-b).
\end{align}
Although Problem~\ref{prob:cmdp} is non-concave in $\mu$, there have been works indicating that strong duality still holds for Problem~\ref{prob:cmdp} when the policy class is described by a good parametrization \citep{paternain2019constrained}. Therefore, here we assume strong duality holds and it is straightforward to generalize our analysis to the case where there exists a duality gap:
\begin{assumption}[Strong duality]
\label{ass:strong duality}
Assume strong duality holds for Problem~\ref{prob:cmdp}, i.e.,
\begin{align}
\label{eq:strong duality}
\max_{\mu\in\Pi}\min_{Y\geq0} \mathcal{L}_{\mathrm{CMDP}}(\mu,Y)=\min_{Y\geq0}\max_{\mu\in\Pi} \mathcal{L}_{\mathrm{CMDP}}(\mu,Y).
\end{align}
\end{assumption}
\begin{remark}
One example case where strong duality (\ref{eq:strong duality}) holds is when policy class $\Pi$ satisfies global realizability. Let $\mu^*_{\text{glo}}$ denote the solution to $\max_{\mu_h(\cdot|s)\in\Delta_{\mathcal{A}}}\min_{Y\geq0} \mathcal{L}_{\mathrm{CMDP}}(\mu,Y)$. \cite{ding2021provably} showed that $\max_{\mu\in(\Delta_{\mathcal{A}})^{|\mathcal{S}|H}}\min_{Y\geq0} \mathcal{L}_{\mathrm{CMDP}}(\mu,Y)$ satisfies strong duality, and thus as long as $\mu^*_{\text{glo}}\in\Pi$, Problem~\ref{prob:cmdp} also has strong duality.
\end{remark}
Further, let $D(Y):=\max_{\mu\in\Pi}\mathcal{L}_{\mathrm{CMDP}}(\mu,Y)$ denote the dual function and suppose the optimal dual variable is $Y^*=\arg\min_{Y\geq0}D(Y)$. To ensure $Y^*$ is bounded, we need to assume that the standard Slater's Condition holds:
\begin{assumption}
\label{ass:slater}
There exists $\lambda_{\mathrm{sla}}>0$ and $\widetilde{\mu}\in\Pi$ such that $V_{g,1}^{\widetilde{\mu}}(s_1)\geq b+\lambda_{\mathrm{sla}}$.
\end{assumption}
Then the following lemma shows that Assumption~\ref{ass:slater} implies bounded optimal dual variable, whose proof is deferred to Appendix~\ref{proof lemma duality}:
\begin{lemma}
\label{lem:duality}
Suppose Assumption~\ref{ass:strong duality},\ref{ass:slater} hold, then we have $0\leq Y^*\leq {H}/{\lambda_{\mathrm{sla}}}$.
\end{lemma}
Now we are ready to adapt \texttt{DORIS}\xspace into a primal-dual algorithm to solve Problem~\ref{prob:cmdp}. Notice that the maximin problem (\ref{prob:maximin}) can be viewed as a zero-sum Markov game where the player's policy is $\mu$ and the reward function for the player is $r_{h}(s,a)+Yg_h(s,a)$. The opponent's action is $Y\in\mathbb{R}_+$ which remains the same throughout a single episode. With this formulation, we can simply run \texttt{DORIS}\xspace on the player, assuming the player is given function classes $\{\mathcal{F}^r,\mathcal{G}^r\}$ and $\{\mathcal{F}^g,\mathcal{G}^g\}$ to approximate $Q_{r,h}^{\mu}$ and $Q_{g,h}^{\mu}$ respectively. In the meanwhile, we run online projected gradient descent on the opponent so that its action $Y$ can capture the total violation so far.
This new algorithm is called \texttt{DORIS-C}\xspace and shown in Algorithm~\ref{alg:CMDP}. It consists of the following three steps in each iteration. For the policy evaluation task in the second step, \texttt{DORIS-C}\xspace runs a single-agent version of \texttt{OptLSPE}\xspace to estimate $V^{\mu}_{r,1}(s_1)$ and $V^{\mu}_{g,1}(s_1)$ separately, which is essential for \texttt{DORIS-C}\xspace to deal with the infinity of the opponent's policy class, i.e., $\mathbb{R}_+$.
\begin{itemize}
\item The player plays a policy $\mu^t$ sampled from its hyperpolicy $p^t$ and collects a trajectory.
\item The player runs \texttt{OptLSPE-C}\xspace to obtain optimistic value function estimations $\overline{V}^t_r(\mu),\break\overline{V}^t_g(\mu)$ for all $\mu\in\Pi$ and updates the hyperpolicy using Hedge with the loss function being $\overline{V}^t_r(\mu)+Y_t\overline{V}^t_g(\mu)$. The construction rule for $\mathcal{B}_{\mathcal{D}}(\mu)$ is still based on relaxed least-squared policy evaluation:
\begin{align}
\label{eq:cmdp eva}
\mathcal{B}_{\mathcal{D}}(\mu)\gets\{f\in\mathcal{F}:\mathcal{L}_{\mathcal{D}}(f_h,f_{h+1},\mu)\leq\inf_{g\in\mathcal{G}}\mathcal{L}_{\mathcal{D}}(g_h,f_{h+1},\mu)+\beta,\forall h\in[H]\},
\end{align}
where $\mathcal{L}_{\mathcal{D}}$ is the empirical Bellman residuals on $\mathcal{D}$:
\begin{align*} \mathcal{L}_{\mathcal{D}}(\xi_h,\zeta_{h+1},\mu)=\sum_{(s_h,a_h,x_h,s_{h+1})\in\mathcal{D}}[\xi_h(s_h,a_h)-x_h-\zeta_{h+1}(s_{h+1},\mu)]^2.
\end{align*}
\item The dual variable is updated using online projected gradient descent.
\end{itemize}
\begin{algorithm}[h]
\caption{\textbf{\texttt{DORIS-C}\xspace}}
\label{alg:CMDP}
\begin{algorithmic}
\State \textbf{Input}: learning rate $\eta,\alpha$, confidence parameter $\beta_r,\beta_g$, projection length $\rchi$.
\State Initialize $p^1\in\mathbb{R}^{|\Pi|}$ to be uniform over $\Pi$, $Y_1\gets 0$.
\For{$t=1,\cdots,K$}
\State \textbf{Collect samples:}
\State The player samples $\mu^t$ from $p^t$.
\State Run $\mu^t$ and collect $\mathcal{D}^r_{t}=\{s^t_1,a^t_1,r^t_1,\cdots,s^t_{H+1}\}$,$\mathcal{D}^g_{t}=\{s^t_1,a^t_1,g^t_1,\cdots,s^t_{H+1}\}$.
\State \textbf{Update policy distribution:}
\State $\overline{V}^t_r(\mu)\gets\textbf{\texttt{OptLSPE-C}\xspace}(\mu,\mathcal{D}^r_{1:t-1},\mathcal{F}^r,\mathcal{G}^r,\beta_r),\quad\forall\mu\in\Pi$.
\State
$\overline{V}^t_g(\mu)\gets\textbf{\texttt{OptLSPE-C}\xspace}(\mu,\mathcal{D}^g_{1:t-1},\mathcal{F}^g,\mathcal{G}^g,\beta_g),\quad\forall\mu\in\Pi$.
\State $p^{t+1}(\mu)\propto p^{t}(\mu)\cdot\exp(\eta\cdot(\overline{V}^t_r(\mu)+Y_t\overline{V}^t_g(\mu))),\quad\forall\mu\in\Pi$.
\State \textbf{Update dual variable:}
\State
$Y_{t+1}\gets\text{Proj}_{[0,\rchi]}(Y_t+\alpha(b-\overline{V}^t_g(\mu^t)))$.
\EndFor
\end{algorithmic}
\end{algorithm}
\begin{algorithm}[h]
\caption{$\textbf{\texttt{OptLSPE-C}\xspace}(\mu,\mathcal{D},\mathcal{F},\mathcal{G},\beta)$}
\label{alg:SGOLF}
\begin{algorithmic}
\State \textbf{Construct} $\mathcal{B}_{\mathcal{D}}(\mu)$ based on $\mathcal{D}$ via (\ref{eq:cmdp eva}).
\State \textbf{Select} $\bar{V}\gets\max_{f\in\mathcal{B}_{\mathcal{D}}(\mu)} f(s_1,\mu)$.
\State \Return $\bar{V}$.
\end{algorithmic}
\end{algorithm}
\subsection{Theoretical Guarantees}
Next we provide the regret and constraint violation bounds for \texttt{DORIS-C}\xspace. Here we also consider the case where $\Pi$ is finite, i.e., Assumption~\ref{ass:player} is true. However, we can see that here the opponent is adaptive and its policy class is infinite, suggesting that Assumption~\ref{ass:opponent} is violated. Fortunately, since the opponent only affects the reward function, the player can simply first estimate $V^{\mu}_{r,1}(s_1)$ and $V^{\mu}_{g,1}(s_1)$ respectively and then use their weighted sum to approximate the target value function $V^{\mu}_{r,1}(s_1)+Y\cdot V^{\mu}_{g,1}(s_1)$. In this way, \texttt{DORIS-C}\xspace circumvents introducing a union bound on $Y$ and thus can work even when the number of possible values for $Y$ is infinite.
We also need to introduce the realizability and general completeness assumptions on the function classes as before:
\begin{assumption}[Realizability and generalized completeness in CMDP]
\label{ass:realize single}
Assume that for any $h\in[H],\mu\in\Pi,f^{r}_{h+1}\in\mathcal{F}^r_{h+1},f^{g}_{h+1}\in\mathcal{F}^g$, we have
\begin{align}
\label{eq:realize cmdp}
Q_{r,h}^{\mu}\in\mathcal{F}^r_h,Q_{g,h}^{\mu}\in\mathcal{F}^g_h, \mathcal{T}_h^{\mu,r}f^r_{h+1}\in\mathcal{G}^r_{h}, \mathcal{T}_h^{\mu,g}f^g_{h+1}\in\mathcal{G}^g_{h}.
\end{align}
\end{assumption}
Here $\mathcal{T}_h^{\mu,r}$ is the Bellman operator at step $h$ with respect to $r$:
\begin{align*}
(\mathcal{T}_h^{\mu,r}f_{h+1})(s,a)=r_h(s,a)+\mathbb{E}_{s'\sim P(\cdot|s,a)}f_{h+1}(s',\mu),
\end{align*}
where $f_{h+1}(s',\mu)=\mathbb{E}_{a'\sim\mu(\cdot|s)}[f_{h+1}(s',a')]$. $\mathcal{T}_h^{\mu,g}$ is defined similarly. We can see that (\ref{eq:realize cmdp}) simply says that all the action value functions with respect to $r$ ($g$) belong to $\mathcal{F}^r$ ($\mathcal{F}^g$) and $\mathcal{G}^r$ ($\mathcal{G}^g$) contains all the results of applying Bellman operator with respect to $r$ ($g$) to the functions in $\mathcal{F}^r$ ($\mathcal{F}^g$).
In addition, as a simplified case of Definition~\ref{def:BEE}, BEE dimension for single-agent setting can be defined as follows:
\begin{definition}
The single-agent $\epsilon$-Bellman Evaluation Eluder dimension of function class $\mathcal{F}$ on distribution family $\mathcal{Q}$ with respect to the policy class $\Pi$ and the reward function $r$ is defined as follows:
\begin{equation*}
\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,r,\mathcal{Q}):=\max_{h\in[H]}\mathrm{dim}_{\mathrm{DE}}((\mathcal{I}-\mathcal{T}^{\Pi,r}_h)\mathcal{F},\mathcal{Q}_{h},\epsilon),
\end{equation*}
where $(\mathcal{I}-\mathcal{T}^{\Pi,r}_h)\mathcal{F}:=\{f_h-\mathcal{T}^{\mu,r}_hf_{h+1}:f\in\mathcal{F},\mu\in\Pi\}$.
\end{definition}
We also let $\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,r)$ denote $\min\{\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,r,\mathcal{Q}^1),\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\break\Pi,r,\mathcal{Q}^2)\}$ as before. $\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,g,\mathcal{Q})$ and $\mathrm{dim}_{\mathrm{BEE}}(\mathcal{F},\epsilon,\Pi,g)$ are defined similarly but with respect to the utility function $g$.
Now we can present the following theorem which shows that \texttt{DORIS-C}\xspace is capable of achieving sublinear regret and constraint violation for Problem~\ref{prob:cmdp}. We also use the following notations to simplify writing:
\begin{align*}
&d_{\mathrm{BEE},r}:=\mathrm{dim}_{\mathrm{BEE}}\big(\mathcal{F}^r,\sqrt{{1}/{K}},\Pi,r\big),\quad\mathcal{N}_{\mathrm{cov},r}:=\mathcal{N}_{\mathcal{F}^r\cup\mathcal{G}^r}(H/K)KH,\\
&d_{\mathrm{BEE},g}:=\mathrm{dim}_{\mathrm{BEE}}\big(\mathcal{F}^g,\sqrt{{1}/{K}},\Pi,g\big),\quad\mathcal{N}_{\mathrm{cov},r}:=\mathcal{N}_{\mathcal{F}^g\cup\mathcal{G}^g}(H/K)KH.
\end{align*}
\begin{theorem}
\label{thm:cmdp}
Under Assumption~\ref{ass:strong duality},\ref{ass:slater},\ref{ass:player},\ref{ass:realize single}, there exists an absolute constant $c$ such that for any $\delta\in(0,1]$, $K\in\mathbb{N}$, if we choose $\beta_r=cH^2\log(\mathcal{N}_{\mathrm{cov},r}|\Pi|/\delta)$, $\beta_g=cH^2\log(\mathcal{N}_{\mathrm{cov},g}|\Pi|/\delta)$, $\alpha=1/{\sqrt{K}}$, $\rchi={2H}/{\lambda_{\mathrm{sla}}}$ and $\eta=\sqrt{{\log|\Pi|}/({K(\rchi+1)^2H^2})}$ in \texttt{DORIS-C}\xspace, then with probability at least $1-\delta$, we have:
\begin{align}
\label{eq:thm3 regret}
&\text{Regret}(K)\leq\mathcal{O}\bigg(\bigg(H^2+\frac{H^2}{\lambda_{\mathrm{sla}}}\bigg)\sqrt{Kd_{\mathrm{BEE},r}\log\left(\mathcal{N}_{\mathrm{cov},r}|\Pi|/\delta\right)}\bigg),
\end{align}
\begin{align}
\label{eq:thm3 violation}
\text{Violation}(K)\leq\mathcal{O}\bigg(\bigg(H^2+\frac{H}{\lambda_{\mathrm{sla}}}\bigg)\sqrt{K\eps_{\text{BEE}}}\bigg),
\end{align}
where we define $\eps_{\text{BEE}}$ as
\begin{align*} \eps_{\text{BEE}}=\max\Big\{d_{\mathrm{BEE},r}\log\left(\mathcal{N}_{\mathrm{cov},r}|\Pi|/\delta\right),d_{\mathrm{BEE},g}\log\left(\mathcal{N}_{\mathrm{cov},g}|\Pi|/\delta\right)\Big\}.
\end{align*}
\end{theorem}
The bounds in (\ref{eq:thm3 regret}) and (\ref{eq:thm3 violation}) show that both the regret and constraint violation of \texttt{DORIS-C}\xspace scale with $\sqrt{K}$. This implies that for any $\epsilon>0$, if $\widehat{\mu}$ is sampled uniformly from $\{\mu^t\}_{t=1}^K$ and $K\geq\widetilde{\mathcal{O}}(1/\epsilon^2)$, $\widehat{\mu}$ will be an $\epsilon$ near-optimal policy with high probability in the sense that
\begin{align*}
V_{r,1}^{\widehat{\mu}}(s_1)\geq V_{r,1}^{\mu^*_{\text{CMDP}}}(s_1)-\epsilon,\qquad V_{g,1}^{\widehat{\mu}}(s_1)\geq b-\epsilon.
\end{align*}
In addition, compared to the results in Theorem~\ref{thm:oblivious} and Theorem~\ref{thm:adaptive}, (\ref{eq:thm3 regret}) and (\ref{eq:thm3 violation}) have an extra term scaling with $1/\lambda_{\mathrm{sla}}$. This is because \texttt{DORIS-C}\xspace is a primal-dual algorithm and $\lambda_{\mathrm{sla}}$ characterizes the regularity of this constrained optimization problem.
The proof of the regret bound is similar to Theorem~\ref{thm:oblivious} and Theorem~\ref{thm:adaptive} by viewing $V^{\mu}_{r,1}(s_1)+YV^{\mu}_{g,1}(s_1)$ as the target value function and decomposing the regret into cumulative estimation error and online learning error. To bound the constraint violation, we need to utilize the strong duality and the property of online projected gradient descent. See Appendix~\ref{proof:thm cmdp} for more details.
\paragraph{Comparison with existing algorithms.} There has been a line of works studying the exploration and exploitation in CMDPs. \cite{efroni2020exploration,ding2021provably} propose a series of algorithms which can achieve $\sqrt{K}$ bound on regrets and constraint violations. However, they focus on tabular cases or linear function approximation and do not consider policy classes while \texttt{DORIS-C}\xspace can deal with nonlinear function approximation and policy classes. As an interesting follow-up, \cite{liu2021learning} reduces the constraint violation to $\widetilde{\mathcal{O}}(1)$ by adding slackness to the algorithm and achieves zero violation when a strictly safe policy is known; \cite{wei2021provably} further avoids such requirement with the price of worsened regrets. However, these improvements are all limited in tabular cases and we leave the consideration of their general function approximation counterpart to future works.
\section{Introduction} \label{sec:intro}
Multi-agent reinforcement learning (MARL) studies how each agent learns to maximize its cumulative rewards
by interacting with the environment as well as other agents, where the state transitions and rewards are affected by the actions of all the agents.
Equipped with powerful function approximators such as deep neural networks \citep{lecun2015deep}, MARL has achieved significant empirical success in various domains including the game of Go \citep{silver2016mastering}, StarCraft \citep{vinyals2019grandmaster}, DOTA2 \citep{berner2019dota}, Atari \citep{mnih2013playing}, multi-agent robotics systems \citep{brambilla2013swarm} and autonomous driving\citep{shalev2016safe}.
Compared with the centralized setting where a central controller collects the information of all agents and coordinates their behaviors, decentralized algorithms \citep{gupta2017cooperative,rashid2018qmix} where each agent autonomously chooses its action based on its own local information are often more desirable in MARL applications.
In specific,
decentralized methods
(1) are easier to implement and enjoy better scalability, (2) are more robust to possible adversaries, and (3) require less communication overhead \citep{hernandez2018multiagent,hernandez2019survey,canese2021multi,zhang2021multi,gronauer2022multi}.
In this work, we aim to design a provably efficient decentralized reinforcement learning (RL) algorithm in the online setting with function approximation.
In the sequel, for the ease of presentation,
we refer to the controllable agent as
the \textit{player}
and regard the rest of the agents as a meta-agent, called the \textit{opponent}, which specifies its policies arbitrarily. Our goal is to maximize the cumulative rewards of the player in the face of a possibly adversarial opponent, in the online setting where the policies of the player and opponent can be based on adaptively gathered local information.
From a theoretical perspective, arguably the most distinctive challenge of
the
decentralized setting
is \textit{nonstationarity}.
That is, from the perspective of any agent, the states transitions are affected by the policies of other agents in an unpredictable and potentially adversarial way and are thus nonstationary.
This is in stark contrast to the centralized setting which can be regarded as a standard RL problem for the central controller which decides the actions for all the players.
Furthermore,
in the online setting, as the environment is unknown, to achieve sample efficiency, the player needs to strike a balance between \textit{exploration} and \textit{exploitation} in the
context of function approximation and in the presence of an adversarial opponent.
The dual challenges of nonstationarity and efficient exploration are thus intertwined, making it challenging to develop provably efficient decentralized MARL algorithms.
Consequently, there seem only limited theoretical understanding of the decentralized MARL setting with a possibly adversarial opponent. Most of the existing algorithms \citep{brafman2002r,wei2017online,tian2021online,jin2021power,huang2021towards} can only compete against the Nash value of the Markov game when faced with an arbitrary opponent.
This is a much weaker baseline compared with the results in classic matrix games \citep{fudenberg1991game,anderson2008theory} where the player is required to compete against \textit{the best fixed policy in hindsight}. Meanwhile, \cite{liu2022learning} seems the only work we know that can achieve no-regret learning in MARL against the best hindsight policy, which focuses on the \textit{policy revealing} setting
where the player observes the policies played by the opponent in previous episodes.
Moreover, the algorithm and theory in this work are limited to tabular cases and fail to deal with large or even continuous state and action space.
To this end, we would like to answer the following question:
\begin{center}
\textbf{\textit{Can we design a decentralized MARL algorithm that provably achieves no-regret against the best fixed policy in hindsight in the context of function approximation?}}
\end{center}
In this work, we provide a positive answer to the above question under the \textit{policy revealing} setting with general function approximation.
In specific, we propose an actor-critic-type algorithm \citep{konda1999actor} called \texttt{DORIS}\xspace, which maintains a distribution over the policy space, named \textit{hyperpolicy}, for decision-making.
To combat the nonstationarity, \texttt{DORIS}\xspace updates the hyperpolicy via mirror descent (or equivalently, Hedge \citep{freund1997decision}).
Furthermore, to encourage exploration, the descent directions of mirror descent are obtained by solving optimistic variants of policy evaluation subproblems with general function approximation, which only involve the local information of the player.
Under standard regularity assumptions on the underlying function classes, we prove that \texttt{DORIS}\xspace achieves a sublinear regret in the presence of an adversarial opponent.
In addition, when the agents all adopt \texttt{DORIS}\xspace independently, we prove that their average policy constitutes an approximate coarse correlated equilibrium.
At the core of our analysis is a new complexity measure of function classes that is tailored to the decentralized MARL setting.
Furthermore, to demonstrate the power of \texttt{DORIS}\xspace, we adapt it for solving constrained Markov decision process (CMDP) and vector-valued Markov decision process (VMDP), which can both be formulated as a zero-sum Markov game with a fictitious opponent.
\paragraph{Our Contributions.} Our contributions are four-fold. First, we propose a new decentralized policy optimization algorithm, \texttt{DORIS}\xspace, that provably achieves no-regret in the context of general function approximation.
As a result, when all agents adopt \texttt{DORIS}\xspace, their average policy converges to a CCE of the Markov game.
Secondly, we propose a new complexity measure named Bellman Evaluation Eluder dimension, which generalizes Bellman Eluder dimension \citep{jin2021bellman} for single-agent MDP to decentralized learning in Markov games, which might be of independent interest.
Third, we modify \texttt{DORIS}\xspace for solving CMDP with general function approximation, which is shown to achieve sublinear regret and constraint violation.
Finally, we extend \texttt{DORIS}\xspace to solving the approchability task \citep{miryoosefi2019reinforcement} in vector-valued Markov decision process (VMDP) and attain a near-optimal solution. To our best knowledge, \texttt{DORIS}\xspace seems the first provably efficient decentralized algorithm for achieving no-regret in MARL with general function approximation.
\
\subsection{Notations}
In this paper we let $[n]=\{1,\cdots,n\}$ for any integer $n$. We denote the set of probability distributions over any set $\mathcal{S}$ by $\Delta_{\mathcal{S}}$ or $\Delta(\mathcal{S})$. We also let $\Vert\cdot\Vert$ denote the $\ell_2$-norm by default.
\section{Preliminaries}
\label{sec:setting}
\subsection{General-Sum Markov Games}
Let us consider an $n$-agent general-sum Markov game (MG) $\mathcal{M}_{\text{MG}}=(\mathcal{S},\{\mathcal{A}_i\}_{i=1}^{n},\{P_h\}_{h=1}^H,\break\{r_{h,i}\}_{h=1,i=1}^{H,n},H)$, where $\mathcal{S}$ is the state space, $\mathcal{A}_i$ is the action space of $i$-th agent, $P_h: \mathcal{S}\times\prod_{i=1}^n\mathcal{A}_i\to\Delta(\mathcal{S})$ is the transition function at $h$-th step, $r_{h,i}:\mathcal{S}\times\prod_{i=1}^n\mathcal{A}_i\to\mathbb{R}_+$ is the reward function of $i$-th agent at $h$-th step and $H$ is the length of each episode.
We assume each episode starts at a fixed start state $s_1$ and terminates at $s_{H+1}$. At step $h\in[H]$, each agent $i$ observes the state $s_h$ and takes action $a_{h,i}$ simultaneously. After that, agent $i$ receives its own reward $r_{h,i}(s_h,\boldsymbol{a}_h)$ where $\boldsymbol{a}_h:=(a_{h,1},\cdots,a_{h,n})$ is the joint action and the environment transits to a new state $s_{h+1}\sim P_h (\cdot|s_h,\boldsymbol{a}_h)$.
\paragraph{Policy.}
A policy of the $i$-th agent $\mu_i=\{\mu_{h,i}:\mathcal{S}\to\Delta_{\mathcal{A}_i}\}_{h\in[H]}$ specifies the action selection probability of agent $i$ in each state at each step. In the following discussion we will drop the $h$ in $\mu_{h,i}$ when it is clear from the context. We use $\pi$ to represent the joint policy of all agents and $\mu_{-i}$ to denote the joint policy of all agents other than $i$. Further, we assume each agent $i$ chooses its policy from a policy class $\Pi_i$. Similarly, let $\Pi_{-i}:=\prod_{j\neq i}\Pi_{j}$ denote the product of all agents' policy classes other than the $i$-th agent.
\paragraph{Value functions and Bellman operators.}
Given any joint policy $\pi$, the $i$-th agent's value function $V^{\pi}_{h,i}:\mathcal{S}\to\mathbb{R}$ and action-value (or Q) function $Q^{\pi}_{h,i}:\mathcal{S}\times\prod_{i=1}^n\mathcal{A}_i\to\mathbb{R}$ characterize its expected cumulative rewards given a state or a state-action pair, as defined below:
\begin{align*}
&V^{\pi}_{h,i}(s):=\mathbb{E}_{\pi}\bigg[\sum_{t=h}^H r_{t,i}(s_t,\boldsymbol{a}_{t})\bigg|s_h=s\bigg], Q^{\pi}_{h,i}(s,\boldsymbol{a}):=\mathbb{E}_{\pi} \bigg [\sum_{t=h}^H r_{t,i} (s_t,\boldsymbol{a}_{t}) \bigg| s_h=s,\boldsymbol{a}_h=\boldsymbol{a} \bigg ],
\end{align*}
where the expectation is w.r.t. to the distribution of the trajectory induced by executing the joint policy $\pi$ in $\mathcal{M}_{\text{MG}}$.
Here we suppose the action-value function is bounded:
\begin{align*}
Q^{\pi}_{h,i}(s,\boldsymbol{a})\leqV_{\max},\forall s,\boldsymbol{a},h,i,\pi.
\end{align*}
Notice that when the reward function is bounded in $[0,1]$, $V_{\max}=H$ naturally.
\subsection{Decentralized Policy Learning}
In this paper we consider the decentralized learning setting \citep{jin2021power,huang2021towards,liu2022learning} where only one agent is under our control, which we call \textit{player}, and the other agents can be adversarial. Without loss of generality, assume that we can only control agent 1 and view the other agents as a meta \textit{opponent}. To simplify writing, we use $a_h,\mathcal{A},r_h,\mu,\Pi, V^{\pi}_h, Q^{\pi}_h$ to denote $a_{h,1},\mathcal{A}_1,r_{h,1},\mu_1,\Pi_1,V^{\pi}_{h,1},Q^{\pi}_{h,1}$ respectively. We also use $b_h,\mathcal{B},\nu,\Pi'$ to represent the joint action, the joint action space, the joint policy and the joint policy class of all the agents other than agent 1.
By \textit{decentralized learning} we mean that during the episode, the player can only observe its own rewards, actions and some information of the opponent specified by the protocol, i.e., $\{s_h^t,a_h^t
\mathcal{J}_h^{t}, r_{h}^t \}_{h=1}^H$ where $\{\mathcal{J}_h\}_{h=1}^H$ is the information revealed by the opponent in each episode, which we will specify later. Then at the beginning of $t$-th episode, the player chooses a policy $\mu^t$ from its policy class $\Pi$ based only on its local information collected from previous episodes, without any coordination from a centralized controller. Meanwhile, the opponent selects $\nu^t$ from $\Pi'$ secretly and probably adversely.
The learning objective is to minimize the regret of the player by comparing its performance against the best fixed policy in hindsight as standard in online learning literature \citep{anderson2008theory,hazan2016introduction}:
\begin{definition}[Regret]
\label{def:regret}
Suppose $(\mu^t,\nu^t)$ are the policies played by the player and the opponent in $t$-th episode. Then the regret for $K$ episodes is defined as
\begin{align}
\label{eq:reg def}
\text{Regret}(K)=\max_{\mu\in\Pi}\sum_{t=1}^KV^{\mu\times\nu^t}_1(s_1)-\sum_{t=1}^KV^{\mu^t\times\nu^t}_1(s_1),
\end{align}
where $\mu\times\nu$ denotes the joint policy where the player and the opponent play $\mu$ and $\nu$ independently.
\end{definition}
Achieving low regrets defined in (\ref{eq:reg def}) indicates that, in the presence of an opponent playing adaptive $\{ \nu^t \}_{t=1}^T$, the algorithm approximately is as good as the best fixed policy in $\Pi$ in the hindsight.
\paragraph{Relation between Definition~\ref{def:regret} and equilibria.} An inspiration for our definition of regrets comes from the tight connection between low regrets and equilibria in the matrix game \citep{fudenberg1991game,blum2007learning,daskalakis2011near}. By viewing each policy in the policy class as a pure strategy in the matrix game, we can generalize the notion of equilibria in matrix games to Markov games naturally. In particular, a correlated mixed strategy profile $\overline{\pi}$ can be defined as a mixture of the joint policy of all agents, i.e., $\overline{\pi}\in\Delta(\prod_{i\in[n]}\Pi_i)$.
Suppose the marginal distribution of $\overline{\pi}$ over the policy of agent $i$ is $\overline{\mu}_i$, then we can see that $\overline{\mu}_i$ is a mixture of the policies in $\Pi_i$. For a correlated profile, the agents might not play their mixed policies $\overline{\mu}_i$ independently, which means that $\overline{\pi}$ might not be the product of $\overline{\mu}_i$. A coarse correlated equilibrium (CCE) is simply a correlated profile that all the agents have no incentive to deviate from by playing a different independent policy:
\begin{definition}[Coarse correlated equilibrium (CCE) for $n$-player MG]
A correlated strategy profile $\overline{\pi}$ is an $\epsilon$-approximate coarse correlated equilibrium if we have for all $i\in[n]$
\begin{align}
\label{eq:def cce}
V_{1,i}^{\overline{\pi}}(s_1)\geq\max_{\mu'\in\Pi_i}V_{1,i}^{\mu'\times\overline{\mu}_{-i}}(s_1)-\epsilon,
\end{align}
where $\overline{\mu}_{-i}$ is the marginal distribution of $\overline{\pi}$ over the joint policy of all agents other than $i$.
\end{definition}
\begin{remark}
Our definition of correlated strategy profile and CCEs is slightly different from \cite{mao2021on}. This is because we are considering with policy classes while \cite{mao2021on} does not. In fact, our definition is more strict in the sense that a correlated profile satisfying our definition must also satisfy theirs.
\end{remark}
Specially, if a CCE $\overline{\pi}$ satisfies $\overline{\pi}=\prod_{i\in[n]}\overline{\mu}_i$, then we call $\overline{\pi}$ a Nash Equilibrium (NE). We will show in Section~\ref{sec:selfplay} that if a decentralized algorithm can achieve low regrets under Definition~\ref{def:regret}, we will be able to find an approximate CCE by running the algorithm independently for each agent and return the resulting mixture policy.
\subsection{Function Approximation}
To deal with the potentially large or even infinite state and action space, we consider learning with general value function approximation in this paper \citep{jiang2017contextual,jin2021bellman}. We assume the player is given a function class $\mathcal{F}=\mathcal{F}_1\times\cdots\times\mathcal{F}_H$ ($\mathcal{F}_h\subseteq(\mathcal{S}\times\mathcal{A}\times\mathcal{B}\to[0,V_{\max}])$) to approximate the action-value functions. Since there is no reward in state $s_{H+1}$, we let $f_{H+1}(s,a,b)=0$ for all $s\in\mathcal{S},a\in\mathcal{A},b\in\mathcal{B},f\in\mathcal{F}$.
To measure the size of $\mathcal{F}$, we use $|\mathcal{F}|$ to denote its cardinality when $\mathcal{F}$ is finite. For infinite function classes, we use $\epsilon$-covering number to measure its size, which is defined as follows.
\begin{definition}[$\epsilon$-covering number]
The $\epsilon$-covering number of $\mathcal{F}$, denoted by $\mathcal{N}_{\mathcal{F}}(\epsilon)$, is the minimum integer $n$ such that there exists a subset $\mathcal{F}'\subset\mathcal{F}$ with $|\mathcal{F}'|=n$ and for any $f\in\mathcal{F}$ there exists $f'\in\mathcal{F}'$ such that $\max_{h\in[H]}\Vert f_h-f'_h\Vert_{\infty}\leq\epsilon$.
\end{definition}
In addition to the size, we also need to impose some complexity assumption on the structure of the function class to achieve small generalization error. Here we introduce one of such structure complexity measures called Distributional Eluder (DE) dimension \citep{jin2021bellman}, which we will utilize in our subsequent analysis. First let us define independence between distributions as follows.
\begin{definition}[$\epsilon$-independence between distributions]
Let $\mathcal{W}$ be a function class defined on $\mathcal{X}$, and $\rho,\rho_1,\cdots,\rho_n$ be probability measure over $\mathcal{X}$. We say $\rho$ is $\epsilon$-independent of $\{\rho_1,\cdots,\rho_n\}$ with respect to $\mathcal{W}$ if there exists $w\in\mathcal{W}$ such that $\sqrt{\sum_{i=1}^n(\mathbb{E}_{\rho_i}[w])^2}\leq\epsilon$ but $|\mathbb{E}_{\rho}[w]|>\epsilon$.
\end{definition}
From the definition we can see that a probability distribution $\rho$ is independent from $\{\rho_1,\cdots,\rho_n\}$ if there exists a discriminator function in $\mathcal{W}$ such that the function values are small at $\{\rho_1,\cdots,\rho_n\}$ while large at $\rho$. Then DE dimension is simply the length of the longest sequence of independent probability distributions that the function class can discriminate.
We lay out the definition of the DE dimension as follows.
\begin{definition}[Distributional Eluder (DE) dimension]
Let $\mathcal{W}$ be a function class defined on $\mathcal{X}$, and $\mathcal{Q}$ be a family of probability measures over $\mathcal{X}$. The distributional Eluder dimension $\mathrm{dim}_{\mathrm{DE}}(\mathcal{W},\mathcal{Q},\epsilon)$ is the length of the longest sequence $\{\rho_1,\cdots,\rho_n\}\subset\mathcal{Q}$ such that there exists $\epsilon'\geq\epsilon$ where $\rho_i$ is $\epsilon'$-independent of $\{\rho_1,\cdots,\rho_{i-1}\}$ for all $i\in[n]$.
\end{definition}
Eluder dimension, another commonly-used complexity measure proposed by \cite{russo2013eluder}, is a special case of DE dimension when the distributions concentrate on a single point. That is, if we choose $\mathcal{Q}=\{\delta_x(\cdot)|x\in\mathcal{X}\}$ where $\delta_x(\cdot)$ is the dirac measure centered at $x$, then the Eluder dimension can be formulated as
\begin{align*}
\mathrm{dim}_{\mathrm{E}}(\mathcal{W},\epsilon)=\mathrm{dim}_{\mathrm{DE}}(\mathcal{W}-\mathcal{W},\mathcal{Q},\epsilon),
\end{align*}
where $\mathcal{W}-\mathcal{W}=\{w_1-w_2: w_1,w_2\in\mathcal{W}\}$. Many function classes in MDPs are known to have low Eluder dimension, including linear MDPs \citep{jin2020provably}, generalized linear complete models \citep{wang2019optimism} and kernel MDPs \citep{jin2021bellman}.
We also assume the existence of an auxiliary function class $\mathcal{G}=\mathcal{G}_1\times\cdots\times\mathcal{G}_H$ ($\mathcal{G}_h\subseteq(\mathcal{S}\times\mathcal{A}\times\mathcal{B}\to[0,V_{\max}])$) to capture the results of applying Bellman operators on $\mathcal{F}$ as in \cite{jin2021bellman,jin2021power}. When $\mathcal{F}$ satisfies completeness (Assumption~\ref{ass:complete self}), we can simply choose $\mathcal{G}=\mathcal{F}$.
\subsection{Related works}
\paragraph{Decentralized learning with an adversarial opponent.} There have been a few works studying decentralized policy learning in the presence of a possibly adversarial opponent. \cite{brafman2002r} proposes R-max and is able to attain an average game value close to the Nash value in tabular MGs.
More recently, \cite{wei2017online,tian2021online} improve the regret bounds in tabular cases and \cite{jin2021power,huang2021towards} extend the results to general function approximation setting.
However, these works only compete against the Nash value of the game and are unable to exploit the opponent.
A more related paper is \cite{liu2022learning}, which develops a provably efficient algorithm that achieves a sublinear regret against the best fixed policy in hindsight.
But there results are only limited to the tabular case.
Our work extends the results \cite{liu2022learning} to the setting with general function approximation, which requires novel technical analysis.
\paragraph{Finding equilibria in self-play Markov games.}
Our work is closely related to the recent literature on finding equilibria in Markov games via reinforcement learning.
Most of the existing works focus on two-player zero-sum games and consider centralized algorithms with unknown model dynamics. For example, \cite{wei2017online, bai2020provable} utilize optimism to tackle the exploration-expoitation tradeoff and find Nash equilibria in tabular cases, and \cite{xie2020learning,jin2021power,huang2021towards} extend the results to linear and general function approximation setting.
Furthermore,
under the decentralized setting with well-explored data,
\cite{daskalakis2020independent,zhang2021gradient,sayin2021decentralized,wei2021last,leonardos2021global,ding2022independent} utilize independent policy gradient algorithms to deal with potential Markov games and two-player zero-sum games.
Meanwhile, under the online setting, \cite{bai2020near,mao2021on,jin2021v} design algorithms named V-learning, which are able to find CCE in multi-agent general-sum games. However, there results are only limited to the tabular case.
\paragraph{Constrained Markov decision process.} \cite{efroni2020exploration,ding2021provably} propose a series of primal-dual algorithms for CMDPs which achieve $\sqrt{K}$ bound on regrets and constraint violations in tabular and linear approximation cases. \cite{liu2021learning} reduces the constraint violation to $\widetilde{\mathcal{O}}(1)$ by adding slackness to the algorithm and achieves zero violation when a strictly safe policy is known; \cite{wei2021provably} further avoids such requirement with the price of worsened regrets. Nevertheless, these improvements are only discussed in the tabular case.
\paragraph{Approchability for vector-valued Markov decision process.} \cite{miryoosefi2019reinforcement} first introduces the approachability task for VMDPs but does not provide an algorithm with polynomial sample complexity. Then \cite{yu2021provably} proposes a couple of primal-dual algorithms to solve this task and achieves a $\widetilde{\mathcal{O}}(\epsilon^{-2})$ sample complexity in the tabular case. More recently, \cite{miryoosefi2021simple} utilizes reward-free reinforcement learning to tackle the problem and studies both the tabular and linear approximation cases, achieving roughly the same sample complexity as \cite{yu2021provably}.
\subsection{Self-Play Sample Complexity}
\label{sec:selfplay}
Our previous discussion assumes the opponent is arbitrary or even adversary. A natural question is to ask whether there are any additional guarantees if the player and opponent run \texttt{DORIS}\xspace simultaneously, which is exactly Algorithm~\ref{alg:MDPS self} in the self-play setting. The following corollary answers this question affirmatively and shows that Algorithm~\ref{alg:MDPS self} can find an approximate CCE $\widehat{\pi}$ efficiently:
\begin{corollary}
\label{cor:selfplay}
Suppose Assumption~\ref{ass:player},\ref{ass:realize adapt} hold for all the agents $i$ and its corresponding $\mathcal{F}_i,\mathcal{G}_i,\Pi_i,\Pi_{-i}$. Then for any $\delta\in(0,1],\epsilon>0$, if we choose
\begin{align}
\label{eq:cor1}
K\geq\mathcal{O}\bigg(H^2V_{\max}^2 \cdot \max_{i\in[n]} \biggl\{ d_{\mathrm{BEE},i} \cdot \biggl(\log\mathcal{N}_{\mathrm{cov},i}+\sum_{j=1}^n\log|\Pi_j|+\log(n/ \delta)\biggr) \biggr\}\bigg/ \epsilon^2\bigg),
\end{align}
where $d_{\mathrm{BEE},i}$ and $\mathcal{N}_{\mathrm{cov},i}$ are defined respectively as
\begin{align*}
d_{\mathrm{BEE},i}:=\mathrm{dim}_{\mathrm{BEE}}\big(\mathcal{F}_i,\sqrt{ 1 / K},\Pi_i,\Pi_{-i}\big),\quad\mathcal{N}_{\mathrm{cov},i}:=\mathcal{N}_{\mathcal{F}_i\cup\mathcal{G}_i}(V_{\max}/K)KH,
\end{align*}
and set $\beta_i=cV_{\max}^2\log(\mathcal{N}_{\mathrm{cov},i}|\Pi_i||\Pi_{-i}|n/\delta),\eta_i=\sqrt{\log|\Pi_i|/(KV_{\max}^2)}$, then with probability at least $1-\delta$, $\widehat{\pi}$ is $\epsilon$-approximate CCE.
\end{corollary}
The proof is deferred to Appendix~\ref{proof corollary selfplay}. Corollary~\ref{cor:selfplay} shows that if we run \texttt{DORIS}\xspace independently for each agent, we are able to find an $\epsilon$-approximate CCE with $\widetilde{\mathcal{O}}(1/\epsilon^2)$ samples. This can be regarded as a counterpart in Markov games to the classic connection between no-regret learning algorithms and equilibria in matrix games. This guarantee does not hold if an algorithm can only achieve low regrets with respect to the Nash values, which further validates the significance of \texttt{DORIS}\xspace to achieve low regrets under Definition~\ref{def:regret}.
\paragraph{Avoiding curse of multiagents.} The sample complexity in (\ref{eq:cor1}) avoids exponential scaling with the number of agents $n$ and only scales with $\max_{i\in[n]}d_{\mathrm{BEE},i}$, $\max_{i\in[n]}\mathcal{N}_{\mathrm{cov},i}$ and $\sum_{j=1}^n\log|\Pi_j|$, suggesting that statistically Algorithm~\ref{alg:MDPS self} is able to escape the \textit{curse-of-multiagents} problem in the literature \citep{jin2021v}. Nevertheless, the input dimension of functions in $\mathcal{F}_i$ and $\mathcal{G}_i$ may scale with the number of the agents linearly, leading to the computational inefficiency of \texttt{OptLSPE}\xspace. We comment that finding computational efficient algorithms is beyond the scope of this paper and we leave it to future works.
\paragraph{Comparison with existing algorithms.} There have been many works studying how to find equilibria in Markov games. However, most of them are focused on centralized two-player zero-sum games \citep{bai2020provable,xie2020learning,jin2021power,huang2021towards} rather than decentralized algorithms. For decentralized algorithms, existing literature mainly handle with potential Markov games \citep{zhang2021gradient,leonardos2021global,ding2022independent} and two-player zero-sum games \citep{daskalakis2020independent,sayin2021decentralized,wei2021last}. \cite{mao2021on,jin2021v} are able to tackle decentralized multi-agent general-sum Markov games while their algorithms are restricted to tabular cases. Algorithm~\ref{alg:MDPS self}, on the other hand, can deal with more general cases with function approximation and policy classes in multi-agent general-sum games. Furthermore, compared to the above works, \texttt{DORIS}\xspace has an additional advantage of robustness to adversaries since all the benign agents can exploit the opponents and achieve no-regret learning.
\paragraph{Extensions.} Although Theorem~\ref{thm:oblivious}, Theorem~\ref{thm:adaptive} and Corollary~\ref{cor:selfplay} are aimed at Markov games, \texttt{DORIS}\xspace can be applied to a much larger scope of problems. Two such problems are finding the optimal policy in constrained MDP (CMDP, Section~\ref{sec:cmdp}) and vector-valued MDP (VMDP, Section~\ref{sec:vmdp}). We will investigate these two special yet important problems later and demonstrate how to convert such problems into Markov games with a fictitious opponent by duality, where \texttt{DORIS}\xspace is ready to use.
\section{Proof Sketch of Theorem~\ref{thm:oblivious} and Theorem~\ref{thm:adaptive}}
\label{sec:proof sketch}
In this section we present a proof sketch for Theorem~\ref{thm:oblivious} and Theorem~\ref{thm:adaptive}. We first consider the oblivious setting. Let $\mu^*=\arg\max_{\mu\in\Pi}\sum_{t=1}^{K}V_1^{\mu\times\nu^t}(s_1)$ and we can decompose the regret into the following terms:
\begin{align}
&\max_{\mu\in\Pi}\sum_{t=1}^{K}V_1^{\mu\times\nu^t}(s_1)-\sum_{t=1}^{K} V_1^{\pi^t}(s_1)\notag\\
&\qquad=\bigg(\underbrace{\sum_{t=1}^{K}V_1^{\mu^*\times\nu^t}(s_1)-\sum_{t=1}^{K}\overline{V}^t(\mu^*)}_{\displaystyle(1)}\bigg) +\bigg(\underbrace{\sum_{t=1}^{K}\overline{V}^t(\mu^*)-\sum_{t=1}^{K}\langle\overline{V}^t,p^t\rangle}_{\displaystyle(2)}\bigg)\notag\\
&\qquad\qquad +\bigg(\underbrace{\sum_{t=1}^{K}\langle\overline{V}^t,p^t\rangle-\sum_{t=1}^{K}\overline{V}^t(\mu^t)}_{\displaystyle(3)}\bigg) +\bigg(\underbrace{\sum_{t=1}^{K}\overline{V}^t(\mu^t)-\sum_{t=1}^{K}V^{\pi^t}_1(s_1)}_{\displaystyle(4)}\bigg).\label{eq:decompose}
\end{align}
Our proof bounds these terms separately and mainly consists of three steps:
\begin{itemize}
\item Prove $\overline{V}^t(\mu)$ is an optimistic estimation of $V_1^{\mu\times\nu^t}(s_1)$ for all $t\in[K]$ and $\mu\in\Pi$, which implies that term $(1)\leq0$.
\item Bound term (4), the cumulative estimation error $\sum_{t=1}^K\overline{V}^t(\mu^t)-V_1^{\pi^t}(s_1)$. In this step we utilize the newly proposed complexity measure BEE dimension to bridge the cumulative estimation error and the empirical Bellman residuals occurred in \texttt{OptLSPE}\xspace.
\item Bound term (2) using the existing results of online learning error induced by Hedge and bound (3) by noticing that it is a martingale difference sequence.
\end{itemize}
\subsection{Step 1: Prove Optimism}
First we can show that the constructed set $\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu,\nu^t)$ is not vacuous in the sense that the true action-value function $Q^{\mu,\nu^t}$ belongs to it with high probability
\begin{lemma}
\label{lem:optimism}
With probability at least $1-{\delta}/{4}$, we have for all $t\in[K]$ and $\mu\in\Pi$, $Q^{\mu,\nu^t}\in\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu,\nu^t)$.
\end{lemma}
\begin{proof}
See Appendix~\ref{proof lemma optimism}.
\end{proof}
Then since $\overline{V}^t(\mu)=\max_{f\in\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu,\nu^t)}f(s_1,\mu,\nu^t)$, we know for all $t\in[K]$ and $\mu\in\Pi$,
\begin{align*}
\overline{V}^t(\mu)\geq Q^{\mu,\nu^t}(s_1,\mu,\nu^t)=V_1^{\mu\times\nu^t}(s_1).
\end{align*}
In particular, we have for all $t\in[K]$,
\begin{align}
\label{eq:optimism}
\overline{V}^t(\mu^*)\geq V_1^{\mu^*\times\nu^t}(s_1).
\end{align}
Thus, \eqref{eq:optimism} implies that $\overline{V}^t(\mu^*)$ is an optimistic estimate of $V_1^{\mu^*\times\nu^t}(s_1)$ for all $t$, and therefore term (1) in \eqref{eq:decompose} is non-positive.
\subsection{Step 2: Bound Estimation Error}
Next we aim to handle term (4) in \eqref{eq:decompose} and show the estimation error $\sum_{t=1}^K\overline{V}^t(\mu^t)-V_1^{\pi^t}(s_1)$ is small. Let
$f^{t,\mu}=\arg\max_{f\in\mathcal{B}_{\mathcal{D}_{1:t-1}}(\mu,\nu^t)}f(s_1,\mu,\nu^t)$. Then using standard concentration inequalities, we can have the following lemma which says that empirical Bellman residuals are indeed close to true residuals with high probability. Recall that here $\pi^k=\mu^k\times\nu^k$.
\begin{lemma}
\label{lem:bounded error}
With probability at least $1-{\delta}/{4}$, we have for all $t\in[K]$, $h\in[H]$ and $\mu\in\Pi$,
\begin{align}
&(a)\quad\sum_{k=1}^{t-1}\mathbb{E}_{\pi^k}\bigg[\Big(f^{t,\mu}_h(s_h,a_h,b_h)-(\mathcal{T}^{\mu,\nu^t}_h f^{t,\mu}_{h+1})(s_h,a_h,b_h)\Big)^2\bigg]\leq\mathcal{O}(\beta),\label{eq:BEE 1}\\
&(b)\quad\sum_{k=1}^{t-1}\Big(f^{t,\mu}_h(s_h^k,a_h^k,b_h^k)-(\mathcal{T}^{\mu,\nu^t}_h f^{t,\mu}_{h+1})(s_h^k,a_h^k,b_h^k)\Big)^2\leq\mathcal{O}(\beta).\label{eq:BEE 2}
\end{align}
\end{lemma}
\begin{proof}
See Appendix~\ref{proof lemma bounded error}.
\end{proof}
Besides, using performance difference lemma we can easily bridge $\overline{V}^t(\mu^t)-V_1^{\pi^t}(s_1)$ with Bellman residuals, whose proof is deferred to Appendix~\ref{proof lemma performance}:
\begin{lemma}
\label{lem:performance}
For any $t\in[K]$, we have
\begin{align*}
\overline{V}^t(\mu^t)-V_1^{\pi^t}(s_1)=\sum_{h=1}^{H}\mathbb{E}_{\pi^t}\big[(f^{t,\mu^t}_h-\mathcal{T}^{\mu^t,\nu^t}_hf^{t,\mu^t}_{h+1})(s_h,a_h.b_h)\big].
\end{align*}
\end{lemma}
Therefore, from Lemma~\ref{lem:performance} we can obtain
\begin{align}
\label{eq:regret-bellman}
\sum_{t=1}^K\overline{V}^t(\mu^t)-V_1^{\pi^t}(s_1)=\sum_{h=1}^{H}\sum_{t=1}^K\mathbb{E}_{\pi^t}\big[(f^{t,\mu^t}_h-\mathcal{T}^{\mu^t,\nu^t}_hf^{t,\mu^t}_{h+1})(s_h,a_h,b_h)\big].
\end{align}
Notice that in (\ref{eq:regret-bellman}) we need to bound the Bellman residuals of $f^{t,\mu^t}_h$ weighted by policy $\pi^t$. However, in Lemma~\ref{lem:bounded error}, we can only bound the Bellman residuals weighted by $\pi^{1:t-1}$. Fortunately, we can utilize the inherent low BEE dimension to bridge these two values with the help of the following technical lemma:
\begin{lemma}[\citep{jin2021bellman}]
\label{lem:BEE}
Given a function class $\Phi$ defined on $\mathcal{X}$ with $\phi(x)\leq C$ for all $(\phi,x)\in\Phi\times\mathcal{X}$, and a family of probability measures $\mathcal{Q}$ over $X$. Suppose sequence $\{\phi_t\}_{t=1}^K\subset\Phi$ and $\{\rho_t\}_{t=1}^K\subset\mathcal{Q}$ satisfy that for all $t\in[K]$, $\sum_{k=1}^{t-1}(\mathbb{E}_{\rho_k}[\phi_t])^2\leq\beta$. Then for all $t\in[K]$ and $w>0$,
\begin{align*}
\sum_{k=1}^t|\mathbb{E}_{\rho_k}[\phi_k]|\leq\mathcal{O}\Big(\sqrt{\mathrm{dim}_{\mathrm{DE}}(\Phi,\mathcal{Q},w)\beta t}+\min\{t,\mathrm{dim}_{\mathrm{DE}}(\Phi,\mathcal{Q},w)\}C+tw\Big).
\end{align*}
\end{lemma}
Invoking Lemma~\ref{lem:BEE} with $\mathcal{Q}=\mathcal{Q}^1_h$, $\Phi=(I-\mathcal{T}^{\Pi,\Pi'}_h)\mathcal{F}$ and $w=\sqrt{{1}/{K}}$, conditioning on the event (\ref{eq:BEE 1}) in Lemma~\ref{lem:bounded error} holds true, we have
\begin{align}
&\sum_{t=1}^K\mathbb{E}_{\pi^t}\big[(f^{t,\mu^t}_h-\mathcal{T}^{\mu^t,\nu^t}_hf^{t,\mu^t}_{h+1})(s_h,a_h.b_h)\big]\label{eq:berr 1}\\
&\qquad\leq\mathcal{O}\bigg(\sqrt{V_{\max}^2K\mathrm{dim}_{\mathrm{BEE}}\Big(\mathcal{F},\sqrt{{1}/{K}},\Pi,\Pi',\mathcal{Q}^1\Big)\log\left(\mathcal{N}_{\mathcal{F}\cup\mathcal{G}}(V_{\max}/K)KH|\Pi|/\delta\right)}\bigg).\notag
\end{align}
Similarly, invoking Lemma~\ref{lem:BEE} with $\mathcal{Q}=\mathcal{Q}^2_h$, $\Phi=(I-\mathcal{T}^{\Pi,\Pi'}_h)\mathcal{F}$ and $w=\sqrt{{1}/{K}}$, conditioning on the event (\ref{eq:BEE 2}) in Lemma~\ref{lem:bounded error} holds true, we have with probability at least $1-\delta/4$,
\begin{align}
&\sum_{t=1}^K\mathbb{E}_{\pi^t}\big[(f^{t,\mu^t}_h-\mathcal{T}^{\mu^t,\nu^t}_hf^{t,\mu^t}_{h+1})(s_h,a_h.b_h)\big]\notag\\
&\qquad\leq\sum_{t=1}^{K}\Big(f^{t,\mu^t}_h(s_h,a_h,b_h)-(\mathcal{T}^{\mu,\nu^t}_h f^{t,\mu^t}_{h+1})(s^t_h,a^t_h,b^t_h)\Big)+\mathcal{O}(\sqrt{K\log (K/\delta)})\notag\\
&\qquad\leq\mathcal{O}\bigg(\sqrt{V_{\max}^2K\mathrm{dim}_{\mathrm{BEE}}\Big(\mathcal{F},\sqrt{{1}/{K}},\Pi,\Pi',\mathcal{Q}^2\Big)\log(\mathcal{N}_{\mathcal{F}\cup\mathcal{G}}(V_{\max}/K)KH|\Pi|/\delta)}\bigg),\label{eq:berr 2}
\end{align}
where the first inequality comes from standard martingale difference concentration. Therefore, combining (\ref{eq:berr 1}) and (\ref{eq:berr 2}),we have:
\begin{align*}
&\sum_{t=1}^K\mathbb{E}_{\pi^t}\big[(f^{t,\mu^t}_h-\mathcal{T}^{\mu^t,\nu^t}_hf^{t,\mu^t}_{h+1})(s_h,a_h.b_h)\big]\notag\\
&\qquad\leq\mathcal{O}\bigg(\sqrt{V_{\max}^2K\mathrm{dim}_{\mathrm{BEE}}\Big(\mathcal{F},\sqrt{{1}/{K}},\Pi,\Pi'\Big)\log(\mathcal{N}_{\mathcal{F}\cup\mathcal{G}}(V_{\max}/K)KH|\Pi|/\delta)}\bigg).
\end{align*}
Substitute the above bounds into (\ref{eq:regret-bellman}) and we have:
\begin{align}
&\sum_{t=1}^K\overline{V}^t(\mu^t)-V_1^{\pi^t}(s_1)\label{eq:estimation}\\
&\qquad\leq\mathcal{O}\bigg(HV_{\max}\sqrt{K\mathrm{dim}_{\mathrm{BEE}}\Big(\mathcal{F},\sqrt{{1}/{K}},\Pi,\Pi'\Big)\log(\mathcal{N}_{\mathcal{F}\cup\mathcal{G}}(V_{\max}/K)KH|\Pi|/\delta)}\bigg).\notag
\end{align}
Thus, in Step 2, we establish an upper bound on term (4) in \eqref{eq:decompose}. It remains to bound term (2) and term (3), which is completed in the final step of the proof.
\subsection{Step 3: Bound the regret}
Now we only need to bound the online learning error. Notice that $p^t$ is updated using Hedge with reward $\overline{V}^t$. Since $0\leq\overline{V}^t\leqV_{\max}$ and there are $|\Pi|$ policies, we have from the online learning literature \citep{hazan2016introduction} that
\begin{align}
\label{eq:online}
\sum_{t=1}^{K}\overline{V}^t(\mu^*)-\sum_{t=1}^{K}\langle\overline{V}^t,p^t\rangle\leqV_{\max}\sqrt{K\log|\Pi|}.
\end{align}
In addition, suppose $\mathfrak{F}_{k}$ denotes the filtration induced by $\{\nu^1\}\cup(\cup_{i=1}^k\{\mu^{i},\mathcal{D}_{i},\nu^{i+1}\})$. Then we can observe that $\langle\overline{V}^t,p^t\rangle-\overline{V}^t(\mu^t)\in\mathfrak{F}_{t}$. In addition, we have $\overline{V}^t\in\mathfrak{F}_{t-1}$ since the estimation of $\overline{V}^t$ only utilizes $\mathcal{D}_{1:t-1}$, which implies
\begin{align*}
\mathbb{E}[\langle\overline{V}^t,p^t\rangle-\overline{V}^t(\mu^t)|\mathfrak{F}_{t-1}]=0.
\end{align*}
Therefore $(3)$ is a martingale difference sequence and by Azuma-Hoeffding's inequality we have with probability at least $1-\delta/4$,
\begin{align}
\label{eq:martingale}
\sum_{t=1}^{K}\langle\overline{V}^t,p^t\rangle-\sum_{t=1}^{K}\overline{V}^t(\mu^t)\leq\mathcal{O}(V_{\max}\sqrt{K\log(1/\delta)})
\end{align}
Substituting (\ref{eq:optimism}), (\ref{eq:estimation}), (\ref{eq:online}), and (\ref{eq:martingale}) into (\ref{eq:decompose}) concludes our proof for Theorem~\ref{thm:oblivious} in the oblivious setting.
Meanwhile, for the adaptive setting, we can simply repeat the above arguments. The only difference is that now $\nu^t$ can depend on $\mathcal{D}_{1:t-1}$ and thus we need to introduce a union bound over $\Pi'$ when proving Lemma~\ref{lem:optimism} and Lemma~\ref{lem:bounded error}. This will incur an additional $\log|\Pi'|$ in $\beta$ and thus also in the regret bound. This concludes our proof. | {'timestamp': '2022-06-06T02:14:58', 'yymm': '2206', 'arxiv_id': '2206.01588', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01588'} | arxiv |
\section{Introduction}
The sample efficiency of reinforcement learning (RL) algorithms crucially depends on the representation of the underlying system state they operate on \cite{finn2016deep,jonschkowski2017pves,dwibedi2018learning,kulkarni2019unsupervised,laskin2020curl,manuelli2020keypoints,vecerik2020s3k}.
Sometimes, a low-dimensional (direct) representation of the state, such as the positions of the objects in the environment, is considered to make the resulting RL problem most efficient \cite{jonschkowski2017pves}.
However, such low-dimensional, direct state representations can have several disadvantages.
On the one hand, a perception module, e.g., pose estimation, is necessary in the real world to obtain the representation from raw observations, which often is difficult to achieve in practice with sufficient robustness.
On the other hand, if the goal is to learn policies that generalize over different object shapes \cite{manuelli2019kpam},
using a low-dimensional state representation is often impractical.
Such scenarios, while challenging for RL, are common, e.g., in
robotic manipulation tasks.
Therefore, there is a large history of approaches that consider RL directly from raw, high-dimensional observations like images (e.g., \cite{mnih2013playing,mnih2015human}).
Typically, an encoder takes the high-dimensional input and maps it to a low-dimensional latent representation of the state.
The RL algorithm (e.g., the Q-function or the policy network) then operates on the latent vector as state input.
This way, no separate perception module is necessary, the framework can extract information from the raw observations that are relevant for the task, and the RL agent, in principle, may generalize over challenging environments, such as if the object shapes are varied.
While these are advantages in principle, jointly training encoders capable of processing high-dimensional inputs from the RL signal alone is challenging.
To address this, one approach is to \emph{pretrain} the encoder on a different task, e.g., image reconstruction \cite{finn2016deep,kulkarni2019unsupervised,li20223d}, multi-view consistency \cite{manuelli2020keypoints}, or a time-constrastive task \cite{dwibedi2018learning}.
Alternatively, an auxiliary loss on the latent encoding can be added \emph{during} the RL procedure \cite{laskin2020curl}.
In both cases, the choice of the actual (auto-)encoder architecture and associated (auxiliary) loss function has a significant influence on the usefulness of the resulting latent space for the downstream RL task.
Especially for image data, convolutional neural networks (CNNs) are commonly used for the encoder \cite{lange2010RLAutoencoder}.
However, 2D CNNs have a 2D (equivariance) bias, while for many RL tasks, the 3D structure of our world is essential.
Architectures like Vision Transformers \cite{vaswani2017attention,dosovitskiy2020image} may process images with no such 2D bias, but they may require large scale data, which might be challenging in RL applications.
Additionally, although multiple uncalibrated 2D image inputs can be used with generic image encoders \cite{akinola2020learning}, they do not benefit from 3D inductive bias, which may help for example in resolving ambiguities in 2D images such as occlusions and object permanence.
Recently, Neural Radiance Fields (NeRFs) \cite{mildenhall2020nerf} have shown great success in learning to represent scenes with a neural network that enables to render the scene from novel viewpoints, and have sparked broad interest in computer vision \cite{dellaert2021neural}.
NeRFs exhibit a strong 3D inductive bias, leading to better scene reconstruction capabilities than methods composed of generic image encoders (e.g., \cite{eslami2018neural}).
In the present work, we investigate whether incorporating these 3D inductive biases of NeRFs into learning a state representation can benefit RL.
Specifically, we propose to train an encoder that maps multiple RGB image views of the scene to a latent representation through an auto-encoder structure, where a (compositional) NeRF decoder provides the self-supervision signal using an image reconstruction loss for each view.
In the experiments, we show for multiple environments that supervision from NeRF leads to a latent representation that makes the downstream RL procedure more sample efficient compared to supervision via a 2D CNN decoder, a contrastive loss on the latent space, or even hand-engineered, perfect low-level state information given as keypoints. Commonly, RL is trained on environments where the objects have the same shape.
Our environments include hanging mugs on hooks, pushing objects on a table, and a door opening scenario. In all of these, the objects' shapes are not fixed, and we require the agent to generalize over all shapes from a distribution.
To summarize our main contributions: (i) we propose to train state representations for RL with NeRF supervision, and (ii) we empirically demonstrate that an encoder trained with a latent-conditioned NeRF decoder, especially with an object-compositional NeRF decoder, leads to increased RL performance relative to standard 2D CNN auto-encoders, contrastive learning, or expert keypoints.
\section{Related Work}
\textbf{Neural Scene/Object Representations in Computer Vision, and Applications.}
To our knowledge, the present work is the first to explore if neural scene representations like NeRFs can benefit RL. Outside of RL, however, there has been a very active research field in the area of neural scene representations, both in the representations themselves \cite{park2019deepsdf,mescheder2019occupancy,chen2019learning,sitzmann2019scene} and their applications; see \cite{xie2021neural,tewari2021advances,dellaert2021neural} for recent reviews. Within the family of NeRFs and related methods, major thrusts of research have included: improving modeling formulations \cite{barron2021mip,barron2021mip360}, modeling larger scenes \cite{barron2021mip360,tancik2022block}, addressing (re-)lighting \cite{Boss20arxiv_NeRD,Srinivasan20arxiv_NeRV,zhang2021nerfactor}, and an especially active area of research has been in improving speed, both of training and of inference-time rendering \cite{Liu20neurips_sparse_nerf,Lindell20arxiv_AutoInt,Rebain20arxiv_derf,neff2021donerf,Garbin21arxiv_FastNeRF,reiser2021kilonerf,yu2021plenoctrees,lombardi2021mixture,yu2021plenoxels,sitzmann2021lfns,mueller2022instant}. In our case, we are not constrained by inference-time computation issues, since we do not need to render images, and only have to run our latent-space encoder (with a runtime of approx. 7 ms on an RTX3090). Additionally of particular relevance, various methods have developed latent-conditioned \cite{martin2021nerf,yu2021pixelnerf,wang2021ibrnet} or compositional/object-oriented approaches for NeRFs \cite{Zhang20arxiv_nerf++,Niemeyer20arxiv_GIRAFFE,Guo20arxiv_OSF,yuan2021star,Wang20arxiv_hybrid_NeRF,ost2020neuralscenegraphs,yu2021unsupervised,yang2021objectnerf,2022-driess-compNerfPreprint}, although they, nor other NeRF-style methods to our knowledge, have been applied to RL. Neural scene representations have found application across many fields (i.e., augmented reality and medical imaging \cite{zhang2021nerd}) and both NeRFs \cite{YenChen20arxiv_iNeRF,adamkiewicz2022vision,ichnowski2021dex,yen2022nerfsupervision} and other neural scene approaches \cite{karunratanakul2020grasping,ha2021learning,simeonov2021neural,wi2022virdo} have started to be used for various problems in robotics, including pose estimation \cite{YenChen20arxiv_iNeRF}, trajectory planning \cite{adamkiewicz2022vision}, visual foresight \cite{li20223d,2022-driess-compNerfPreprint}, grasping \cite{karunratanakul2020grasping,ichnowski2021dex}, and rearrangement tasks \cite{ha2021learning,simeonov2021neural,yen2022nerfsupervision}.
\textbf{Learning State Representations for Reinforcement Learning.}
One of the key enabling factors for the success of deep RL is its ability to find effective representations of the environment from high-dimensional observation data~\cite{mnih2015human,silver2016mastering}. Extensive research has gone into investigating different ways to learn better state representations using various auxiliary objective functions.
Contrastive learning is a common objective and has shown success in unsupervised representation learning in computer vision applications~\cite{chen2020simple,he2020momentum}.
Researchers built upon this success and have shown such learning objectives can lead to better performance and sample efficiency in deep RL~\cite{srinivas2020curl,you2022integrating}, where the contrasting signals could come from time alignment~\cite{sermanet2018time,dwibedi2018learning}, camera viewpoints~\cite{kinose2022multi}, and different sensory modalities~\cite{chen2021multi}, with applications in real-world robotic tasks~\cite{manuelli2020keypoints,nair2022r3m}.
Extensive efforts have investigated the role of representation learning in RL~\cite{stooke2021decoupling}, provided a detailed analysis of the importance of different visual representation pretraining methods~\cite{parisi2022unsurprising}, and shown how we can improve training stability in the face of multiple auxiliary losses~\cite{yarats2019improving}.
There is also a range of additional explorations on pretraining methods with novel objective functions (e.g., bisimulation metrics~\cite{zhang2020learning} and temporal cycle-consistency loss~\cite{zakka2022xirl}) and less-explored data sources (e.g., in-the-wild images~\cite{xiao2022masked} and action-free videos~\cite{seo2022reinforcement}).
Please check the survey for more related work in this direction~\cite{lesort2018state}. Our method is different in that we explicitly utilize a decoder that includes strong 3D inductive biases provided by NeRFs, which we empirically show improves RL for tasks that depend on the geometry of the objects.
\section{Background}\label{sec:background}
\subsection{Reinforcement Learning}\label{sec:RL}
This work considers decision problems that can be described as discrete-time Markov Decision Processes (MDPs) $M = \langle \mathcal{S}, \mathcal{A}, T, \gamma, R, P_0 \rangle$.
$\mathcal{S}$ and $\mathcal{A}$ are the sets of all states and actions, respectively.
The transition probability (density) from $s$ to $s'$ using action $a$ is $T(s'\mid s,a)$. The agent receives a real-valued reward $R(s,a,s')$ after each step.
The discount factor $\gamma \in [0,1)$ trades off immediate and future rewards.
$P_0: \mathcal{S} \rightarrow \mathbb{R}_0^+$ is the distribution of the start state.
RL algorithms try to find the optimal policy $\pi^*: \mathcal{S} \times \mathcal{A} \rightarrow \mathbb{R}_0^+$, where
$
\pi^* = \argmax_{\pi} \sum_{t=0}^\infty \gamma^t \mathbb{E}_{s_{t+1} \sim T(\cdot\mid s_t,a_t),\, a_{t} \sim \pi(\cdot\mid s_t), s_0 \sim P_0}\left[ R(s_t,a_t,s_{t+1}) \right].
$
Importantly, in this work, we consider RL problems where the state $s$ encodes both the position and the shape of the objects in the scene.
We require the RL agent to generalize over all of these shapes at test time.
We can therefore think of the state as a tuple $s=(s_p, s_s)$, where $s_p$ encodes positional information, and $s_s$ encodes the shapes involved.
We focus the experiments on sparse reward settings, meaning $R(s,a,s') = R_0 > 0$ for $s'\in\mathcal{S}_g$ and $R(s,a,s') = 0$ for $s\in\mathcal{S}\backslash\mathcal{S}_g$, where the volume of $\mathcal{S}_g \subset \mathcal{S}$ is much smaller than the volume of $\mathcal{S}$.
The state space $\mathcal{S}$ usually is low-dimensional or a minimal description of the degrees of freedom of the system.
In this work, we consider that the RL algorithm has only access to a (high-dimensional) observation $y\in\mathcal{Y}$ of the scene (e.g., RGB images).
In particular, this means that the policy has observations as input $a \sim \pi(\cdot \mid y)$.
Since we assume that the underlying state $s=(s_p, s_s)$ is fully observable from $y$, we can treat $y$ like a state for an MDP.
\textbf{Reinforcement Learning with Learned Latent Scene Representations.}
The general idea of RL with learned latent scene representations is to learn an \emph{encoder} $\Omega$ that maps an observation $y\in\mathcal{Y}$ to a $k$-dimensional \emph{latent vector}
$
z = \Omega(y)\in\mathcal{Z}\subset \mathbb{R}^k \label{eq:latentRL}
$
of the scene.
The actual RL components, e.g., the Q-function or policy, then operate on $z$ as its state description.
For a policy $\pi$, this means that the action
$
a \sim \pi(\cdot\mid z) = \pi(\cdot\mid \Omega(y))
$
is conditional on the latent vector $z$ instead of the observation $y$ directly.
The dimension $k$ of the latent vector is typically (much) smaller than that of the observation space $\mathcal{Y}$, but larger than that of the state space $\mathcal{S}$.
\subsection{Neural Radiance Fields (NeRFs)}\label{sec:backgroundNerfs}
The general idea of NeRF, originally proposed by \cite{mildenhall2020nerf}, is to learn a function $f = (\sigma, c)$ that predicts the emitted RGB color value $c(x)\in\mathbb{R}^{3}$ and volume density $\sigma(x)\in\mathbb{R}_{\ge0}$ at any 3D world coordinate $x\in\mathbb{R}^3$.
Based on $f$, an image from an arbitrary view and camera parameters can be rendered by computing the color $C(r)\in\mathbb{R}^3$ of each pixel along its corresponding camera ray $r(\alpha) = r(0) + \alpha d$ through the volumetric rendering relation
\begin{align}
C(r) = \int_{\alpha_n}^{\alpha_f}T_f(r, \alpha)\sigma(r(\alpha))c(r(\alpha))\diff \alpha ~~~~~~~\text{with}~~~~~~~T_f(r, \alpha) = \exp\left(-\int_{\alpha_n}^\alpha \sigma(r(u))\diff u \right). \label{eq:nerfC}
\end{align}
Here, $r(0)\in\mathbb{R}^3$ is the camera origin, $d\in\mathbb{R}^3$ the pixel dependent direction of the ray and $\alpha_n, \alpha_f \in \mathbb{R}$ the near and far bounds within which objects are expected, respectively.
The camera rays are determined from the camera matrix $K$ (intrinsics and extrinsics) describing the desired view.
\section{Learning State Representations for RL with NeRF Supervision}\label{sec:RLWithNeRF}
This section describes our proposed framework, in which we use a latent state space for RL that is learned from NeRF supervision.
For learning the latent space, we use an encoder-decoder where the decoder is a latent-conditioned NeRF, which may either be a global \cite{martin2021nerf,yu2021pixelnerf,wang2021ibrnet} or a compositional NeRF decoder \cite{2022-driess-compNerfPreprint}.
To our knowledge, no prior work has used such NeRF-derived supevision for RL. In Sec.~\ref{subsec:nerf-latent-for-rl} we describe this proposition, Sec.~\ref{subsec:comp-nerf-overivew} provides an overview of the encoder-decoder training,
Sec.~\ref{sec:nerfDecoder} and Sec.~\ref{sec:objectEncoder} introduce options for the NeRF decoder and encoder, respectively.
\begin{figure}
\centering
\includegraphics[width=0.9\linewidth]{images/NeRF-RL2.pdf}
\vspace{-0.25cm}
\caption{State representation learning for RL with NeRFs. First, the encoder and NeRF decoder are trained with supervision from a multi-view reconstruction loss on an offline dataset. Then, the encoder's weights are frozen, and the latent space is used as state input to train a policy with RL. $^*$Masks of individual objects are only required for the compositional variant of our encoder.}
\label{fig:RLWithLearnedStateRepresentations}
\end{figure}
\subsection{Using Latent-Conditioned NeRF for RL}\label{subsec:nerf-latent-for-rl}
We propose the state representation $z$ on which an RL algorithm operates to be a latent vector produced by an encoder that maps images from multiple views to a latent $z$, which is trained with a (compositional) latent-conditioned NeRF decoder.
As will be verified in experiments, we hypothesize that this framework is beneficial for the downstream RL task, as it produces latent vectors that represent the actual 3D geometry of the objects in the scene, can handle multiple objects well, as well as fuse multiple views in a consistent way to deal with occlusions by providing shape completion, all of which is relevant to solve tasks where the geometry is important.
There are two steps to our framework, as shown in Fig.~\ref{fig:RLWithLearnedStateRepresentations}. First, we train the encoder + decoder
from a dataset collected by random interactions with the environment, i.e., we do not yet need a trained policy.
Second, we take encoder trained in the first step, which we leave frozen, and use the latent space to train an RL policy.
Note that we investigate two variants of the auto-encoder framework, a global one, where the whole scene is represented by one single latent vector, and a compositional one, where objects are represented by their own latent vector.
For the latter, objects are identified by masks in the views.
\subsection{Overview: Auto-Encoder with Latent-Conditioned NeRF Decoder}\label{subsec:comp-nerf-overivew}
Assume that an observation $y = \left(I^{1:V}, K^{1:V}, M^{1:V}\right)$ of the scene consists of RGB images $I^i\in\mathbb{R}^{3\times h \times w}$, $i=1,\ldots, V$ taken from $V$ many camera views, their respective camera projection matrices $K^i\in\mathbb{R}^{3\times 4}$ (including both intrinsics and extrinsics), and per-view image masks $M^{1:V}$.
For a {\em{global}} NeRF decoder, these are global non-background masks $M_{\text{tot}}^i\in\{0,1\}^{h\times w}$, and for a {\em{compositional}} NeRF decoder as in \cite{2022-driess-compNerfPreprint}, these are sets of binary masks $M_j^i\in\left\{0,1\right\}^{h\times w}$ that identify the objects $j=1,\ldots, m$ in the scene in view $i$. The global case is equivalent to $m=1$, $M^i_{j=1}=M^i_{\text{tot}}$.
The encoder $\Omega$ maps these posed image observations from the multiple views into a set of latent vectors $z_{1:m}$, where each $z_j$ represents each object in the scene separately in the compositional case, or the single $z_1$ all objects in the scene.
This is achieved by querying $\Omega$ on the masks $M_j^{1:V}$,
i.e.,
\begin{align}
z_{j} = \Omega\left(I^{1:V}, K^{1:V}, M^{1:V}_{j}\right) \in\mathbb{R}^k \label{eq:omega}
\end{align}
for object $j$.
The supervision signal to train the encoder is the image reconstruction loss
\begin{align}
\mathcal{L}^i = \left\|I^i\circ M^i_\text{tot} - D\left(\Omega\left(I^{1:V}, K^{1:V}, M^{1:V}_{1:m}\right), K^i\right)\right\|_2^2
\end{align}
on the input view $i$ where the decoder $D$ renders an image $I = D(z_{1:m}, K)$
for arbitrary views specified by the camera matrix $K$ from the set of latent vectors $z_{1:m}$.
Both the encoder and decoder are trained end-to-end at the same time. The target images for the decoder are the same in both the global and compositional case: the global-masked image $I^i\circ M^i_\text{tot}$ ($\circ$ is the element-wise product). In the compositional case this can be computed with
$M^i_\text{tot} = \bigvee_{j=1}^m M_j^i$.
By fusing the information from multiple views of the objects into the latent vector from which the decoder has to be able to render the scene from multiple views, this auto-encoder framework can learn latent vectors that represent the 3D configurations (shape and pose) of the objects in the scene.
\subsection{Latent-Conditioned NeRF Decoder Details}\label{sec:nerfDecoder}
\textbf{Global.} The original NeRF formulation \cite{mildenhall2020nerf} learns a fully connected network $f$ that represents one single scene (Sec.~\ref{sec:backgroundNerfs}). In order to create a decoder from NeRFs within an auto-encoder to learn a latent space, we condition the NeRF $f(\cdot, z)$ on the latent vector $z\in\mathbb{R}^k$ \cite{martin2021nerf,yu2021pixelnerf,wang2021ibrnet}. While approaches such as \cite{martin2021nerf,yu2021pixelnerf,wang2021ibrnet} use the latent code to represent factors such as lighting or category-level generalization, in our case the latent code is intended to represent the scene variation, i.e., shape \emph{and} configuration of objects, such that a downstream RL agent may use this as a state representation.
\textbf{Compositional.} In the compositional case, the encoder produces a set of latent vectors $z_{1:m}$ describing each object $j=1,\ldots, m$ individually, this leads to $m$ many NeRFs $(\sigma_j(x), c_j(x)) = f_j(x) = f(x, z_j)$, $j=1,\ldots, m$
with their associated volume density $\sigma_j$ and color value $c_j$. Note that while one could use different networks $f_j$ with their own network weights for each object, we have a single network $f$ for all objects.
This means that both the object's pose as well as its shape and type are represented through the latent code $z_j$.
In order to force those conditioned NeRFs to learn the 3D configuration of each object separately, we compose then into a global NeRF model with the composition formulas (proposed e.g., by \cite{Niemeyer2020GIRAFFE, stelzner2021decomposing}):
$
\sigma(x) = \sum_{j=1}^m \sigma_j(x)$, $c(x) = \frac{1}{\sigma(x)}\sum_{j=1}^m \sigma_j(x)c_j(x).
$
As this composition happens in 3D space, the latent vectors will be learned such that they correctly represent the actual shape and pose of the objects in the scene with respect to the other objects, which we hypothesize may be useful for the downstream RL agent.
\subsection{Encoder Details}\label{sec:objectEncoder}
The encoder $\Omega$ operates by fusing multiple views together to estimate the latent vector for the RL task.
Since the scientific question of this work is to investigate whether a decoder built from NeRFs to train the encoder end-to-end is beneficial for RL, we consider two different encoder architectures.
The first one is a 2D CNN that averages feature encodings from the different views, where each encoding is additionally conditioned on the camera matrix of that view.
The second one is based on a learned 3D neural vector field that incorporates 3D biases by fusing the different camera views in 3D space through 3D convolutions and camera projection.
This way, we are able to distinguish between the importance of 3D priors incorporated into the encoder versus the decoder.
\textbf{Per-image CNN Encoder (``Image encoder'').}
For the global version, we utilize the network architecture from \cite{li20223d} as an encoder choice.
In order to work with multiple objects in the compositional case, we modify the architecture from \cite{li20223d} by taking the object masks into account as follows.
For each object $j$, the 2D CNN encoder computes
\vspace{-0.5em}
\begin{align}
z_j = \Omega_\text{CNN}\left(I^{1:V}, K^{1:V}, M^{1:V}_{j}\right) = h_\text{MLP}\!\left(\frac{1}{V}\sum_{i=1}^Vg_\text{MLP}\!\left(E_\text{CNN}\!\left(I^i\circ M^i_j\right), K^i\right) \right).\label{eq:CNNEncoder}
\end{align}
$E_\text{CNN}$ is a ResNet-18 \cite{he2016deep} CNN feature extractor that determines a feature from the masked input image $I^i\circ M^i_j$ of object $j$ for each view $i$, which is then concatenated with the (flattened) camera matrix.
The output of the network $g_\text{MLP}$ is hence the encoding of each view, including the camera information, which is averaged and then processed with $h_\text{MLP}$, to produce the final latent vector.
Note that in the global case, we set $m=1$, $M^i_{j=1}=M_\text{tot}^i$ such that $\Omega_\text{CNN}$ produces a single latent vector.
\textbf{Neural Field 3D CNN Encoder (``Field encoder'').}
Several authors \cite{yu2021pixelnerf} have considered to incorporate 3D biases into learning an encoder by computing pixel-aligned features from queried 3D locations of the scene to fuse the information from the different camera views directly in 3D space.
We utilize the encoder architecture from \cite{2022-driess-compNerfPreprint}, where the idea is to learn a neural vector field $\phi\left[I^{1:V}, M^{1:V}_j\right]:\mathbb{R}^3\rightarrow\mathbb{R}^E$ over 3D space, conditioned on the input views and masks.
The features of $\phi$ are computed from projecting the query point into the camera coordinate system from the respective view.
To turn $\phi$ into a latent vector, it is queried on a workspace set $\mathcal{X}_h\in \mathbb{R}^{d_\mathcal{X} \times h_\mathcal{X} \times w_\mathcal{X}}$ (a 3D grid) and then processed by a 3D convolutional network, i.e., $z_j = E_\text{3D CNN}\left(\phi\left[I^{1:V}, M^{1:V}_j\right](\mathcal{X}_h)\right)$.
This method differs from \cite{yu2021pixelnerf, saito2019pifu, ha2021learning} by computing a latent vector from the pixel-aligned features.
\section{Baselines / Alternative State Representations}\label{sec:baselines}
In this section, we briefly describe alternative ways of training an encoder for RL, which we will investigate in the experiments as baselines and ablations.
\textbf{Conv.\ Autoencoder.}\label{sec:2DCNNDecoder}
This baseline uses a standard CNN decoder based on deconvolutions instead of NeRF to reconstruct the image from the latent representation, similar to \cite{finn2016deep}.
Therefore, with this baseline we investigate the influence of the NeRF decoder relative to CNN decoders.
We follow the architecture of \cite{li20223d} for the deconvolution part for the global case.
In the compositional case, we modify the architecture to be able to deal with a set of individual latent vectors instead of a single, global one.
The image
$
I = D_\text{deconv}(g_\text{MLP}(\frac{1}{m}\sum_{j=1}^m z_j), K)
$
is rendered from $z_{1:m}$ by first averaging the latent vectors and then processing the averaged vector with a fully connected network $g_\text{MLP}$, leading to an aggregated feature.
This aggregated feature is concatenated with the (flattened) camera matrix $K$ describing the desired view and then rendered into the image with $D_\text{deconv}$.
In the experiments, we utilize this decoder as the supervision signal to train the latent space produced by the 2D CNN encoder from Sec.~\ref{sec:objectEncoder}.
In the compositional version, the 2D CNN encoder \eqref{eq:CNNEncoder} use the same object masks as the compositional NeRF-RL variant.
\textbf{Contrastive Learning.}
As an alternative to learning an encoder via a reconstruction loss, the idea of contrastive learning \cite{hadsell2006dimensionality} is to define a loss function directly on the latent space that tries to pull latent vectors describing the same configurations together (called positive samples) while ones representing different system states apart (called negative samples).
A popular approach to achieve this is with the InfoNCE loss \cite{van2018representation,chen2020simple}.
Let $y_i$ and $\tilde{y}_i$ be two \emph{different} observations of the \emph{same} state.
Here, $\tilde{\cdot}$ denotes a perturbed/augmented version of the observation.
For a mini-batch of observations $\left\{(y_i, \tilde{y}_i)\right\}_{i=1}^n$, after encoding those into their respective latent vectors $z_i = \Omega(y_i)$, $\tilde{z}_i = \Omega(\tilde{y}_i)$ with the encoder $\Omega$, the loss for that batch would use ($z_i$, $\tilde{z}_i$) as a positive pair, and ($z_i$,$\tilde{z}_{\ne i}$) as a negative pair, or some similar variation.
A crucial question in contrastive learning is how the observation $y$ is perturbed/augmented into $\tilde{y}$ to generate positive and negative training pairs, described in the following.
\textbf{CURL.}
In CURL \cite{laskin2020curl}, the input image is randomly cropped to generate $y$ and $\tilde{y}$.
We closely follow the hyperparameters and design of \cite{laskin2020curl}.
CURL operates on a single input view and we carefully choose a view for this baseline from which the state of the environment can be inferred as best as possible.
\textbf{Multi-View CURL.}
This baseline investigates if the neural field 3D encoder (Sec.~\ref{sec:objectEncoder}) can be trained with a contrastive loss.
As this encoder operates on multiple input views
we \emph{double} the amount of available camera views.
Half of the views are the same as in the other experiments, the other half are captured from sightly perturbed camera angles.
We use the same loss as CURL, but with different contrastive pairs -- rather than from augmentation, the contrastive style is taken from TCN \cite{sermanet2018time}: the positive pairs come from different views but at the same moment in time, while negative pairs come from different times.
Therefore, this baseline can be seen as a multi-view adaptation of CURL \cite{laskin2020curl}.
\textbf{Direct State / Keypoint Representations.}\label{sec:keypoint}
Finally, we also consider a direct, low-dimensional representation of the state.
Since we are interested in generalizing over different object shapes, we consider multiple 3D keypoints that are attached at relevant locations of the objects by expert knowledge and observed with a perfect keypoint detector \cite{manuelli2019kpam}.
See Fig.~\ref{fig:mug:keypoints} for a visualization of those keypoints.
The keypoints both provide information about object shape and its pose.
Furthermore, as seen in Fig.~\ref{fig:mug:keypoints}, they have been chosen to reflect those locations in the environment relevant to solve the task.
Additionally, we report results where the state is represented by the poses of the objects -- as this cannot represent object shape, in this case we use a constant object shape for training and test.
\section{Experiments}\label{sec:exp}
We evaluate our proposed method on different environments where the geometry of the objects in the scene is important to solve the task successfully.
Please also refer to the video \url{https://dannydriess.github.io/nerf-rl}.
Commonly, RL is trained and evaluated on a single environment, where only the poses are changed, but the involved object shapes are kept constant.
Since latent-conditioned NeRFs have been shown to be capable of generalizing over geometry \cite{yu2021pixelnerf}, we consider experiments where we require the RL agent to generalize over object shapes within some distribution.
Answering the scientific question of this work requires environments with multi-view observations — and for the compositional versions object masks as well. These are \textit{not provided in standard RL benchmarks}, which is the reason for choosing the environments investigated in this work.
We use PPO \cite{schulman2017proximal} as the RL algorithm and four camera views in all experiments.
Refer to the appendix for more details about our environments, parameter choices, and training times.
\subsection{Environments}\label{sec:exp:environments}
\textbf{Mug on Hook.}
In this environment, adopted from \cite{driess2022CoRL} and visualized in Fig.~\ref{fig:mug:keypoints}, the task is to hang a mug on a hook.
Both the mug and the hook shape are randomized.
The actions are small 3D translations applied to the mug.
This environment is challenging as we require the RL agent to generalize over mug and hook shapes and the tolerance between the handle opening and the hook is relatively small.
Further, the agent receives a sparse reward only if the mug has been hung stably.
This reward is calculated by virtually simulating a mug drop after each action.
If the mug would not fall onto the ground from the current state, a reward of one is assigned, otherwise zero.
\textbf{Planar Pushing.}
The task in this environment, shown in Fig.~\ref{fig:box:images}, is to push yellow box-shaped objects into the left region of the table and blue objects into the right region with the red pusher that can move in the plane, i.e., the action is two dimensional.
This is the same environment as in \cite{2022-driess-compNerfPreprint} with the same four different camera views.
Each run contains a single object on the table (plus the pusher).
If the box has been pushed inside its respective region, a sparse reward of one is received, otherwise zero.
The boxes in the environment have different sizes, two colors and are randomly initialized.
In this environment, we cannot use keypoints for the multi-shape setting, as the reward depends on the object color; we evaluate the keypoints baseline only in the single shape case (Appendix).
\textbf{Door Opening.}
Fig.~\ref{fig:door:images} shows the door environment, where the task is to open a sliding door with the red end-effector that can be translated in 3 DoFs as the action.
To solve this task, the agent has to push on the door handle.
As the handle position and size is randomized, the agent has to learn to interact with the handle geometry accordingly.
Interestingly, as can be seen in the video, the agent often chooses to push on the handle only at the beginning, as, afterwards, it is sufficient to push the door itself at its side.
The agent receives a sparse reward if the door has been opened sufficiently, otherwise, zero reward is assigned.
\begin{table}[p!]
\definecolor{darkcyan14149148}{RGB}{14,149,148}
\definecolor{darkgray176}{RGB}{176,176,176}
\definecolor{gray130129109}{RGB}{130,129,109}
\definecolor{lightgray204}{RGB}{204,204,204}
\definecolor{olivedrab9615345}{RGB}{96,153,45}
\definecolor{orange24316718}{RGB}{243,167,18}
\definecolor{orangered2554310}{RGB}{255,43,10}
\definecolor{seagreen3616887}{RGB}{36,168,87}
\definecolor{sienna1146170}{RGB}{114,61,70}
\definecolor{teal875131}{RGB}{8,75,131}
\small
\renewcommand{\arraystretch}{0.8}
\begin{tabular}{clccccc}
\toprule
&& encoder & decoder & comp. & NeRF & loss \\
\midrule
NeRF- &\bfseries \color{orangered2554310} {comp.+field} & 3D CNN & comp.\ 3D NeRF & \cmark & \cmark & image reconstr.: L2 \\
RL &\bfseries \color{seagreen3616887} {comp.+image} & 2D CNN & comp.\ 3D NeRF & \cmark & \cmark & image reconstr.: L2 \\
(ours) &\bfseries \color{teal875131}{global+image} & 2D CNN & global 3D NeRF & \xmark & \cmark & image reconstr.: L2 \\
\midrule
&\color{darkcyan14149148}Conv.\ Autoencoder, {\em{c}} & 2D CNN & comp. 2D CNN & \cmark & \xmark & image reconstr.: L2 \\
&\color{darkgray176} Conv.\ Autoencoder, {\em{g}} & 2D CNN & 2D CNN & \xmark & \xmark & image reconstr.: L2 \\
&\color{sienna1146170}CURL & 2D CNN & - & \xmark & \xmark & contrast: InfoNCE\\
&\color{olivedrab9615345}Multi-CURL & 3D CNN & - & \cmark & \xmark & contrast: InfoNCE \\
\midrule
&\color{orange24316718}Keypoints & \multicolumn{5}{c}{chosen by expert knowledge and perfect extraction}\\
\bottomrule
\end{tabular}
\vspace{-0.2cm}
\caption{Overview of the different state representation learning frameworks.}
\label{tab:overviewStateRepresentations}
\end{table}
\begin{figure}[p!]
\vspace{-0.5cm}
\centering
\hspace{-0.3cm}
\begin{minipage}{0.49\textwidth}
\subfloat[Learning curve.]{
\includetikz{plots/mug_multi_confidence}
\label{fig:mug:learning}
}
\end{minipage}%
\begin{minipage}{0.49\textwidth}
\subfloat[Left: Blue coordinate frames denote the four camera poses. Red points are the expert keypoints. Right: NeRF renderings (different scenes).]{
\shortstack{
\includetikz{plots/mug_multi_confidence_legend}\\
\includegraphics[trim={0 6cm 0 2cm}, clip, height=1.9cm]{images/mug/mugWithKeypoints}
}
\shortstack{
\includegraphics[height=1.75cm]{images/mug/48_0.png}\\
\includegraphics[height=1.75cm]{images/mug/0_2.png}
}
\shortstack{
\includegraphics[height=1.75cm]{images/mug/19_1.png}\\
\includegraphics[height=1.75cm]{images/mug/9_3.png}
}
\label{fig:mug:keypoints}
}
\vspace{-0.16cm}
\end{minipage}
\vspace{-0.2cm}
\caption{Mug on hook environment. (b) shows an example scene and NeRF renderings}
\label{fig:mug}
\end{figure}
\begin{figure}[p!]
\vspace{-0.5cm}
\centering
\hspace{-0.3cm}
\begin{minipage}{0.49\textwidth}
\subfloat[Learning curve.]{
\includetikz{plots/box_multi_confidence}
\label{fig:box:learning}
}
\end{minipage}%
\begin{minipage}{0.49\textwidth}
\subfloat[Left: Blue coordinate frames denote the four camera poses. Yellow and blue areas are goal regions where the objects should be pushed to. Right: NeRF renderings.]{
\shortstack{
\includetikz{plots/box_multi_confidence_legend}\\
\includegraphics[trim={0 3cm 0 2cm}, clip, height=2.05cm]{images/box/box}
}
\shortstack{
\includegraphics[trim={1cm 0cm 1cm 0cm}, clip, height=1.8cm]{images/box/15_0.png}\\
\includegraphics[trim={1cm 0cm 1cm 0cm}, clip, height=1.8cm]{images/box/21_3.png}
}
\shortstack{
\includegraphics[trim={1cm 0cm 1cm 0cm}, clip, height=1.8cm]{images/box/37_1.png}\\
\includegraphics[trim={1cm 0cm 1cm 0cm}, clip, height=1.8cm]{images/box/7_2.png}
}
\label{fig:box:images}
}
\vspace{-0.16cm}
\end{minipage}
\vspace{-0.2cm}
\caption{Pushing environment. (b) shows NeRF renderings for different scenes.}
\label{fig:box}
\end{figure}
\begin{figure}[p!]
\vspace{-0.5cm}
\centering
\hspace{-0.3cm}
\begin{minipage}{0.49\textwidth}
\subfloat[Learning curve.]{
\includetikz{plots/door_multi_confidence}
\label{fig:door:learning}
}
\end{minipage}%
\begin{minipage}{0.49\textwidth}
\subfloat[Left: Blue coordinate frames denote the four camera poses. Right: NeRF renderings.]{
\shortstack{
\includetikz{plots/door_multi_confidence_legend}\\
\includegraphics[trim={0 4cm 0 0cm}, clip, width=2.2cm]{images/door/door}
}
\shortstack{
\includegraphics[width=2.cm]{images/door/0_0}\\
\includegraphics[width=2.cm]{images/door/19_1}
}
\shortstack{
\includegraphics[width=2.cm]{images/door/34_2}\\
\includegraphics[width=2.cm]{images/door/62_3}
}
\label{fig:door:images}
}
\end{minipage}
\vspace{-0.2cm}
\caption{Door environment. (b) shows NeRF renderings for different scenes.}
\label{fig:door}
\end{figure}
\subsection{Results}\label{sec:exp:results}
Figs~\ref{fig:mug:learning}, \ref{fig:box:learning}, \ref{fig:door:learning} show success rates (averaged over $6$ independent experiment repetitions and over $30$ test rollouts per repetition per timestep) as a function of training steps.
Also shown are the $68\%$ confidence intervals.
These success rates have been evaluated using randomized object shapes and initial conditions, and therefore reflect the agent's ability to generalize over these.
In all these experiments, a latent space trained with compositional NeRF supervision as the decoder consistently outperformed all other learned representations, both in terms of sample efficiency and asymptotic performance.
Furthermore, our proposed framework with compositional NeRF even outperforms the expert keypoint representation.
For the door environment, the 3D neural field encoder plus NeRF decoder (NeRF-RL comp.\ + field) reaches nearly perfect success rates.
For the other two environments, the compositional 2D CNN encoder plus NeRF decoder (NeRF-RL comp.\ + image) was slightly better than with the neural field encoder but not significantly.
This shows that the \emph{decoder} built from compositional NeRF is relevant for the performance, not so much the choice of the encoder.
Training the 3D neural field encoder with a contrastive loss as supervision signal for different camera views as positive/negative training pairs is not able to achieve significant learning progress in these scenarios (Multi-CURL).
However, the other contrastive baseline, CURL, which has a different encoder and uses image cropping as data augmentation instead of additional camera views, is able to achieve decent performance and sample efficiency on the door environment, but not for the pushing environment.
In the mug environment, CURL initially is able to make learning progress comparable to our framework, but never reaches a success rate above 59\% and then becomes unstable.
Similarly, the global CNN autoencoder baseline shows decent learning progress initially on the mug and pushing scenario (not for the door), but then becomes unstable (mug) or never surpasses 50\% success rate (pushing).
Such variations in performance or instable learning across the different environments have not been observed with our method, which is stable in all cases.
The compositional variant (NeRF-RL comp.) of our framework achieves the highest performance.
Since the conv.\ comp.\ autoencoder baseline has worse performance than its global variant, compositionality alone is not the sole reason for the better performance of our state representation.
Indeed, the global NeRF-RL + image variant in the pushing env.\ is also better than all other baselines.
\section{Discussion}\label{sec:discussion}
\paragraph{Why NeRF provides better supervision.}
The NeRF training objective \eqref{eq:nerfC} strongly forces each $f(\cdot, z_j)$ to represent each object in its actual 3D configuration and relative to other objects in the scene (compositional case), including their shape.
This implies that the latent vectors $z_j$ have to contain this information, i.e., they are trained to determine the object type, shape and pose in the scene.
In the global case, $z_1$ has to represent the geometry of the whole secne.
As the tasks we consider require policies to take the geometry of the objects into account, we hypothesize that a latent vector that is capable of parameterizing a NeRF to reconstruct the scene in the 3D space has to contain enough of the relevant 3D information of the objects also for the policy to be successful.
\paragraph{Masks.}
In order for the auto-encoder framework to be compositional, it requires object masks.
We believe that instance segmentation has reached a level of maturity \cite{he2017mask} that this is a fair assumption to make.
As we also utilize the individual masks for the compositional conv. autoencoder and the multi-view CURL baseline, which do not show good performance, it indicates that the masks are not the main reason that our state representation achieves higher performance.
This is further supported by the fact that the global NeRF-RL variant which does not rely on individual object masks on the pushing scenario achieved a performance higher than all baselines, i.e., masks will increase the performance of NeRF-RL as they enable the compositional version, but they do not seem essential.
\paragraph{Offline/Online.}
In this work, we focused on pretraining the latent representation offline from a dataset collected by random actions.
During RL, the encoder is fixed and only the policy networks are learned.
This has the advantage that the same representation can be used for different RL tasks and the dataset to train the representation not necessarily has to come from the same distribution.
However, if a policy is needed to explore reasonable regions of the state space, collecting a dataset offline to learn a latent space that covers the state space sufficiently might be more challenging for an offline approach.
This was not an issue for our experiments where data collection with random actions was sufficient.
Indeed, we show generalization over different starting states of the same environment and with respect to different shapes (within distribution).
Future work could investigate NeRF supervision in an online setup.
Note that the reconstruction loss via NeRF is computationally more demanding than via a 2D CNN deconv.\ decoder or a contrastive term, making NeRF supervision as an auxiliary loss at each RL training step costly.
One potential solution for this is to apply the auxiliary loss not at every RL training step, but with a lower frequency.
Regarding computational efficiency, this is where contrastive learning has an advantage over our proposed NeRF-based decoder, as the encoding with CURL can be trained within half a day, whereas the NeRF auto-encoder took up to 2 days to train for our environments.
However, when using the encoder for RL, there is no difference in inference time.
\paragraph{Multi-View.}
The auto-encoder framework we propose can fuse the information of multiple camera views into a latent vector describing an object in the scene.
This way, occlusions can be addressed and the agent can gain a better 3D understanding of the scene from the different camera angles.
Having access to multiple camera views and their camera matrices is an additional assumption we make, although we believe the capability to utilize this information is an advantage of our method.
\section{Conclusion}\label{sec:conclusion}
In this work, we have proposed the idea to utilize Neural Radiance Fields (NeRFs) to train latent spaces for RL.
Our environments focus on tasks where the geometry of the objects in the scene is relevant for successfully solving the tasks.
Training RL agents with the pretrained encoder that maps multiple views of the scene to a latent space consistently outperformed other ways of learning a state representation and even keypoints chosen by expert knowledge.
Our results show that the 3D prior present in compositional NeRF as the decoder is more important than priors in the encoder.
\textbf{Broader Impacts.} Our main contribution is a method to learn representations that improve the efficiency of vision-based RL, which could impact automation.
As such, our work inherits general ethical risks of AI, like the question of how to address the potential of increased automation in society.
\section*{Acknowledgments}
The authors thank Russ Tedrake for initial discussions; Jonathan Tompson and Jon Barron for feedback on drafts; Vincent Vanhoucke for encouraging latent NeRFs.
This research has been supported by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) under Germany's Excellence Strategy – EXC 2002/1 ``Sience of Intelligence'' – project number 390523135.
Danny Driess thanks the International Max-Planck Research School for Intelligent Systems (IMPRS-IS) for the support.
\bibliographystyle{corlabbrvnat}
| {'timestamp': '2022-06-06T02:16:23', 'yymm': '2206', 'arxiv_id': '2206.01634', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01634'} | arxiv |
\section{Appendix}
\subsection{Missing Data Mechanisms}
\label{subsec:missing_data}
Let $\displaystyle {\bm{X}} \in \mathbb{R}^{n \times p}$ represent the data matrix of $n$ samples with $p$ features. Each sample $\displaystyle {\bm{x}} \in {\bm{X}}$ then can be decomposed into observed $\displaystyle {\bm{x}}^o$ and missing $\displaystyle {\bm{x}}^m$ components where the pattern of the missing values can be indicated by a mask vector $\displaystyle {\bm{m}} \in \{0,1\}^p$. Using these notation, the underlying mechanisms for missing values in data can be divided into three categories~\citep{rubin1976inference, ghahramani1995learning,schafer2002missing}:
\begin{enumerate}
\item \textbf{Missing Completely at Random (MCAR):} where there is no systematic relationship between the patterns of missingness with either observed or unobserved variables, \textit{i.e.}, $\displaystyle p({\bm{m}} \mid {\bm{x}}^o, {\bm{x}}^m)=p({\bm{m}})$. In this case the missingness patterns are completely at random and do not depend on observed or missing data.
\item \textbf{Missing at Random (MAR):} is a weaker assumption than MCAR (MCAR data is MAR but not vice-versa), in which the patterns of missingness are independent from missing data but may depend on observed values, \textit{i.e.}, $\displaystyle p({\bm{m}} \mid {\bm{x}}^o, {\bm{x}}^m)=p({\bm{m}} \mid {\bm{x}}^o)$.
\item \textbf{Missing Not at Random (MNAR):} where the pattern of missingness depends on the values of missing data, \textit{i.e.}, $\displaystyle p({\bm{m}} \mid {\bm{x}}^o, {\bm{x}}^m)$ depends on the values in $\displaystyle {\bm{x}}$. An example of MNAR is censored data in which a certain range of data is missing.
\end{enumerate}
\subsection{Activation of (m)PROMISSING Neurons}
\label{subsec:activations_proofs}
\subsubsection{Derivation of Eq.~\ref{eq:promissing_activation}}
\label{subsubsec:eq1_proofs}
Eq.~\ref{eq:promissing_activation} can be derived by inserting Eq.~\ref{eq:neuralizer} in Eq.~\ref{eq:activation} for missing inputs $\displaystyle x_j \in {\bm{x}}^m$:
\begin{equation*}
\label{eq:eq3_derivation}
\begin{split}
\displaystyle a^{(k)} = & \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \sum_{x_j \in {\bm{x}}^m} x_j w^{(k)}_j + b^{(k)} \quad \xrightarrow[]{x_j = \frac{-b^{(k)}}{pw^{(k)}_j}} \\
a^{(k)} = & \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \sum_{x_j \in {\bm{x}}^m} \frac{-b^{(k)}w^{(k)}_j}{pw^{(k)}_j} + b^{(k)} \\
= & \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \frac{-rb^{(k)}+pb^{(k)}}{p} =
\sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \frac{(p-r)b^{(k)}}{p} \\
= & \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \frac{qb^{(k)}}{p}.
\end{split}
\end{equation*}
\subsubsection{Proof of Proposition~\ref{prop:promissing1}}
\label{subsubsec:prop1_proofs}
When all input values are missing ($\displaystyle {\bm{x}}^o= \varnothing$, $q=0$, and $r=p$), then the activation of a PROMISSING neuron is zero:
\begin{equation*}
\label{eq:prop1_proofs}
\begin{split}
\displaystyle a^{(k)} = & \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \sum_{x_j \in {\bm{x}}^m} x_j w^{(k)}_j + b^{(k)} \quad \xrightarrow[{\bm{x}}^o= \varnothing]{x_j = \frac{-b^{(k)}}{pw^{(k)}_j}} \\
a^{(k)} = & \sum_{x_j \in {\bm{x}}^m} \frac{-b^{(k)}w^{(k)}_j}{pw^{(k)}_j} + b^{(k)} = \frac{-rb^{(k)}}{p} + b^{(k)} \quad \xrightarrow[]{r=p} \\
a^{(k)} = & 0.
\end{split}
\end{equation*}
\subsubsection{Proof of Proposition~\ref{prop:promissing2}}
\label{subsubsec:prop2_proofs}
When there are no missing values in inputs ($\displaystyle {\bm{x}}^m= \varnothing$, $q=p$, and $r=0$), then the activation of a normal neuron (Eq.~\ref{eq:activation}) is computed as follows:
\begin{equation*}
\begin{split}
\label{eq:activation_normal}
\displaystyle a^{(k)} = & \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \sum_{x_j \in {\bm{x}}^m} x_j w^{(k)}_j + b^{(k)} \quad \xrightarrow[]{{\bm{x}}^m= \varnothing} \\
a^{(k)} = & \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + b^{(k)}.
\end{split}
\end{equation*}
In this case, the activation of a PROMISSING neuron is exactly equal to an ordinary neuron:
\begin{equation*}
\label{eq:promissing_activation_detailed}
\displaystyle a^{(k)} = \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \frac{qb^{(k)}}{p} \quad \xrightarrow[]{p=q} \quad \displaystyle a^{(k)} = \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + b^{(k)}.
\end{equation*}
\subsubsection{Proof of Proposition~\ref{prop:promissing3}}
\label{subsubsec:prop3_proofs}
When there are no missing values in inputs ($\displaystyle {\bm{x}}^m= \varnothing$, $q=p$, and $r=0$), the activation of an mPROMISSING neuron is exactly equal to an ordinary neuron:
\begin{equation*}
\label{eq:mpromissing_activation_detailed}
\displaystyle \displaystyle a^{(k)} = \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \frac{qb^{(k)}+rw^{(k)}_c}{p} \quad \xrightarrow[r=0]{p=q} \quad \displaystyle a^{(k)} = \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + b^{(k)}.
\end{equation*}
\subsection{A \texttt{nanDense} Layer}
\label{subsec:nandense}
A preliminary implementation of a \texttt{nanDense} layer is listed in Listing \ref{list:nandense}. This layer is implemented by inheriting and overloading the class constructor, \texttt{build}, and \texttt{call} functions. A flag, \texttt{use\_c}, is added to the class constructor to decide whether to use compensatory weights or not (defaulted to \texttt{False}). Using this flag, the user can simply switch between PROMISSING and mPROMISSING. Furthermore, the flag \texttt{use\_bias} is fixed to \texttt{True}. In the \texttt{build} function an extra weight is concatenated to the end of the weight vector to implement compensatory weight in the case \texttt{use\_c==True}. The matrix of epsilons is also pre-set for usage in the \texttt{call} function. In the \texttt{call} function, the values for compensatory weights and neutralizers are computed, accordingly. The current implementation is limited to non-sparse 2-dimensional inputs. The implementation is preliminary and not optimized for memory and speed efficiencies. This implementation is tested with \texttt{Python 3.8.3}, \texttt{TensorFlow 2.4.1}, and \texttt{Keras 2.4.3}. A similar guideline may be followed to implement PROMISSING within other types of NN layers.
\begin{lstlisting}[language=Python, label=list:nandense ,caption=An implementation of a \texttt{nanDense} layer in Keras.]
import keras
import tensorflow as tf
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.keras import backend as K
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.keras.engine.input_spec import InputSpec
from tensorflow.python.keras import activations
from tensorflow.python.keras import initializers
from tensorflow.python.keras import regularizers
from tensorflow.python.keras import constraints
class nanDense(keras.layers.Dense):
def __init__(self,
units,
use_c = False, # A flag to use compensatory weight or not.
activation=None,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
**kwargs):
super(nanDense, self).__init__(units,
activity_regularizer=activity_regularizer, **kwargs)
self.use_c = use_c
self.use_bias = True
self.units = int(units) if not isinstance(units, int) else units
self.activation = activations.get(activation)
self.kernel_initializer = initializers.get(kernel_initializer)
self.bias_initializer = initializers.get(bias_initializer)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.bias_regularizer = regularizers.get(bias_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.bias_constraint = constraints.get(bias_constraint)
self.input_spec = InputSpec(min_ndim=2)
self.supports_masking = True
def build(self, input_shape):
dtype = dtypes.as_dtype(self.dtype or K.floatx())
if not (dtype.is_floating or dtype.is_complex):
raise TypeError('Unable to build `nanDense` layer with non-floating point '
'dtype
input_shape = tensor_shape.TensorShape(input_shape)
last_dim = tensor_shape.dimension_value(input_shape[-1])
if last_dim is None:
raise ValueError('The last dimension of the inputs to `nanDense` '
'should be defined. Found `None`.')
self.input_spec = InputSpec(min_ndim=2, axes={-1: last_dim})
if self.use_c: # an extra weight if use_c is True.
self.kernel = self.add_weight(
'kernel',
shape=[last_dim+1, self.units],
initializer=self.kernel_initializer,
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint,
dtype=self.dtype,
trainable=True)
else:
self.kernel = self.add_weight(
'kernel',
shape=[last_dim, self.units],
initializer=self.kernel_initializer,
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint,
dtype=self.dtype,
trainable=True)
self.bias = self.add_weight(
'bias',
shape=[self.units,],
initializer=self.bias_initializer,
regularizer=self.bias_regularizer,
constraint=self.bias_constraint,
dtype=self.dtype,
trainable=True)
self.epsilon = tf.fill(self.kernel.shape, K.epsilon()) # Epsilon Matrix
self.built = True
def call(self, inputs):
dtype = self._compute_dtype_object
if self.use_c: # Computing and concatenating the compensatory weight to the weights
c = tf.math.reduce_sum(tf.cast(tf.math.is_nan(inputs), dtype), axis=1)
c = tf.math.divide(c, inputs.shape[1])
inputs = tf.concat([inputs,tf.expand_dims(c, axis=1)], axis=1)
kernel = math_ops.add(self.epsilon, self.kernel) # Adding epsilon to weights
if self.dtype:
if inputs.dtype.base_dtype != dtype.base_dtype:
inputs = math_ops.cast(inputs, dtype=dtype)
rank = inputs.shape.rank
if rank == 2 or rank is None:
if isinstance(inputs, sparse_tensor.SparseTensor):
raise NotImplementedError
else:
outputs = []
for i in range(self.kernel.shape[1]): # Computing Neutralizers and activations for each neuron
d = tf.math.divide(-self.bias[i]/self.kernel.shape[0], kernel[:,i])
temp_inputs = tf.where(tf.math.is_nan(inputs), d, inputs) # replacing nans in inputs with -b/w
outputs.append(gen_math_ops.mat_mul(temp_inputs, kernel[:,i:i+1]))
outputs = tf.concat(outputs, axis=1)
# Broadcast kernel to inputs.
else:
raise NotImplementedError
outputs = nn_ops.bias_add(outputs, self.bias)
if self.activation is not None:
outputs = self.activation(outputs)
return outputs
\end{lstlisting}
\subsection{Missing Data Simulations}
\label{subsec:missing_data_simulation}
We used the same procedures in~\citet{schelter2021jenga} to simulate the missing values in our experiments on simulated and OpenML data. For MAR and MNAR settings, first, a random range of a certain feature $F1$ is selected. This random range is decided based on random lower and upper bound percentiles. In the MAR condition, the values of a second random feature $F2$ are removed if the values of $F1$ lie in the specified range, \textit{i.e.}, the missing values in $F2$ depend on the observations in $F1$ (see Fig.~\ref{fig:Simulated_Data_mar} for an example). In contrast in the MNAR case, the values are removed from the same $F1$ feature. In fact, in the MNAR case the values of $F1$ are censored for in a certain range (see Fig.~\ref{fig:Simulated_Data_mnar} for an example). In the MCAR setting, the samples with missing value are selected completely at random (see Fig.~\ref{fig:Simulated_Data_mcar}).
\begin{figure}
\centering
\begin{subfigure}[h]{0.75\textwidth}
\centering
\includegraphics[width=\textwidth]{Figures/Experiment_1_MCAR_0.3_data.pdf}
\caption{Simulated data and imputation results in MCAR setting.}
\label{fig:Simulated_Data_mcar}
\end{subfigure}
\vfill
\begin{subfigure}[h]{0.75\textwidth}
\centering
\includegraphics[width=\textwidth]{Figures/Experiment_1_MAR_0.3_data.pdf}
\caption{Simulated data and imputation results in MAR setting.}
\label{fig:Simulated_Data_mar}
\end{subfigure}
\vfill
\begin{subfigure}[h]{0.75\textwidth}
\centering
\includegraphics[width=\textwidth]{Figures/Experiment_1_MNAR_0.3_data.pdf}
\caption{Simulated data and imputation results in MNAR setting.}
\label{fig:Simulated_Data_mnar}
\end{subfigure}
\caption{In each panel: a) The simulated XOR data. The effect of b) zero, c) mean, d) KNN, and e) iterative imputations on simulated data with MCAR, MAR, and MNAR missing values. The missing values for the first feature (x-axis) are selected based on a random range of the second feature (y-axis).}
\label{fig:Simulated_Data}
\end{figure}
Fig.~\ref{fig:Simulated_Data}b-e illustrate the effect of applying different data imputation methods. In all cases, imputation may result in the misrepresentation of samples with missing values.
\subsection{Supplementary Material for the Simulation Study}
\label{subsec:full_dark_matter}
To better understand the learned representation of unknowns $\displaystyle {\bm{U}}$, we have visualized the elements in $\displaystyle {\bm{U}}$ across 100 simulation replications. Fig.~\ref{sfig:dark_matter} shows the values of $\displaystyle {\bm{U}}$ across 100 simulation runs in our simulation study. In our simulation study, $\displaystyle {\bm{U}}$ has eight values (two inputs for each four input neurons). Markers with similar color and shape represent the neutralizer values for two features (axes) in four neurons in a specific run. For example, the four blue circles show the values of four neutralizers in two-dimensional feature space in the first run of the experiment. Since the scatter plot is very crowded, we plotted only the 8 representative runs in Fig.~\ref{fig:Experiment_1_analysis_8} in the main text in Sec.~\ref{subsec:simulation}. Since $\displaystyle {\bm{U}}$ is derived from the network parameters, due to the stochastic nature of parameter initialization and optimization, it may end up with different values in each run (local minima). Our visual inspection shows that the network finds four main groups of solutions for representing unknowns.
Fig.~\ref{fig:Experiment_1_analysis_8} depicts elements in $\displaystyle {\bm{U}}$ for 8 selected runs that represent these four groups. In this case, $\displaystyle {\bm{U}}$ has eight elements (two inputs for four neurons). Markers with similar colors represent the neutralizer values for two features (axes) and four neurons in a specific run (legends). The neutralizers in the first group (1 and 11) are roughly zero imputers in which the missing values are imputed with close to (but not absolutely) zero values. These are sub-optimal solutions that happen only in a few runs. In the other cases, the models seem to perform more than a simple imputer. In another minority group, represented by runs 52 and 100, the model turns to a mean imputer for the first feature, but it learns diverse representation for the second feature; the neurons see unknowns as borderline samples. In another minority group (represented by run 41 and 81), some neurons see unknowns as samples with extreme values (outside or close to the outer range of inputs). Run 7 and 10 represent the majority group of solutions in which each neuron has its unique perception of unknowns.
\begin{figure}[t]
\begin{center}
\includegraphics[width=0.95\textwidth]{Figures/Experiment_1_0.3_results.pdf}
\end{center}
\caption{Comparison between learning curves of PROMISSING and mPROMISSING with data imputation approaches on simulated MCAR, MAR, and MNAR data, when tested on a test set without missing values (first row) and with $30\%$ missing values (second row).}
\label{fig:Experiment_1_sup_results}
\vspace{-0.5cm}
\end{figure}
\begin{figure}
\centering
\begin{subfigure}[h]{0.55\textwidth}
\centering
\includegraphics[width=\textwidth]{Figures/Experiment_1_MCAR_0.5_analysis.pdf}
\caption{The patterns of neutralizers for MCAR data.}
\label{fig:dark_matter_mcar}
\end{subfigure}
\vfill
\begin{subfigure}[h]{0.55\textwidth}
\centering
\includegraphics[width=\textwidth]{Figures/Experiment_1_MAR_0.5_analysis.pdf}
\caption{The patterns of neutralizers for MAR data.}
\label{fig:dark_matter_mar}
\end{subfigure}
\vfill
\begin{subfigure}[h]{0.55\textwidth}
\centering
\includegraphics[width=\textwidth]{Figures/Experiment_1_MNAR_0.5_analysis.pdf}
\caption{The patterns of neutralizers for MNAR data.}
\label{fig:dark_matter_mnar}
\end{subfigure}
\caption{Patterns of neutralizer elements across two input features and the four neurons across 100 simulation repetitions. The markers with the same color and shape show the neutralizer values for each of four neurons in a specific run (the legends) of the pipeline. The blue and red dots in the background are representing the simulated data.}
\label{sfig:dark_matter}
\end{figure}
\begin{figure}[h]
\vspace{-0.5cm}
\begin{center}
\includegraphics[width=0.55\textwidth]{Figures/Experiment_1_8_MNAR_0.5_analysis.pdf}
\end{center}
\caption{Pattern of neutralizers in $\displaystyle {\bm{U}}$ across two input features and the four neurons. The markers with the same color show the neutralizer values for each of four neurons in a specific run (legends) of the pipeline. The blue and red dots in the background are representing the simulated data.}
\label{fig:Experiment_1_analysis_8}
\end{figure}
\subsection{Supplementary Materials for Experiments on OpenML Data}
\label{subsec:experiment2_supplementary}
Table~\ref{tab:classification_datasets} and Table~\ref{tab:regression_datasets} summarize the OpenML datasets that are respectively used in our classification and regression analyses in Sec.~\ref{subsec:openml}. We used exactly the same datasets as in~\citet{jager2021benchmark}.
\begin{table}[h]
\caption{Classification datasets that are used in our analysis in Sec.~\ref{subsec:openml}.}
\label{tab:classification_datasets}
\centering
\resizebox{0.7\textwidth}{!}{%
\begin{tabular}{@{}l|lrrc@{}}
\toprule
\multicolumn{1}{c}{} &
\multicolumn{1}{c}{\textbf{\begin{tabular}[c]{@{}c@{}}Dataset \\ Name\end{tabular}}} &
\multicolumn{1}{c}{\textbf{\begin{tabular}[c]{@{}c@{}}OpenML \\ ID\end{tabular}}} &
\multicolumn{1}{c}{\textbf{\begin{tabular}[c]{@{}c@{}}Sample \\ Num.\end{tabular}}} &
\multicolumn{1}{c}{\textbf{\begin{tabular}[c]{@{}c@{}}Feature \\ Num.\end{tabular}}} \\ \midrule
1 & space-ga & 737 & 3107 & 6 \\
2 & pollen & 871 & 3848 & 5 \\
3 & wilt & 40983 & 4839 & 5 \\
4 & analcatdata-supreme & 728 & 4052 & 7 \\
5 & phoneme & 1489 & 5404 & 5 \\
6 & delta-ailerons & 803 & 7129 & 5 \\
7 & visualizing-soil & 923 & 8641 & 4 \\
8 & bank8FM & 725 & 8192 & 8 \\
9 & compas-two-years & 42192 & 5278 & 13 \\
10 & bank-marketing & 1558 & 4521 & 16 \\
11 & mammography & 310 & 11183 & 6 \\
12 & mozilla4 & 1046 & 15545 & 5 \\
13 & wind & 847 & 6574 & 14 \\
14 & churn & 40701 & 5000 & 20 \\
15 & sylvine & 41146 & 5124 & 20 \\
16 & ringnorm & 1496 & 7400 & 20 \\
17 & twonorm & 1507 & 7400 & 20 \\
18 & houses & 823 & 20640 & 8 \\
19 & airlines & 42493 & 26969 & 7 \\
20 & eeg-eye-state & 1471 & 14980 & 14 \\
21 & MagicTelescope & 1120 & 19020 & 10 \\
22 & Amazon-employee-access & 4135 & 32769 & 9 \\
23 & BNG(tic-tac-toe) & 137 & 39366 & 9 \\
24 & BNG(breast-w) & 251 & 39366 & 9 \\
25 & Click-prediction-small & 1220 & 39948 & 9 \\
26 & electricity & 151 & 45312 & 8 \\
27 & fried & 901 & 40768 & 10 \\
28 & mv & 881 & 40768 & 10 \\
29 & Run-or-walk-information & 40922 & 88588 & 6 \\
30 & default-of-credit-card-clients & 42477 & 30000 & 23 \\
31 & numerai28.6 & 23517 & 96320 & 21 \\ \bottomrule
\end{tabular}%
}
\end{table}
\begin{table}[h]
\caption{Regression datasets that are used in our analysis in Sec.~\ref{subsec:openml}.}
\label{tab:regression_datasets}
\centering
\resizebox{0.7\textwidth}{!}{%
\begin{tabular}{@{}llrrc@{}}
\toprule
\multicolumn{1}{c}{} &
\multicolumn{1}{c}{\textbf{\begin{tabular}[c]{@{}c@{}}Dataset\\ Name\end{tabular}}} &
\multicolumn{1}{c}{\textbf{\begin{tabular}[c]{@{}c@{}}OpenML\\ ID\end{tabular}}} &
\multicolumn{1}{c}{\textbf{\begin{tabular}[c]{@{}c@{}}Sample\\ Num.\end{tabular}}} &
\textbf{\begin{tabular}[c]{@{}c@{}}Feature\\ Num.\end{tabular}} \\ \midrule
\multicolumn{1}{l|}{1} & stock-fardamento02 & 42545 & 6277 & 6 \\
\multicolumn{1}{l|}{2} & auml-eml-1-d & 42675 & 4585 & 10 \\
\multicolumn{1}{l|}{3} & delta-elevators & 198 & 9517 & 6 \\
\multicolumn{1}{l|}{4} & sulfur & 23515 & 10081 & 6 \\
\multicolumn{1}{l|}{5} & kin8nm & 189 & 8192 & 8 \\
\multicolumn{1}{l|}{6} & wine-quality & 287 & 6497 & 12 \\
\multicolumn{1}{l|}{7} & Long & 42636 & 4477 & 19 \\
\multicolumn{1}{l|}{8} & Brazilian-houses & 42688 & 10692 & 12 \\
\multicolumn{1}{l|}{9} & dataset-sales & 42183 & 10738 & 14 \\
\multicolumn{1}{l|}{10} & BNG(echoMonths) & 1199 & 17496 & 9 \\
\multicolumn{1}{l|}{11} & cpu-act & 197 & 8192 & 21 \\
\multicolumn{1}{l|}{12} & house-8L & 218 & 22784 & 8 \\
\multicolumn{1}{l|}{13} & Bike-Sharing-Demand & 42712 & 17379 & 9 \\
\multicolumn{1}{l|}{14} & BNG(lowbwt) & 1193 & 31104 & 9 \\
\multicolumn{1}{l|}{15} & elevators & 216 & 16599 & 18 \\
\multicolumn{1}{l|}{16} & 2dplanes & 215 & 40768 & 10 \\
\multicolumn{1}{l|}{17} & COMET-MC-SAMPLE & 23395 & 89640 & 4 \\
\multicolumn{1}{l|}{18} & diamonds & 42225 & 53940 & 9 \\
\multicolumn{1}{l|}{19} & BNG(stock) & 1200 & 59049 & 9 \\
\multicolumn{1}{l|}{20} & BNG(mv) & 1213 & 78732 & 10 \\
\multicolumn{1}{l|}{21} & auml-url-2 & 42669 & 95911 & 12 \\ \bottomrule
\end{tabular}%
}
\end{table}
Fig.~\ref{fig:Experiment_0_classification} and Fig.~\ref{fig:Experiment_0_regression} compare the performance of our naive NN architecture (that are used in our experiments in Sec.~\ref{subsec:openml}) with a random forest (RF) classifier or regressor across (with default settings) benchmark datasets. The errorbars represent the variation in AUC/SMSE across 10 repetitions. The models are evaluated in a 2-fold cross-validation scheme. The random number generator seed is fixed for all algorithms in each repetition. Our results show that our simple NN architecture with two hidden layers generally performs as well as random forest models. Both NN and RF models show near the chance performance on 'pollen', 'egg-eye-state', and 'numerai28.6', thus we have removed these datasets from our analyses in Sec.~\ref{subsec:openml}. About the regression tasks, again we observed poor performance (SMSE$>$1) of both models in the case of 'stock-fardamento02', 'wine-quality', and 'Bike-Sharing-Demand' datasets. Thus, they are removed from our analysis.
\begin{figure}
\centering
\begin{subfigure}[h]{0.995\textwidth}
\centering
\includegraphics[width=\textwidth]{Figures/Experiment_0_classification.pdf}
\caption{AUCs in classification tasks. The higher score is better.}
\label{fig:Experiment_0_classification}
\end{subfigure}
\vfill
\begin{subfigure}[h]{0.995\textwidth}
\centering
\includegraphics[width=\textwidth]{Figures/Experiment_0_regression.pdf}
\caption{SMSEs in regression tasks. The less score is better.}
\label{fig:Experiment_0_regression}
\end{subfigure}
\caption{Comparison between the performance of our simple NN architecture with random forest across a) 31 classification and b) 21 regression tasks.}
\label{fig:Experiment_0}
\end{figure}
Fig.~\ref{fig:Experiment_3_regression} shows the results for experiments in Sec~\ref{subsec:openml} in the regression tasks. Plots show the difference between the SMSE of the full model (trained on complete data) and the model trained on data with missing values. As expected the difference in SMSE increases with an increase in the ratios of missing samples and features. The (m)PROMISSING shows competitive performance compared to HGB and the better performing imputers, \textit{i.e.}, the zero, mean, and KNN imputers.
\begin{figure}[t]
\begin{center}
\includegraphics[width=0.995\textwidth]{Figures/Experiment_3_regression.pdf}
\end{center}
\caption{Comparing increase in SMSEs in regression tasks with respect to the full model across five different imputation methods, HGB, and (m)PROMISSING in MCAR, MAR, and MNAR settings.}
\label{fig:Experiment_3_regression}
\end{figure}
In an extra experiment, we used the MCAR scheme to simulate different ratios of samples (0.1, 0.25, 0.5, 0.9) and features (0.1, 0.25, 0.5, 0.75, 1) with missing values across datasets. Please bear in mind that applying this setting (with more than one feature with missing values) to the MAR and MNAR conditions is tricky because guaranteeing the assumptions behind these schemes can be complicated. Fig.~\ref{fig:Experiment_2_classification} compares the performance of different data imputation methods with (m)PROMISSING on the classification tasks for different missing sample ratios (in each panel) and missing feature ratios (x-axes). The AUC drops with respect to the full model (trained on complete data) are averaged across different datasets and ten runs. The (m)PROMISSING shows competitive performance compared to the better performing imputers, \textit{i.e.}, the mean and KNN imputers. Especially, mPROMISSING performs slightly better when the ratio of missing features is increasing. A similar overall pattern can be observed when comparing the increase in the SMSE in the regression tasks (see Fig.~\ref{fig:Experiment_2_regression}). In summary, these results show that (m)PROMISSING can compete with data imputation approaches without the need for filling the unknowns.
\begin{figure}[t]
\begin{center}
\includegraphics[width=0.995\textwidth]{Figures/Experiment_2_classification.pdf}
\end{center}
\caption{Comparing AUC drops with respect to the full model across four different imputation methods, HGB, and (m)PROMISSING in classification tasks.}
\label{fig:Experiment_2_classification}
\end{figure}
\begin{figure}[t]
\begin{center}
\includegraphics[width=0.995\textwidth]{Figures/Experiment_2_regression.pdf}
\end{center}
\caption{Comparing increase in SMSEs with respect to the full model across four different imputation methods, HGB, and (m)PROMISSING in regression tasks.}
\label{fig:Experiment_2_regression}
\end{figure}
\section{Summary and Conclusions}
\label{sec:conclusions}
In this work, we presented PROMISSING, a promising and novel \emph{second} thought on dealing with missing data in neural networks. Unlike previous works, we do not intend to replace missing values based on their relation to other features or the joint distribution of observed data. Instead, we opt to use the unknowns as an additional source of information by learning a representation for missing data. The learned representation is used to prune missing values by neutralizing their effect on the neurons' activation. The proposed method is convenient, intuitive, and reliable. It is convenient because it is straightforward in implementation and application; there is no need for extra data preparation, and the missing values are directly fed to the model; and unlike some data imputation methods, it is flexible with all input data types including continuous, binary, and categorical. This feature makes PROMISSING irreplaceable in applications of neural networks on multi-modal datasets with a mixture of diverse features. It is intuitive because it reacts to unknowns like a living agent; the more the unknowns, the less the actions. Moreover, it is reliable since it performs as well as its alternatives while its decisions are calibrated with the amount of information it receives. Furthermore, it provides an embedded mechanism to explain the decisions of complex neural networks models which is favorable for more reliable applications of ML in clinical decision making. Therefore, we consider PROMISSING as one step ahead towards more naturalistic ML-based decision-making in uncertain environments. Despite our extensive experiments, some analytical and empirical aspects of PROMISSING remain unexplored. Exploring the connection between modeling unknowns and model uncertainty, empirical comparison with model-based incomplete data modeling, and applications on more complex and structured data are among the unexplored avenues that we consider as future work.
\section{Experiments and Results}
\label{sec:experiments}
In a set of three experiments, 1) in a simulation study, we investigate the convergence behaviors of (m)PROMISSING on MCAR, MAR, and MNAR data; 2) in a large experiment on real data, we benchmark the reliability of (m)PROMISSING in several classification and regression tasks, and 3) on a multi-modal clinical dataset, we demonstrate an application of PROMISSING on an open problem of psychosis prognosis prediction.
\begin{figure}[t]
\begin{center}
\includegraphics[width=0.995\textwidth]{Figures/Experiment_1_0.5_results.pdf}
\end{center}
\caption{Comparison between learning curves of PROMISSING and mPROMISSING with data imputation approaches on simulated MCAR, MAR, and MNAR data, when tested on a test set without missing values (first row) and with $50\%$ missing values (second row).}
\label{fig:Experiment_1_results}
\vspace{-0.5cm}
\end{figure}
\subsection{Simulated Data}
\label{subsec:simulation}
We conducted a simple analysis of synthesized data to better understand the behaviors of PROMISSING. For data simulation, we simulated the XOR problem with 1000 samples. Gaussian noise with a variance of 0.25 is added to data. We simulated the missing data for MCAR, MAR, and MNAR settings. The same procedures as in~\citet{schelter2021jenga} are used to simulate the MCAR, MAR, and MNAR missing values (see Appendix~\ref{subsec:missing_data_simulation} for details). The experiments are repeated for $30\%$ and $50\%$ missing samples. We used scikit-learn~\citep{pedregosa2011scikit} for implementing different data imputation schemes.\footnote{Scikit-learn 0.24.2 with Numpy 1.19.5.} We also compared our method with a GAN-based imputation proposed in~\citet{yoon2018gain}. Default configurations are used for all imputers.
To evaluate (m)PROMISSING, we used a simple fully connected NN architecture with four tangent-hyperbolic neurons in the hidden layer and a single sigmoid neuron in the output layer. This simple architecture can reach the performance of the Bayes optimal classifier (AUC=$0.99 \pm 0.01$) on simulated data without missing values (see the black lines in Fig.~\ref{fig:Experiment_1_results}). We randomly divided the simulated data into training and test sets with 500 samples in each set. The pipeline of 1) data simulation, 2) random data corruption with missing values, 3) randomly splitting data into the training and test set, and 4) training the model is repeated 100 times, and the standard deviation of performances across repetitions is reported (shadowed areas in Fig.~\ref{fig:Experiment_1_results}). We have fixed the random number generator seed in each repetition (randomly selected from $[0,100000]$) to ensure a fair comparison between models. A stochastic gradient descent (SGD) optimizer is used to minimize a binary cross-entropy loss function. We evaluated the network performance as the training procedure proceeds in two different settings i) on the complete test set without missing data, and ii) on the test set with missing values.
The first row of plots in Fig.~\ref{fig:Experiment_1_results} shows the area under the ROC curve (AUC) for models trained on data with $50\%$ missing values (see Fig.~\ref{fig:Experiment_1_sup_results} for $30\%$) and tested on test sets without missing values as the number of epochs progresses. Here, by comparing the performance gap between the different missing data curation strategies and the optimal Bayes classifier, we can evaluate the \emph{training bias} imposed by each strategy during the training. A lower training bias indicates a lower effect of data curation strategy on the quality of the trained model. Our empirical results show that the training bias is modulated by both the strategy and missing data mechanism. In the MCAR setting, all strategies show less training bias. However, in the MAR and MNAR conditions, the model biases are more pronounced, especially with higher percentages of missing values. The (m)PROMISSING techniques show a competitive performance, especially in the MNAR setting where they perform equivalently with mean, KNN, and MICE imputers (with Wilcoxon rank-sum test p-values of 0.26, 0.02, and 0.15) and better performance than zero and GAIN imputations (p-values$\leq3\times10^{-12}$). These results confirm that the (m)PROMISSING models provide the possibility to learn meaningful representations for the unknowns that are at least as informative as imputed data.
The second row of plots in Fig.~\ref{fig:Experiment_1_results} compares the learning curves of models when tested on the test set with missing values. By comparing the final performance of models in the first and second row, we immediately notice the performance drops across almost all strategies. These performance drops show the negative effect of data degradation imposed by each imputation method on the generalization of models when applied to data with missing values. Thus, we refer to this difference as \emph{test bias}. While all methods show similar test bias in the MCAR and MAR scenarios, the (m)PROMISSING models show a negligible test bias in the MNAR scenario, \textit{i.e.}, the performance of (m)PROMISSING models is not affected when they are applied to test data with MNAR missing values. Furthermore, m(PROMISSING) methods show significantly better performance on MNAR test data (p-values$\leq 6 \times 10^{-6}$). The small training and test biases of the (m)PROMISSING models in the MNAR setting confirm their effectiveness in jointly modeling the data and missing patterns.
We have further analyzed the patterns of neutralizers in $\displaystyle {\bm{U}}$ to interpret the learned representations of unknowns in PROMISSING (see Fig.~\ref{sfig:dark_matter} in appendix~\ref{subsec:full_dark_matter}). Since $\displaystyle {\bm{U}}$ is derived from the network parameters, due to the stochastic nature of parameter initialization and optimization, it may end up with different values in each repetition. Our visual inspection shows that each neuron learns a different solution for unknowns, ranging from a simple zero or mean imputer to more complex patterns. This is a unique feature for PROMISSING providing the possibility to learn a neuron-specific imputation strategy from data.
\begin{figure}[t]
\begin{center}
\includegraphics[width=0.995\textwidth]{Figures/Experiment_3_classification.pdf}
\end{center}
\caption{Comparing AUC drops in classification tasks with respect to the full model across five different imputation methods, HGB, and (m)PROMISSING in MCAR, MAR, and MNAR settings.}
\label{fig:Experiment_3_classification}
\vspace{-0.5cm}
\end{figure}
\subsection{OpenML Data}
\label{subsec:openml}
In the second set of experiments, we benchmarked (m)PROMISSING alongside several imputation techniques on a range of publicly available classification and regression datasets from OpenML~\citep{vanschoren2014openml}. We used the same classification and regression datasets as in~\citet{jager2021benchmark} (see Table~\ref{tab:classification_datasets} and Table~\ref{tab:regression_datasets} in appendix~\ref{subsec:experiment2_supplementary}). Here, we use a simple fully-connected architecture with two hidden layers, with $p/2$ ReLU neurons in the first and two neurons in the second hidden layer, so the architecture changes slightly from one dataset to another depending on the number of features. A single output neuron with a sigmoid or linear transfer function is used for output layers in classifiers or regressors, respectively. Our quick experiments on benchmark datasets show that this simple architecture provides competitive results with random forest classifiers and regressors (see Fig~\ref{fig:Experiment_0} in appendix~\ref{subsec:experiment2_supplementary}). We excluded three classification and three regression datasets from our analyses due to the poor performance of baseline models on the complete data (see appendix~\ref{subsec:experiment2_supplementary}). We used MCAR, MAR, and MNAR schemes to simulate different ratios (0.1, 0.25, 0.5, 0.9) of samples with missing values across datasets. The same procedures as in~\citet{schelter2021jenga} are used to simulate the MAR and MNAR missing values. In the MNAR setting, a random percentile of the most informative feature (based on the mutual information with the target variable) is removed. In the MAR case, values in the most informative feature are removed based on a random percentile of the second most informative feature (see Appendix~\ref{subsec:missing_data_simulation} for more details). An SGD optimizer for 100 epochs with a mini-batch size of 10 samples is used in the training process to minimize a binary cross-entropy or a mean squared error (MSE) loss in the classification or regression scenario. The performances of different methods are evaluated in a 2-fold cross-validation scheme computing the AUC and standardized MSE (SMSE) metrics. The whole experiment pipeline, including 1) simulating missing values, 2) data imputation (this step does not apply to (m)PROMISSING), 3) data standardization, 4) model training and evaluation, is repeated twenty times with a fixed random number generator seed in each repetition. When imputing data, the default imputer settings are applied. We have also included the histogram-based gradient boosting (HGB)~\citep{ke2017lightgbm} --that similar to (m)PROMISSING provides a mechanism to directly deal with missing values without imputation-- in our experiments.
Fig.~\ref{fig:Experiment_3_classification} compares the performance of different data imputation methods with (m)PROMISSING in classification tasks for various missing value mechanisms and missing sample ratios (x-axes). The AUC drops with respect to the full model (trained and tested on complete data) are plotted. To summarize the results across datasets and replication runs, we first compute the median performance across datasets and then average across twenty replications. While in all settings the HGB is the best performer, the (m)PROMISSING shows competitive performance with the better performing imputers. A similar overall pattern can be observed when comparing the increase in the SMSE in regression tasks (see Fig.~\ref{fig:Experiment_3_regression} in appendix~\ref{subsec:experiment2_supplementary}). In summary, these results show that (m)PROMISSING can compete with data imputation approaches without the need for filling the unknowns, thus it is more flexible with underlying missing data mechanisms and all input data types including continuous, binary, and categorical.
\subsection{Clinical Application: Psychosis Prognosis Prediction}
\label{subsec:ppp}
Missing data are seemingly ubiquitous in the healthcare domain. In general, clinical datasets contain multi-modal data that are collected through different measurement tools, including patient questionnaires, medical reports and instruments, biological tests, and imaging data. Each modality may represent a different aspect of a disease or treatment outcome. Therefore, employing smart modality fusion techniques is inevitable to best benefit from these rich data. However, this goal is occluded because these data are collected through different sources and often include missing variables or even missing modalities. In this section, we demonstrate an application of PROMISSING in multi-modal data fusion and counterfactual model interpretation for psychosis prognosis prediction (PPP).
\begin{wraptable}{r}{8cm}
\vspace{-0.5cm}
\centering
\caption{Data modalities in the OPTiMiSE dataset.}
\label{tab:optimise_data}
\resizebox{0.5\textwidth}{!}{%
\begin{tabular}{@{}llcccl@{}}
\toprule
\multicolumn{1}{c}{} &
\multicolumn{1}{c}{\textbf{Modality}} &
\textbf{\begin{tabular}[c]{@{}c@{}}Measures\\ Num.\end{tabular}} &
\textbf{\begin{tabular}[c]{@{}c@{}}Samples\\ with NaNs\end{tabular}} &
\textbf{\begin{tabular}[c]{@{}c@{}}Percentage \\ of NaNs\end{tabular}} &
\multicolumn{1}{c}{\textbf{Description}} \\ \midrule
\multicolumn{1}{l|}{1} & Demographics & 20 & 300 & $16\%$ & Socio-demographic features \\
\multicolumn{1}{l|}{2} & Diagnosis & 6 & 45 & $6\%$ & Illness related features \\
\multicolumn{1}{l|}{3} & Lifestyle & 7 & 421 & $21\%$ & Use of substances like drugs and alcohol \\
\multicolumn{1}{l|}{4} & Somatic & 11 & 92 & $13\%$ & Psychical examination \\
\multicolumn{1}{l|}{5} & Treatment & 1 & 67 & $14\%$ & Average dosage of medication \\
\multicolumn{1}{l|}{6} & MINI & 67 & 47 & $8\%$ & Psychiatric comorbidity \\
\multicolumn{1}{l|}{7} & Cytokines & 34 & 100 & $20\%$ & Proteins important in cell signaling \\
\multicolumn{1}{l|}{8} & PANSS & 30 & 42 & $8\%$ & Positive and Negative Syndrome Scale \\
\multicolumn{1}{l|}{9} & PSP & 5 & 57 & $11\%$ & Personal and Social Performance Scale \\
\multicolumn{1}{l|}{10} & CGI & 1 & 46 & $9\%$ & Clinical Global Impression \\
\multicolumn{1}{l|}{11} & CDSS & 9 & 53 & $11\%$ & Measurement scale about depression \\
\multicolumn{1}{l|}{12} & SWN & 20 & 81 & $16\%$ & Subjective Well-Being Under Neuroleptic \\ \midrule
\multicolumn{1}{l}{} & Summary & 211 & - & $13\%$ & \multicolumn{1}{c}{-} \\ \bottomrule
\end{tabular}%
}
\end{wraptable}
\subsubsection{OPTiMiSE Dataset}
\label{subsubsec:optimise}
We used the OPTiMiSE dataset~\citep{kahn2018amisulpride}, an antipsychotic three-phase switching study: 495 patients with schizophrenia, schizophreniform, or schizoaffective disorder according to DSM-IV diagnosis standards. The patients received different medications in a three-phase study design. We used the data from the first phase of the study in which the patients were treated with amisulpride for four weeks. Only 376 patients who finished the first phase are used in our experiments. In a PPP framework, we aimed to predict the probability of patients' symptomatic remission based on the Positive and Negative Syndrome Scale (PANSS) as defined by consensus criteria~\citep{andreasen2005remission}. We used 12 different data modalities in our experiments (see Table~\ref{tab:optimise_data}). In total, $13\%$ values in the dataset are missing. These missing values include complete or partial missed modalities. The missing values are scattered across patients and measures; somehow, if we remove all subjects with missing values only 17 patients are left. This observation substantiates, even more, the importance of missing data management in clinical datasets. We have applied a minimal preprocessing pipeline on the data before the modeling stage. The input data contains binary, categorical, and continuous variables. We used 0/1 and one-hot encoding for binary and categorical variables, respectively. All continuous variables are standardized before feeding them to the model. Considering the unbalanced class distributions ($67\%$ of patients get remitted), in each fold of K-fold cross-validation, we resampled the minority class samples in the training data to match its size to the majority class.
\begin{wrapfigure}{R}{0.5\textwidth}
\vspace{-0.5cm}
\begin{center}
\includegraphics[width=0.495\textwidth]{Figures/MM_Model.pdf}
\end{center}
\caption{The NN architecture with middle and late information fusion for psychosis prognosis prediction on multi-modal data.}
\label{fig:MM_Model}
\vspace{-0.25cm}
\end{wrapfigure}
\subsubsection{A Multi-Modal Model for PPP}
\label{subsubsec:ppp_model}
Inspired by~\citet{huang2020multimodal}, we used a multi-modal NN architecture with middle and late information fusion. As depicted in Fig.~\ref{fig:MM_Model}, our model has five layers: input, representation learning, modality-specific classification, fusion, and classification. The network receives the data from $M$ different modalities in the input layer. Since input samples may contain missing values, we use \texttt{nanDense} layers right after the input layer in the representation learning phase. These layers transfer the raw inputs to an intermediate representations. We roughly (without any optimization and solely based on input feature size) fixed the number of neurons in this layer for each modality (Demographics=10, Diagnosis=10, Lifestyle=5, Somatic=5, Treatment=2, MINI=10, Cytokines=10, PANSS=10, PSP=5, CGI=2, CDSS=5, SWN=5). In the modality-specific classification layer, we use 2 Softmax neurons to classify the modality-specific representations into target classes, \textit{i.e.}, whether a patient remits given a certain amount of medication after four weeks. These decisions are merged with middle representation and then fed to the fusion layer. A trivial ReLU \texttt{Dense} layer with five neurons is used for the fusion layer. Finally, two Softmax neurons are used to classify the fused data into target classes. Dropout layers with a probability of $0.1$ are applied before any weighted layer. An Adam~\citep{kingma2014adam} optimizer (with learning rate of $0.0003$) is used to minimize the total categorical cross-entropy loss across classification layers.
\begin{figure}[t]
\vspace{-0.5cm}
\begin{center}
\includegraphics[width=0.995\textwidth]{Figures/Experiment_4.pdf}
\end{center}
\caption{The trajectories of model predictions for 17 patients with information loss when using a) data imputation, b) PROMISSING, and c) mRPOMISSING methods to handle missing data.}
\label{fig:Experiment_4}
\vspace{-0.5cm}
\end{figure}
\subsubsection{Evaluation and Comparison}
\label{subsubsec:ppp_results}
We first compared (m)PROMISSING with two alternative strategies: i) removing features with missing values and ii) data imputation. In the first case, we first removed subjects that completely missed one data modality; then, we removed features containing missing values. This procedure ended up losing 67 subjects and $78\%$ of features including two modalities. In the second case, we used a KNN to impute the missing data. Note that, due to binary and categorical features, many imputation techniques (such as mean and iterative imputer) cannot be directly applied to our data. Even in the KNN case, we needed to set the number of neighbors equal to one to avoid float numbers for the categorical features. A 10-fold cross-validation scheme is employed for model evaluations, and all the experiments are repeated ten times to evaluate the variability in performances. The results support our conclusion in Sec.~\ref{subsec:openml} that (m)PROMISSING performs as well as data imputation. PROMISSING and mPROMISSING result in AUCs of $0.67\pm0.02$ and $0.66\pm0.02$ that are on a par with the KNN imputer $0.66\pm0.02$. However, as is expected, removing missing features resulted in an impaired model performance of $0.61\pm0.02$. The similar performance of (m)PROMISSING and data imputation despite their completely different strategies to deal with missing values raises two questions: ``Do the resulting models behave similarly too?", ``If not, how are they different?". Craving to answer these questions, we set up the second set of experiments on the OPTiMiSe data.
In the next experiment, we left all the 17 patients with complete data in the test set and used the other 359 patients (with missing data) for training. Here, to fully use the capabilities of (m)PROMISSING models, we have augmented the training data by removing different subsets of modalities from data. Having $M=12$ modalities and $n=470$ samples (after balancing the training data) in the training set, this procedure resulted in $1,919,010$ samples ($\sum_{m=0}^{M-1}\binom{M}{m} \times n$). We trained three models, one using KNN imputation and two using (m)PROMISSING. Then, we have used a particular procedure for testing these models on the test set. In 100 repetitions, we have removed the modalities one by one and in random order. Fig.~\ref{fig:Experiment_4} shows the trajectories of predictions for 17 test subjects across three models. The trajectories show the predicted probability of remission when the model has access to less information about the patients (from complete information on the left to no information on the right). Note that it is impossible to remove all modalities in the KNN imputation case because it impairs the imputation mechanism. The interesting observation is the difference between the prediction behavior of models when they have less information available. The model trained and tested on imputed data always reacts to inputs even in an unknown environment. While the predictions of m(PROMISSING) models monotonically converge to 0.5, \textit{i.e.}, the models become indecisive in an unknown environment. As expected, the predictions of the PROMISSING model are slightly below the chance when the number of missing values increases, but this divergence is corrected in mPROMISSING. This feature is crucial in delicate applications of ML in the medical domain in which the decisions made by machines can significantly affect the quality of life of patients.
One possible application of PROMISSING is in counterfactual interpretation (CI)~\citep{mothilal2020explaining} of model decisions. CI is an effective method for the causal interpretation of complex models such as NNs. PROMISSING facilitates the usage of CI; we can simply use artificially inserted missing values to create the counterfactual examples. In other words, to evaluate the effect of one variable or modality on the final prediction, we assume it is missing in a counterfactual scenario. To demonstrate this feature, we used this technique on the predictions of an mPROMISSING model. The first and second row of Fig.~\ref{fig:Experiment_5_CFI} show respectively the CI results for four example patients with correct and incorrect predictions on their remission. In the first case (Fig.~\ref{fig:Experiment_5_CFI}a), the model correctly predicts no-remission, and CI shows that the demographic features are the decisive factor by reducing the probability of remission by $\sim0.5$. Similar inference can be used to explain the false decisions. For example, PANSS and MINI measures are decisive factors in wrong model predictions in Fig.~\ref{fig:Experiment_5_CFI}c and ~\ref{fig:Experiment_5_CFI}d, respectively. This extra level of model explainability at the individual patient level is valuable in the clinical settings as it answers the ``Why?" question often asked by the clinicians about decisions of black box models, and hopefully, paves the way towards the new field of precision psychiatry~\citep{fernandes2017new}.
\begin{figure}[t]
\begin{center}
\includegraphics[width=0.995\textwidth]{Figures/Experiment_5_CFI.pdf}
\end{center}
\caption{Counterfactual interpretation of model decisions using mPROMISSING for a) true negative, b) true positive, c) false negative, and d) false positive examples in model predictions.}
\label{fig:Experiment_5_CFI}
\vspace{-0.5cm}
\end{figure}
\section{Introduction}
\label{sec:introduction}
Missing and incomplete data are abundant in real-world problems; however, the learning and inference procedures in machine learning (ML) models highly rely on high-quality and complete data. Therefore, it is necessary to develop new methods to deal with data imperfections in rugged environments. Currently, the most popular way to deal with imperfect data is to impute the missing values. However, if we consider the learning and inference procedures in our brain as a role model for ML algorithms, data imputation barely follows the natural principles of incomplete data processing in our brain. This is because the imputation is generally based on using a heuristic for \emph{replacing} missing values. Our brain does not impute incomplete sensory information but instead uses its incompleteness as a separate source of information for decision making. For example, by only hearing the rain we can estimate how hard it is raining, and we do not necessarily need to receive visual information. Instead, we direct our attention more toward our auditory inputs to decide whether to go out with an umbrella. In addition, the more we miss sensory information, the more cautious we get in decision-making. That is why we are more careful in darker environments.
Neural networks (NNs) are brain-inspired algorithms that are very popular these days (under the name of deep learning) for learning complex relationships between inputs and target variables. However, they are in principle unable to handle incomplete data with missing values. They mainly rely on matrix operations which cannot operate on not-a-number (NaN) values. Only one NaN in a dataset impairs the forward propagation in a network. There are three solutions to this problem~\citep{garcia2010pattern}: i) removing samples or features with missing values, ii) imputing the missing values, and iii) modeling the incomplete data. Removing the samples with missing values can be very costly, especially in small-sample size and high-dimensional datasets. For example, data collection in clinical applications is an expensive procedure in terms of time, finance, and patient burden. Moreover, removing even a few samples from small datasets can affect negatively the generalization performance of the final model. Removing informative features with missing values is also compensated with lower model performance. Therefore, filling the information gaps is inevitable.
There are various techniques for data imputation, ranging from simply imputing missing values with a constant to more sophisticated ML-based imputation approaches~\citep{little2019statistical,garcia2010pattern}. One can categorize the most common techniques into three main categories: i) constant imputation, ii) regression-based imputation, and iii) ML-based imputation. In constant imputation, the missing values are replaced with a constant, \textit{e.g.}, zeros or mean/median of features. It has been shown that constant imputation is Bayes consistent when the missing features are not informative~\citep{josse2019consistency}. In the regression-based imputation, a linear or non-linear regression model is derived to predict the missing values. This method can be used to impute a single or multiple features. The most popular regression-based imputation is Multiple Imputation by Chained Equations (MICE)~\citep{van2011mice,azur2011multiple}. In MICE, an iterative procedure of predicting missing values and re-training regressors with updated predictions is performed for a limited number of cycles. The central assumption behind the MICE approach is that the missing values are missed at random (see~\citet{rubin1976inference} and Appendix~\ref{subsec:missing_data} for definitions of missing value mechanisms including missing completely at random (MCAR), missing at random (MAR), and missing not at random (MNAR)). Applying MICE can result in biased estimations if this assumption is not satisfied~\citep{azur2011multiple}. Another critical limitation of regression-based imputation is its high computational complexity~\citep{caiafa2021learning}. If we do not know which feature will be missed at the test time, for $d$ features, we need to train $d$ different regression models. In the ML-based approach ML algorithms, such as a K-nearest neighbor (KNN), regularized linear model~\citep{jiang2021adaptive}, decision trees~\citep{twala2008good}, random forest~\citep{xia2017adjusted}, neural network~\citep{bengio1996recurrent}, or generative model~\citep{yoon2018gain,ipsen2020not,collier2020vaes,nazabal2020handling}, are used for handling missing data.
As an alternative solution to data imputation, one can use the elegance of probabilistic modeling to model the incomplete data under certain assumptions. One seminal work in this direction is presented by~\citet{ghahramani1994supervised}, where a Gaussian Mixture Model (GMM) is used to estimate the joint density function on incomplete data using an Expectation-Maximization (EM) algorithm. This approach is later adopted and extended to logistic regression~\citep{williams2005incomplete}, Gaussian processes, support vector machines~\citep{smola2005kernel}, and multi-class non-linear classification~\citep{liao2007quadratically}. However, despite their good performance on small-size datasets, their application remained limited on big and high-dimensional data due to the high computational complexity~\citep{caiafa2021learning}. To overcome this issue, \citet{caiafa2021learning} proposed a sparse dictionary learning algorithm that is trained end-to-end, and simultaneously learns the parameters of the classifier and sparse dictionary representation. \citet{le2020neumiss} proposed NeuMiss, a neural-network architecture that uses a differentiable imputation procedure in a impute-then-regress scheme~\citep{morvan2021s}. A notable feature of NeuMiss is its robustness to MNAR data. Inverse probability weighted estimation~\citep{wooldridge2007inverse,seaman2013review} is another probabilistic approach for handling missing values without imputation in which the weights for samples with many missing values are inflated based on an estimation of the sampling probability. Recently, \citet{smieja2018processing} proposed a modified neuron structure that uses GMM with a diagonal covariance matrix (assuming MAR) to estimate the density of missing data. GMM parameters are learned with other network parameters. Conveniently, it handles missing values in the first layer of the network, and the rest of the architecture remains unchanged. Elsewhere, \citet{nowicki2016novel} proposed a new neural network architecture based on rough set theory~\citep{pawlak1998rough} for learning from imperfect data. It is fascinating that this method can say ``I do not know" when a large portion of input values are missing, unlike traditional models trained on imputed data that may predict definite outcomes even on completely unmeasured samples, \textit{i.e.}, they run in the absolute darkness. These predictions can be dangerous with catastrophic consequences in more delicate applications of ML for example in autonomous driving, robotic surgery, or clinical decision-making.
In this work, we attack the problem of modeling incomplete data using artificial neural networks without data imputation. We propose a simple technique for pruning missing values (PROMISSING) in which the effect of missing values on the activation of a neuron is neutralized. In this strategy, a missing value is not replaced by arbitrary values (\textit{e.g.,} through imputation); it is naturally considered a missing piece of the puzzle; \emph{we learn a problem-specific numerical representation for unknowns}. The key feature of PROMISSING is its simplicity; it is plug-and-play; it deals with missing values in the first layer of the network without the need to change anything in the rest of the network architecture or optimization process. PROMISSING in its original form does not add extra parameters to the network, and its computational overhead remains negligible. Our experiments on simulated data and several classification/regression problems show that the proposed pruning method does not negatively affect the model accuracy and provides competitive results compared to several data imputation techniques. In a clinical application, making prognostic predictions for patients with a psychotic disorder, we present an application of PROMISSING on a multi-modal clinical dataset. We demonstrate how the NN model trained using PROMISSING becomes indecisive when facing many unknowns. This is a crucial feature for developing trustworthy prediction models in clinical applications. Furthermore, we show a side application of PROMISSING for counterfactual interpretation~\citep{mothilal2020explaining} of NNs decisions that can be valuable in clinics.
\section{Methods}
\label{sec:methods}
Let $\displaystyle {\bm{x}} \in \mathbb{R}^{p}$ represent a vector of an input sample with $p$ features. We assume that the features in $\displaystyle {\bm{x}}$ are divided into two sets of $q$ observed $\displaystyle {\bm{x}}^o \in \mathbb{R}^q$ and $r$ missing features $\displaystyle {\bm{x}}^m$ (where $p=q+r$). In this study, we do not put any assumption on the pattern of missing values in $\displaystyle {\bm{x}}$. Then, the activation of the $k$th ($k \in \{1,2, \dots, s \}$) neuron in the first hidden layer of an ordinary NN is:
\begin{equation}
\label{eq:activation}
\displaystyle a^{(k)} = \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \sum_{x_j \in {\bm{x}}^m} x_j w^{(k)}_j + b^{(k)}.
\end{equation}
This activation cannot be computed unless the values in $\displaystyle {\bm{x}}^m$ are imputed with real numbers. Here, in PROMISSING, we propose to alternatively replace the missing values with a \emph{neutralizer} that 1) prunes the missing values from inputs of a neuron, 2) neutralizes the effect of missing values on the neuron's activation by cancelling the second term in Eq.~\ref{eq:activation} and modifying the neuron's bias. A missing value $x_j \in \displaystyle {\bm{x}}^m$ is replaced with its corresponding neutralizer $u_j^{(k)}$ at the $k$th neuron, where:
\begin{equation}
\label{eq:neuralizer}
\displaystyle u_j^{(k)} = \frac{-b^{(k)}}{pw^{(k)}_j}.
\end{equation}
The value of a neutralizer depends on its corresponding weight ($\displaystyle w^{(k)}_j$), the bias of the corresponding neuron ($\displaystyle b^{(k)}$), and the number of features ($p$); thus, it can be computed on the fly during the training or inference procedures. A small value is added to weights before computing neutralizers to avoid division by zero. Inserting the neutralizer into Eq.~\ref{eq:activation}, the activation of the $k$th neuron is rewritten as:
\begin{equation}
\label{eq:promissing_activation}
\displaystyle a^{(k)} = \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \frac{qb^{(k)}}{p},
\end{equation}
in which the effect of weights of missing values on the activation of the neuron is eliminated, and the neuron's bias is reduced by a factor of $r/p$. If all input values for a specific sample are missing then the neuron is completely neutralized.
\begin{theorem}
\label{prop:promissing1}
If all input values are missing ($q=0$ and $\displaystyle {\bm{x}}^o= \varnothing$) then the activation of a PROMISSING neuron is zero (see Appendix~\ref{subsubsec:prop1_proofs} for the proof).
\end{theorem}
\begin{theorem}
\label{prop:promissing2}
If there are no missing values in inputs ($q=p$ and $\displaystyle {\bm{x}}^m= \varnothing$) then the activation of a PROMISSING neuron is equal to a normal neuron (see Appendix~\ref{subsubsec:prop2_proofs} for the proof)..
\end{theorem}
We should emphasize that, when using PROMISSING, the user does not need to apply any change to the input vectors, and the missing values (generally represented as \texttt{nan}s in the input matrix) are fed directly to the network. After the training procedure, we eventually learn $\displaystyle {\bm{U}} \in \mathbb{R}^{s \times p}$, a matrix representation for unknowns (or metaphorically the dark matter):
\begin{equation}
\label{eq:unknown}
\displaystyle u_j^{*(k)} = \frac{-b^{*(k)}}{pw^{*(k)}_j} \quad \quad j \in \{1,2, \dots, p \}, \quad k \in \{1,2, \dots, s \},
\end{equation}
where $b^*$ and $w^*$ are representing the final learned bias and weight. At the prediction stage, a missing value at $j$th input feature will be replaced with its corresponding neutralizer from $\displaystyle {\bm{U}}$. It is worth emphasizing that the missing values are replaced with different neutralizers at different neurons; therefore, it cannot be considered a constant imputation. In fact, each neuron perceives differently a missing value in the input space. Metaphorically, the neurons can be seen as blind men in the parable of ``the blind men and an elephant"~\footnote{See \url{https://en.wikipedia.org/wiki/Blind_men_and_an_elephant} for the parable.} when facing unknowns. Furthermore, it is different from regression-based imputation and model-based approaches in the sense that a missing value in a specific feature is not inferred from other observed features, or the distribution of observed values; \textit{i.e.}, unknowns remain unknowns. In PROMISSING, we do not assume any certain missing value mechanism (\textit{e.g.}, MAR) in advance. Instead, we try to learn the patterns of missing values from data that maybe advantageous in more difficult scenarios such as MNAR (see results in Sec.~\ref{subsec:simulation}).
One possible drawback of using PROMISSING is in high-dimensional input spaces and when the number of missing values is large, \textit{i.e.}, when $p \to \infty$ and $r \gg q$. In this case, the neuron will undershoot; hence the effect of few non-missing values are ignored.~\footnote{Note that this again might be considered as an advantage in some applications.} To address this problem, we propose a \emph{modified} version of PROMISSING (mPROMISSING) in which the effect of large $r$ can be compensated with a \emph{compensatory} weight, $w_c$. The compensatory weight receives a fixed input of $r/p$ for a specific sample; thus, the activation of the neuron will change to:
\begin{equation}
\label{eq:mpromissing_activation}
\displaystyle a^{(k)} = \sum_{x_i \in {\bm{x}}^o} x_i w^{(k)}_i + \frac{qb^{(k)}+rw^{(k)}_c}{p}.
\end{equation}
$w^{(k)}_c$ is learned alongside the rest of the network parameters in the optimization process. On training data with few missing values, data augmentation (\textit{e.g.}, by simulating different patterns and size of missing values) is advisable to ensure the sensibility of the learned compensatory weight. Since the input for this weight ($r/p$) is computed at the run time, no modification to input vectors is required.
\begin{theorem}
\label{prop:promissing3}
If there are no missing values ($q=p$, $r=0$, and $\displaystyle {\bm{x}}^m= \varnothing$) then the activation of an mPROMISSING neuron is equal to a normal neuron (see Appendix~\ref{subsubsec:prop3_proofs} for the proof).
\end{theorem}
The proposed PROMISSING approach is straightforward to implement and use. It can be incorporated into the current implementations of different types of NN layers by adding/modifying few lines of code. We have implemented a \texttt{nanDense} layer, inheriting from Keras~\citep{chollet2015keras} \texttt{Dense} layer, using PROMISSING and mPROMISSING neurons (see appendix~\ref{subsec:nandense}). The \texttt{nanDense} layer can be directly imported and used with any Keras model. In its general usage, the \texttt{nanDense} layer is only used for the first layer of an NN to handle missing values in inputs, unless we expect some missing values in the intermediate layers. | {'timestamp': '2022-06-06T02:16:31', 'yymm': '2206', 'arxiv_id': '2206.01640', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01640'} | arxiv |
\section{Introduction}
People in the Information Age read reviews from online review websites
when making decisions to buy a product or use a service. The proliferation of such reviews has driven research on opinion mining \cite{hu2006opinion,pang2008opinion}, where the ultimate goal is to glean information from multiple reviews so that users can make decisions more effectively. Opinion mining has assumed several facets in its history: among others, there are sentiment analysis \cite{pang2002thumbs}, that reduces a single review into a sentiment label,
opinion extraction \cite{mukherjee-liu-2012-aspect}, that produces a list of aspect-sentiment pairs representing opinions mentioned in the reviews,
and most notably
\textit{opinion summarization} \cite{wang-ling-2016-neural}, which creates a textual summary of opinions that are found in multiple reviews about a certain product or service.
Opinion summarization is arguably the most effective solution for opinion mining, especially when assisting the user in making decisions. Specifically, textual opinion summaries provide users with information that is both more concise and more comprehensible compared to other alternatives. Thus, opinion mining research on the IR community
has geared its focus towards opinion summarization in recent years (see Table~\ref{tab:sols}).
The task of summarizing opinions in multiple reviews can be divided into two subtasks: opinion retrieval and summary generation. Opinion retrieval selects opinions from the reviews that are salient and thus need to be included in the summary.
Summary generation produces a textual summary given the retrieved opinions that is concise yet informative and comprehensible for users to read and make decisions effectively.
The summary can be generated from scratch with possibly novel tokens (i.e., \textit{abstractive} summarization; \cite{opinosis,meansum}) or spans of text directly extracted from the input (i.e., \textit{extractive} summarization; \cite{hu2004mining2,mate_mt}).
Traditionally, these subtasks correspond to a pipeline of natural language generation models \cite{mckeown1992text,carenini-etal-2006-multi,wang-ling-2016-neural} where opinion retrieval and summary generation are treated as content selection and surface realization tasks, respectively.
Thanks to advancements in neural networks, most of the recent methods use an end-to-end approach \cite{meansum,copycat,fewsum} where both opinion retrieval and summary generation are done by a single model optimized to produce well-formed and informative summaries.
There are two broad types of challenges in opinion summarization:
\textit{annotated data scarcity} and \textit{usability}. As reviews-summary pairs are expensive to create, this has resulted in annotated dataset scarcity. However, the exceptional performance of neural networks for text summarization is mostly driven by large-scale supervised training~\citep{rush2015neural,zhang2020pegasus}, which makes opinion summarization challenging. The second challenge -- usability -- stems from a number of practical requirements for industrial applications. First, for real-world products and service we often need to summarize many thousands of reviews. This is largely infeasible due to the high computational and memory costs of modelling that many reviews with neural architectures~\citep{Beltagy2020Longformer}. Second, state-of-the-art text summarizers are prone to hallucinations~\citep{maynez-etal-2020-faithfulness}. In other words, a summarizer might mistakenly generate a summary with information not covered by input reviews, thus misinforming the user. Third, generic summaries often cannot address specific user needs. This, in turn, calls for ways to learn summarizers producing personalized summaries.
\begin{comment}
\begin{figure}[t]
\centering
\includegraphics[width=0.9\linewidth]{stats.pdf}
\vspace{-0.2cm}
\caption{Increasing \# of papers for opinion summarization that are published in WSDM, CIKM, KDD, RecSys, ICML, WWW, and SIGIR from 2017 to 2021. \xiaolan{Can be removed.}}
\label{fig:stats}
\vspace{-0.2cm}
\end{figure}
\end{comment}
This opens exciting avenues to develop methods for solving these major challenges in opinion summarization. In this light, the aim of the tutorial is to inform interested researchers and practitioners, especially in opinion mining and text summarization, about recent and ongoing efforts to improve the state of the art and make opinion summarization systems useful in real-world scenarios. And the tutorial will make the audience well-equipped for addressing these challenges in terms of methods, ideas, and related work.
\section{Tutorial Content and Outline}
The tutorial will be 3 hours long and consist of the following
five parts, which we describe in detail below.
\subsection{Part I: Introduction [30 min]}
Opinion summarization~\cite{hu2006opinion, titov2008joint, kim2011comprehensive} focuses on summarizing opinionated text, such as customer reviews, and has been actively studied by researchers from the natural language processing and data mining community for decades. There are two major types of opinion summaries: non-textual summaries, such as aggregated ratings~\cite{lu2009rated}, aspect-sentiment tables~\cite{titov2008joint}, and opinion clusters~\cite{hu2004mining2}, and textual summaries, which often consist of a short text. Compared to non-textual summaries, which may confuse users due to their complex formats, textual summaries are considered much more user-friendly~\cite{murray2017opinion}. Thus, in recent years, the considerable research interest in opinion summarization has shifted towards textual opinion summaries. In this tutorial, we will also focus on recent solutions for generating textual opinion summaries.
Like single document summary \cite{rush2015neural,see2017get}, textual opinion summary can also be either extractive or abstractive. However, unlike single document summarization, opinion summarization can rarely rely on gold-standard summaries at training time due to the lack of large-scale training examples in the form of review-summary pairs. Meanwhile, the prohibitively many and redundant input reviews also pose new challenges for the task.
In this part of the tutorial, we will first describe the opinion summarization task, its history, and the major challenges that come with the task. We will then provide a brief overview of existing opinion summarization solutions.
\begin{table}[]
\small
\centering
\caption{Opinion summarization solutions that will be covered in this tutorial. A dagger $\dagger$ denotes that the solution also leverages weak supervision.}
\vspace{-2mm}
\begin{tabular}{@{~}p{8.3cm}@{~}}
\hline
\multicolumn{1}{c}{\textbf{Pre-Neural Solutions}} \\
\hline
\textbf{Extractive}:\\LexRank~\cite{lexrank}, TextRank~\cite{textrank},
MEAD~\cite{carenini-etal-2006-multi},
Wang et.al~\cite{wang-etal-2014-query} \\
\textbf{Abstractive}:\\Opinosis~\cite{opinosis},
SEA~\cite{carenini-etal-2006-multi},
Gerani et.al~\cite{gerani2014abstractive} \\
\hline
\multicolumn{1}{c}{\textbf{Autoencoders}} \\
\hline
\textbf{Extractive}: \\MATE+MT$^\dagger$~\cite{mate_mt},
Mukherjee et.al$^\dagger$~\cite{mukherjee2020read},
ASPMEM$^\dagger$~\cite{aspmem},
QT~\cite{qt} \\
\textbf{Abstractive}:\\MeanSum~\cite{meansum},
Coavoux et.al~\cite{coavoux2019unsupervised},
OpinionDigest$^\dagger$~\cite{opiniondigest},
RecurSum~\cite{recursum},
MultimodalSum~\cite{multimodalsum},
COOP~\cite{coop} \\
\hline
\multicolumn{1}{c}{\textbf{Synthetic Training}} \\
\hline
\textbf{Abstractive}:\\Copycat~\cite{copycat},
DenoiseSum~\cite{denoisesum},
MMDS~\cite{mmds},
Elsahar et.al$^\dagger$~\cite{elsahar2021self},
Jiang et.al~\cite{Jiang2021},
PlanSum~\cite{plansum},
TransSum~\cite{transsum},
AceSum~\cite{acesum}, ConsistSum~\cite{ke2022consistsum},
LSARS~\cite{pan2020large}\\
\hline
\multicolumn{1}{c}{\textbf{Low-Resource}} \\
\hline
\textbf{Abstractive}: \\
Wang et.al~\cite{wang-ling-2016-neural},
FewSum~\cite{fewsum},
AdaSum~\cite{brazinskas2022efficient},
PASS~\cite{pass},
SelSum~\cite{selsum},
CondaSum~\cite{condasum},
Wei et.al~\cite{Wei2021}\\
\hline
\end{tabular}
\label{tab:sols}
\vspace{-0.2cm}
\end{table}
\begin{comment}
\begin{table}[t]
\centering
\small
\begin{tabular}{c|c}
\toprule
\multirow{9}{*}{\begin{sideways}\textbf{Pre-Neural}\end{sideways}}
& \multicolumn{1}{c}{\textbf{Extractive}} \\[3pt]
& LexRank~\cite{lexrank} \\
& TextRank~\cite{textrank} \\
& MEAD~\cite{mead_sea}\\
& Wang et.al~\cite{wang-etal-2014-query} \\[3pt]
& \multicolumn{1}{c}{\textbf{Abstractive}} \\[3pt]
& Opinosis~\cite{opinosis}\\
& SEA~\cite{mead_sea}\\
& Gerani et.al~\cite{gerani2014abstractive} \\
\midrule
\multirow{13}{*}{\begin{sideways}\textbf{Autoencoders}\end{sideways}}
& \multicolumn{1}{c}{\textbf{Extractive}} \\[3pt]
& MATE+MT$^\dagger$~\cite{mate_mt} \\
& Mukherjee et.al$^\dagger$~\cite{mukherjee2020read} \\
& ASPMEM$^\dagger$~\cite{aspmem} \\
& QT~\cite{qt} \\[3pt]
& \multicolumn{1}{c}{\textbf{Abstractive}} \\[3pt]
& MeanSum~\cite{meansum}\\
& Coavoux et.al~\cite{coavoux2019unsupervised}\\
& OpinionDigest$^\dagger$~\cite{opiniondigest}\\
& RecurSum~\cite{recursum}\\
& MultimodalSum~\cite{multimodalsum}\\
& COOP~\cite{coop} \\
\midrule
\multirow{9}{*}{\begin{sideways}\textbf{Synthetic Training}\end{sideways}}
& \multicolumn{1}{c}{\textbf{Abstractive}} \\[3pt]
& CopyCat~\cite{copycat}\\
& DenoiseSum~\cite{denoisesum}\\
& MMDS~\cite{mmds}\\
& Elsahar et.al$^\dagger$~\cite{elsahar2021self}\\
& Jiang et.al~\cite{Jiang2021}\\
& PlanSum~\cite{plansum}\\
& TransSum~\cite{transsum}\\
& AceSum~\cite{acesum} \\
\midrule
\multirow{7}{*}{\begin{sideways}\textbf{Low-Resource}\end{sideways}}
& \multicolumn{1}{c}{\textbf{Abstractive}} \\[3pt]
& Wang et.al~\cite{wang-ling-2016-neural}\\
& FewSum~\cite{fewsum}\\
& PASS~\cite{pass} \\
& SelSum~\cite{selsum}\\
& CondaSum~\cite{condasum}\\
& Wei et.al~\cite{Wei2021}\\
\bottomrule
\end{tabular}
\caption{Opinion summarization solutions that will be covered in this tutorial. A dagger $\dagger$ denotes that the solution also leverages weak supervision.\todo{Format}}
\label{tab:sols}
\end{table}
\end{comment}
\begin{comment}
\begin{table*}[ht]
\centering
\small
\begin{tabular}{c|c|c}
\toprule
& \textbf{Extractive} & \textbf{Abstractive} \\\midrule
\textbf{Pre-neural} & \makecell{LexRank~\cite{lexrank} \\ TextRank~\cite{textrank} \\ MEAD~\cite{mead_sea}\\Wang et.al~\cite{wang-etal-2014-query}} &
\makecell{Opinosis~\cite{opinosis}\\SEA~\cite{mead_sea}\\Gerani et.al~\cite{gerani2014abstractive}}
\\\midrule\midrule
\makecell{\textbf{Autoencoders} \\(\S\ref{subsubsec:autoencoder})} & \makecell{MATE+MT$^\dagger$~\cite{mate_mt}\\ Mukherjee et.al$^\dagger$~\cite{mukherjee2020read} \\ ASPMEM$^\dagger$~\cite{aspmem}
\\QT~\cite{qt}} & \makecell{MeanSum~\cite{meansum}\\Coavoux et.al~\cite{coavoux2019unsupervised}\\
OpinionDigest$^\dagger$~\cite{opiniondigest}\\RecurSum~\cite{recursum}\\MultimodalSum~\cite{multimodalsum}\\COOP~\cite{coop}}\\\midrule
\makecell{\textbf{Synthetic Training} \\ (\S\ref{subsubsec:synthetic})} & & \makecell{
CopyCat~\cite{copycat}\\
DenoiseSum~\cite{denoisesum}\\
MMDS~\cite{mmds}\\
Elsahar et.al$^\dagger$~\cite{elsahar2021self}\\
Jiang et.al~\cite{Jiang2021}\\
PlanSum~\cite{plansum}\\
TransSum~\cite{transsum}\\
AceSum~\cite{acesum}
} \\\midrule
\makecell{\textbf{Low-resource Learning}
\\ (\S\ref{subsubsec:fewshot})} & & \makecell{
Wang et.al~\cite{wang-ling-2016-neural}\\
FewSum~\cite{fewsum}\\
PASS~\cite{pass} \\
SelSum~\cite{selsum}\\
CondaSum~\cite{condasum}\\
Wei et.al~\cite{Wei2021}
}\\
\bottomrule
\end{tabular}
\caption{Opinion summarization solutions that will be covered in this tutorial. A dagger $\dagger$ denotes that the solution also leverages weak supervision.}
\label{tab:sols}
\end{table*}
\end{comment}
\subsection{Part II: Solutions To Data Scarcity [90 min]}
In this part of the tutorial, we will present multiple existing opinion summarization models, as also summarized in Table~\ref{tab:sols}. These models attempt to solve the annotated data scarcity problem and are classified into four parts: pre-neural models, autoencoder-based models, models that use synthetic data, and models that leverage low-resource annotated data.
\subsubsection{Autoencoders [30/90 min]}\label{subsubsec:autoencoder}
Due to the lack of training examples, one major approach is to use autoencoders for unsupervised opinion summarization. The autoencoder model consists of an encoder that transforms the input into latent representations and a decoder that attempts to \textit{reconstruct} the original input using a reconstruction objective. It has a wide range of applications in both
CV and NLP communities~\cite{hinton2011transforming,Kingma2014AutoEncodingVB,bowman-etal-2016-generating}. Autoencoders can also help models obtain better text representations, which allows easier text clustering, aggregation, and selection. Thus, it benefits both extractive and abstractive solutions. In this tutorial, we will first introduce the basics of autoencoders and then describe how to use autoencoders for both extractive and abstractive opinion summarization.
\subsubsection{Synthetic Dataset Creation [30/90 min]}
\label{subsubsec:synthetic}
{The supervised training of high-capacity models on large datasets containing hundreds of thousands of document-summary pairs is critical to the recent success of deep learning techniques for abstractive summarization \citep{rush2015neural,see2017get}}.
The absence of human-written summaries in a large-scale calls for creative ways to synthesize datasets for {supervised training of abstractive summarization models}. Customer reviews, available in large quantities, can be used to create synthetic datasets for training. Such datasets are created by sampling one review as a pseudo-summary, and then selecting or generating a subset of reviews as input to be paired with the pseudo-summary. Subsequently, the summarizer is trained in a supervised manner to predict the pseudo-summary given the input reviews. This \textit{self-supervised} approach, as has been shown in a number of works [\citealp{zhang2020pegasus}, \textit{inter alia}], is effective for training summarizers to generate abstractive opinion summamaaries. In this tutorial, we will introduce various techniques to create synthetic datasets, contrast them, and present results achieved by different works.
\subsubsection{Low-Resource Learning [30/90 min]}\label{subsubsec:fewshot}
Modern deep learning methods rely on large amounts of annotated data for training. Unlike synthetic datasets, automatically created from customer reviews, annotated datasets require expensive human effort. Consequently, only datasets with a handful of human-written summaries are available, which lead to a number of few-shot models. These models alleviate annotated data-scarcity using specialized mechanisms, such as parameter subset fine-tuning and summary candidate ranking. An alternative to human-written are editor-written summaries that are scraped from the web and linked to customer reviews. This setup is challenging because each summary can have hundreds of associated reviews. In this tutorial, we will present both methods that are few-shot learners and that scale to hundreds of input reviews.
\vspace{-0.5mm}
\subsection{Part III: Improving Usability [30 min]}\label{subsubsec:advanced}
In order to make opinion summarizers more useful in industrial settings, a number of features need to be improved. In this part of the tutorial, we will discuss the following three major features and recent solutions the community has proposed:
\begin{itemize}[leftmargin=*]
\setlength\itemsep{1mm}
\item \textbf{Scalability: }
The ability to handle a massive number of input reviews. To handle large scale input, the ability to retrieve salient information, e.g., reviews or opinions, becomes a important yet challenging feature for opinion summarization solutions.
\item \textbf{Input Faithfulness: }
The ability of a summarizer to generate summaries covered in content by input reviews. In other words, the summarizer should not confuse entities or introduce novel content into summaries.
\item \textbf{Controllability: }
The ability to produce constrained summaries, such as a hotel summary that only includes room cleanliness or a product summary that only covers the negative opinions.
\end{itemize}
\subsection{Part IV: Evaluation and Resources [20 min]}
As is common in other areas of natural language processing, in opinion summarization, researchers often rely on automatic metrics. These metrics, such as ROUGE \cite{lin2004rouge}, are based on word overlaps with the reference summary. However, word overlap metrics are limited and can weakly correlate with human judgment.
To address these shortcomings, human evaluation is often used, where human annotators assess various aspects of generated summaries. In this tutorial, we will present different kinds of human evaluation experiments, how they are designed, and how they are performed.
\vspace{-1mm}
\subsection{Part V: Future Work [10 min]}
To conclude the tutorial, we will present several notable open questions for opinion summarization, such as the need for additional annotated resources, common issues with the generated summary (e.g., repetition, hallucination, coherency, and factuality), and the ability to handle various type of input data (e.g., images and knowledge bases). Based on these open questions, we will also present future work on opinion summarization.
\section{Objectives}
In this tutorial, we will cover a wide range of techniques from pre-neural approaches to the most recent advances for opinion summarization. In addition, we will also introduce the commonly used resources and evaluation metrics. Our goal for this tutorial is to increase the interest of the IR community towards the opinion summarization problem and help researchers to start working on relevant problems.
\section{Relevance to the IR community}
Sentiment analysis has been a major research area in the IR community. Since the tutorial will cover cutting-edge research in the field, it would attract a wide variety of IR researchers and practitioners.
We would also like to emphasize that the interest in opinion mining and summarization techniques in the IR community has been rapidly and significantly increased in recent years. To the best of our knowledge, we are the first ones to offer a tutorial covering the series of recent opinion summarization approaches.\footnote{More than 80\% of the papers were published within the last three years.}
\begin{figure}[t]
\centering
\includegraphics[width=0.85\linewidth]{stats.pdf}
\vspace{-0.2cm}
\caption{Increasing \# of papers for opinion summarization that are published in IR-related venues.}
\label{fig:stats}
\vspace{-0.2cm}
\end{figure}
\section{Broader Impact}
Methods presented in the tutorial also have applications beyond customer reviews. The amount of opinions on various topics expressed online is vast. These opinions address various sports, politics, and public events. In turn, this calls for ways to summarize this information for the benefit of the user. As we will discuss, the methods presented in the tutorial can be applied to other opinion domains, such as social media and blogs.
\iffalse
\section{Relevance to ACL}
The models we will discuss in this tutorial were originally developed for opinion summarization, but the techniques can be used for many other NLP tasks such as aspect-based sentiment analysis, opinion extraction, unsupervised text generation, multi-document, and long-form summarization.
The tutorial also covers open-ended problems and future directions that are also relevant in other tasks such as personalization, multimodality, and multilinguality, among others.
\section{Tutorial Type}
This is a \textbf{cutting-edge} tutorial that primarily covers recently published papers. More than 80\% of the papers were published within the last two years.
The techniques that will be discussed in the tutorial,
especially abstractive opinion summarization methods, are currently active and emerging research areas.
\section{Breadth}
At least $70\%$ of papers covered by the tutorial are not authored by the tutorial presentors.
\section{Prerequisites}
The tutorial is self-contained, which will cover essential background knowledge for each technique.
We assume that the audience has basic knowledge of Machine Learning and NLP. More advanced knowledge in Neural Networks such as encoder-decoder models, the attention mechanism, and pre-trained language models are preferred.
\section{Reading List}
Reading the following papers will be helpful for attendees but are not necessary:
\begin{itemize}
\setlength{\parskip}{0cm}
\setlength{\itemsep}{0cm}
\item Opinion Mining: \cite{liu2012sentiment}
\item Text summarization: \cite{rush2015neural}
\item Opinion Summarization: \cite{mate_mt, meansum}
\end{itemize}
\section{Target Audience}
\todo{Revise for IR community after meging with Relevance to ACL}
We believe that we are the first to offer a tutorial that covers the series of recent opinion summarization models.
Thus, we expect the tutorial to attract a wide variety of IR researchers and practitioners, especially in the areas of opinion mining and text summarization. We estimate that at least 100 people will attend the tutorial.
To the best of our knowledge, there is no tutorial that covers a similar set of recent works for opinion summarization.
\section{Open Access}
We will publicly share all the materials used during the tutorial, including presentation slides and software.
\fi
\section{Instructors}
\smallskip
\textit{Reinald Kim Amplayo} is a Research Scientist at Google. He received his PhD from the University of Edinburgh, where his thesis focused on controllable and personalizable opinion summarization. He is a recepient of a best student paper runner-up at ACML 2018.
\smallskip
\textit{Arthur Bra\v{z}inskas} is a Research Scientist at Google working on natural language generation for Google Assistant. His PhD on low- and high-resource opinion summarization is supervised by Ivan Titov and Mirella Lapata at the University of Edinburgh.
\smallskip
\textit{Yoshi Suhara} is an Applied Research Scientist at Grammarly. Previously, he was a Senior Research Scientist at Megagon Labs, an Adjunct Instructor at New College of Florida,
a Visiting Scientist at the MIT Media Lab, and a Research Scientist at NTT Laboratories. He received his PhD from Keio University in 2014. His expertise lies in NLP, especially Opinion Mining and Information Extraction.
\smallskip
\textit{Xiaolan Wang} is a Senior Research Scientist at Megagon Labs.
She received her PhD from University of Massachusetts Amherst in 2019. Her research interests include data integration, data cleaning, and natural language processing. She co-instructed the tutorial, \textit{Data Augmentation for ML-driven Data Preparation and Integration}, at VLDB 2021.
\smallskip
\textit{Bing Liu} is a Distinguished Professor of Computer Science at the University of Illinois at Chicago (UIC). He has published extensively in top conferences and journals. He also authored four books about lifelong learning, sentiment analysis and Web mining. Three of his papers received Test-of-Time awards: two from SIGKDD and one from WSDM. He has served as the Chair of ACM SIGKDD from 2013-2017, as program chair of many leading data mining conferences, including KDD, ICDM, CIKM, WSDM, SDM, and PAKDD, and as associate editor of leading journals such as TKDE, TWEB, DMKD and TKDD. He is a recipient of ACM SIGKDD Innovation Award, and he is a Fellow of the ACM, AAAI, and IEEE.
\bibliographystyle{ACM-Reference-Format}
| {'timestamp': '2022-06-06T02:13:13', 'yymm': '2206', 'arxiv_id': '2206.01543', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01543'} | arxiv |
\section{Appendix}
\subsection{Method to rescale estimated densities}
If we want our estimation to correspond to a proper probability density function, that is $\Integ{\ensuremath{\mathcal{Y}}}{}\,\pfhat{Y \pCond X = x}(y)dy \approx 1$, we can numerically estimate the integral using the trapezoidal rule on a grid of $m$ target values $\{y_i\}_{i = 1, \cdots, m}$ such that its values are evenly distributed between the quantiles $0.001$ and $0.999$ of $\pf{Y}$ (which we can always estimate through the marginal density estimator) and then rescale the predicted value, doing as follows: \\\\
\noindent
MCD.\textit{rescale}\,(pdf) \quad \begin{tabular}[http]{|l}
\begin{minipage}[t]{10cm}
$\bullet$ Generate a grid of $m$ target values $\{y_i\}_{i = 1, \cdots, m}$. \\
$\bullet$ Estimate $\{\pf{Y \pCond X = x}(y_i)\}_{i = 1, \cdots, m}$.\\
$\bullet$ Use the trapezoidal rule to estimate $\Integ{\ensuremath{\mathcal{Y}}}{}\,\pfhat{Y \pCond X = x}(y)dy$.\\
$\bullet$ Divide the predicted value by the estimation of $\Integ{\ensuremath{\mathcal{Y}}}{}\,\pfhat{Y \pCond X = x}(y)dy$.
\end{minipage}
\end{tabular}\\
.
\\\\
Note that this step must be repeated for each observation $x$ for which we want to estimate a conditional density function, but given a set observation $x$, we can reuse the computed integral for any number of target values. This technique will also be used for the other benchmarked methods which do not yield proper integrals by default.
\subsection{Python code for training set construction}
We provide extracts of the \textit{python}\, code used to construct $\mDwz{}$, the training set for the discriminator.
\lstinputlisting[language=Python, caption=Python code extract corresponding to Constructions 1 and 3.]{Code/generateWZiid.py}
\lstinputlisting[language=Python, caption=Python code extract corresponding to Constructions 2 and 4.]{Code/generateWZuid.py}
\lstinputlisting[language=Python, caption=Python code extract corresponding to Construction 5.]{Code/generateWZmts.py}
\subsection{Exhaustive experimental results}
In this section, we present the exhaustive results corresponding to Tables~\ref{table:features}, ~\ref{table:timing} and ~\ref{table:real}.
\begin{table}[http]
\centering
\tiny
\begin{tabular}{lccccccccccc}
Empirical \textbf{KL}\, & \rot{\textbf{MCD}\,:\textbf{MLP}\,} & \rot{\textbf{MCD}\,:\textbf{CatBoost}\,} & \rot{\textbf{NNKCDE}\,} & \rot{\textbf{MDN}\,} & \rot{\textbf{KMN}\,} & \rot{\textbf{N.Flow}\,} & \rot{\textbf{LSCond}\,} & \rot{\textbf{RFCDE}\,} & \rot{\textbf{FlexCode}\,:\textbf{MLP}\,} & \rot{\textbf{FlexCode}\,:\textbf{XGboost}\,} & \rot{\textbf{Deepcde}\,} \\
\hline
$\ensuremath{p} = 3$ & 0.008 & 0.009 & 0.022 & 0.109 & 0.067 & 0.189 & 0.342 & 0.037 & 0.094 & 0.093 & 0.152 \\
$\ensuremath{p} = 10$ & 0.036 & 0.042 & 0.063 & 0.229 & 0.096 & 0.228 & 0.61 & 0.105 & 0.106 & 0.076 & 0.205 \\
$\ensuremath{p} = 30$ & 0.115 & 0.202 & 0.154 & 0.396 & 0.181 & 0.432 & 0.369 & 0.238 & 0.22 & 0.196 & 0.385 \\
$\ensuremath{p} = 100$ & 0.162 & 0.224 & 0.173 & 0.45 & 0.401 & 0.411 & 1.059 & 0.238 & 0.234 & 0.264 & 0.36 \\
$\ensuremath{p} = 300$ & 0.244 & 0.308 & 0.282 & 0.506 & 0.304 & 0.67 & 0.783 & 0.507 & 0.253 & 0.302 & 0.306 \\
\hline
\end{tabular}
\caption{Evaluation of the \textbf{KL}\, divergence values for various feature sizes $\ensuremath{p}$, on the \textbf{BasicLinear}\, density model, with $\ensuremath{n}= 100$.}
\end{table}
\begin{table}[http]
\centering
\tiny
\begin{tabular}{lccccccccccc}
Time in sec. & \rot{\textbf{MCD}\,:\textbf{MLP}\,} & \rot{\textbf{MCD}\,:\textbf{CatBoost}\,} & \rot{\textbf{NNKCDE}\,} & \rot{\textbf{MDN}\,} & \rot{\textbf{KMN}\,} & \rot{\textbf{N.Flow}\,} & \rot{\textbf{LSCond}\,} & \rot{\textbf{RFCDE}\,} & \rot{\textbf{FlexCode}\,:\textbf{MLP}\,} & \rot{\textbf{FlexCode}\,:\textbf{XGboost}\,} & \rot{\textbf{Deepcde}\,} \\
\hline
$\ensuremath{n}=30$ & 3.133 & 0.46 & 0.01 & 35.46 & 47.92 & 50.74 & 12.01 & 0.044 & 0.018 & 9.574 & 1.943 \\
$\ensuremath{n}=100$ & 3.149 & 0.369 & 0.022 & 35.45 & 102.7 & 50.72 & 37.14 & 0.149 & 0.017 & 9.57 & 2.11 \\
$\ensuremath{n}=300$ & 3.132 & 0.446 & 0.04 & 35.65 & 150.6 & 50.62 & 100.5 & 0.448 & 0.017 & 13.19 & 3.225 \\
$\ensuremath{n}=1000$ & 3.296 & 0.689 & 0.043 & 35.73 & 143.6 & 51.12 & 167.9 & 0.952 & 0.02 & 25.24 & 6.388 \\
\hline
\end{tabular}
\caption{Training Time in seconds for various training set sizes $\ensuremath{n}$, on the \textbf{BasicLinear}\, density model.}
\end{table}
\begin{table}[http]
\centering
\tiny
\begin{tabular}{lcccccccccc}
Empirical \text{NLL}\, & \rot{\textbf{MCD}\,:\textbf{MLP}\,} & \rot{\textbf{CatBoost}\,} & \rot{\textbf{NNKCDE}\,} & \rot{\textbf{MDN}\,} & \rot{\textbf{KMN}\,} & \rot{\textbf{N.Flow}\,} & \rot{\textbf{LSCond}\,} & \rot{\textbf{FlexCode}\,:\textbf{MLP}\,} & \rot{\textbf{FlexCode}\,:\textbf{XGboost}\,} & \rot{\textbf{Deepcde}\,} \\
\hline
BostonHousing & -0.64 & -0.59 & -0.81 & -1.17 & -1.22 & -1.63 & -2.19 & -1.99 & -1.84 & -7.09 \\
Concrete & -0.86 & -1.02 & -1.23 & -2.02 & -2.30 & -2.13 & -4.00 & -2.26 & -1.25 & -10.1 \\
NCYTaxiDropoff:lon. & -1.30 & -1.28 & -1.68 & -2.51 & -2.51 & -2.85 & -3.90 & -2.05 & -2.17 & -11.2 \\
NCYTaxiDropoff:lat. & -1.31 & -1.31 & -1.44 & -2.51 & -2.45 & -2.96 & -4.72 & -1.67 & -6.18 & -9.35 \\
Power & -0.06 & -0.36 & -0.73 & -0.55 & -0.35 & -0.39 & -0.70 & -1.09 & -0.75 & -8.97 \\
Protein & -0.09 & -0.42 & -0.77 & -0.54 & -0.68 & -0.54 & -1.09 & -0.83 & -1.38 & -10.5 \\
WineRed & -0.89 & -0.89 & 3.486 & -1.27 & -0.90 & -2.43 & -6.25 & 1.062 & 0.965 & -10.1 \\
WineWhite & -1.18 & -1.13 & 2.99 & -2.24 & -1.7 & -4.18 & -5.41 & -0.73 & -0.63 & -13.2 \\
Yacht & 0.14 & 0.822 & -0.46 & 0.083 & 0.025 & 0.401 & -2.79 & -1.23 & 0.144 & -7.52 \\
teddy & -0.47 & -0.51 & -0.83 & -0.87 & -0.76 & -0.94 & -0.91 & -0.83 & -1.34 & -9.59 \\
toy dataset 1 & -0.99 & -0.47 & -0.63 & -0.40 & -0.35 & -0.71 & -0.70 & -0.88 & -1.46 & -6.10 \\
toy dataset 2 & -1.40 & -1.33 & -1.31 & -1.40 & -1.33 & -1.39 & -1.35 & -1.54 & -1.43 & -3.53 \\
\hline
\end{tabular}
\caption{Evaluation of the negative log-likelihood (\text{NLL}\,) for $12$ datasets.}
\end{table}
\section{Experiments}\label{Sec:experiments}
In this section we detail the implementation of \textbf{MCD}\,{} in section~\ref{sec:imple} and provide a benchmark to compare \textbf{MCD}\,{} to other available methods. All our experiments are done in \textit{python}\, and the random seed is always set such that the results of our method are fully reproducible. \\
We compare our method \textbf{MCD}\,{} with other well-known methods presented in section~\ref{sec:benchmarkMethod} on both density models including two new ones, described in section~\ref{sec:expdens} and real dataset. Our results are displayed in sections~\ref{sec:resultsExperiments} and~\ref{sec:realExperiments}.
\subsection{Method implementation}\label{sec:imple}
\paragraph{Training.} First describe the procedure used for both parametric and nonparametric estimation, to train our estimator \textbf{MCD}\, on dataset corresponding respectively to Framework ~\ref{DATA1}, ~\ref{DATA2} or ~\ref{DATA3}. Table~\ref{tab:lookup} details which Construction to use in each Framework.\\
\noindent
\textbf{Training} \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
$(\text{Step}_1).$ Set $\ratio$.\\
$(\text{Step}_2).$ Estimate $\pf{Y}$ using $\{Y_i\}_{i=1,\cdots,\ensuremath{n}}$ from $\ensuremath{\mathcal{D}^{X,Y}_n}$.\\
$(\text{Step}_3).$ Generate $\mDwz{\ensuremath{N}}$. \\
$(\text{Step}_4).$ Train either a regressor or a binary classifier on $\mDwz{\ensuremath{N}}$.
\end{minipage}
\end{tabular}
\\
The estimators obtained in steps 2 and 4 are called respectively the \textbf{marginal estimator} $\pfhat{Y}$ and the \textbf{discriminator} $\widetilde{q}$. Note that for any $(x,y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$, we have $\,\widetilde{q}(x,y)\in [0,1]$ while $q(x,y) \in [0,1)$. To obtain an appropriate prediction, we introduce a thresholding constant $\epsilon = 10^{-6}$ and set $$\widehat{q}(x,y) = \min(\widetilde{q}(x,y), 1 - \epsilon) \in [0,1 - \epsilon] \subset [0,1).$$
\begin{table}[http]\label{tab:lookup}
\centering
\begin{tabular}{|l|l|c|c|}
\hline
Framework & Available datasets & \ensuremath{i.i.d.}\,\,samples & \ensuremath{i.d.}\,\,samples \\
\hline
\hline
Framework~\ref{DATA1} & $\ensuremath{\mathcal{D}^{X,Y}_n}$ & Construction~\ref{const:DwzNiid} & Construction~\ref{const:DwzNid} \\
\hline
Framework~\ref{DATA2}& $\ensuremath{\mathcal{D}^{X,Y}_n}, \ensuremath{\mathcal{D}_{n_x}^{X}}, \ensuremath{\mathcal{D}_{n_y}^{Y}}$ & Construction~\ref{const:DwzNiidAD} & Construction~\ref{const:DwzNidAD} \\
\hline
Framework~\ref{DATA3} & $\ensuremath{\mathcal{D}_{n,m}^{X,\mathbb{Y}}}$ & Not applicable & Construction~\ref{const:DwzNidFram3} \\
\hline
\end{tabular}
\caption{Look-up table to determine the appropriate construction corresponding to each framework.}
\end{table}
Next, underline that \textbf{MCD}\,{} can be used to perform two different tasks:
\begin{itemize}
\item Nonparametric estimation of the conditional density
$\pf{Y \pCond X = x}(\cdot)$ for all $x \in \ensuremath{\mathcal{X}} $.
\item Pointwise estimation of the conditional density
$\pf{Y \pCond X = x}(y)$ for any $(x,y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$.
\end{itemize}
Indeed, using Fact~\ref{fac:MCF} we have: $\forall (x,y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$, \begin{equation}\label{eq:plugin}
\pfhat{Y \pCond X = x}(y) = \pfhat{Y}(y) \frac{\widehat{q}(x,y)}{1 - \widehat{q}(x,y)}\frac{1 - \ratio}{\ratio}.
\end{equation}
This implies that it is sufficient to have estimators of both $\pf{Y}$ and $q$ to have a point estimate of $\pf{Y\pCond X = x}(y)$. We may also deduce the literal expression of $\pfhat{Y \pCond X = x}(\cdot)$, the nonparametric estimate of the conditional density, provided we know the literal expressions of $\,\widehat{q}(x,\cdot)$ and $\pfhat{Y }(\cdot)$. It is the case for $\widehat{q}${} in Deep Learning, as we can write the literal expression of $\,\widehat{q}(x,\cdot)$ from the \textbf{NN}\, parameters learned in the learning step and a value $x$.
Under certain assumptions on $\widehat{q}$,\, $\pfhat{Y \pCond X = x}(\cdot)$ is a true density (\cite{gutmann_noise-contrastive_2010}). \\
\paragraph{Prediction.} For parametric pointwise estimation, at test time, given any new observation $x \in \ensuremath{\mathcal{X}}$, for any chosen target value $y \in \ensuremath{\mathcal{Y}}$, we can estimate $\pf{Y \pCond X = x}(y)$ the value of the probability density function evaluated on $(x,y)$:\\\\
\noindent
\textbf{Prediction} \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
$(\text{Step}_1).$ Evaluate $\widetilde{q}(x,y)$. \\
$(\text{Step}_2).$ Apply thresholding: $\widehat{q}(x,y) = \min(\widetilde{q}(x,y), 1 - \epsilon)$.\\%Note that in practice this should almost always be the case when using a neural network classifier with the sigmoid output activation function. \\
$(\text{Step}_3).$ Evaluate $\pfhat{Y}(y)$.\\
$(\text{Step}_4).$Plug in $\pf{Y \pCond X = x}(y)$ by applying equation~\ref{eq:plugin} given above.
\end{minipage}
\end{tabular}\\
\noindent Remark that if the discriminator is a classifier, the predicted value should be the probability of class 1, $i.e.$ $\ensuremath{\mathbb{P}}[Z = 1\pCond W = (x,y)]$.
\paragraph{Choice of parameters.} There are 4 major choices to make when implementing our method: the marginal density estimator method, the discriminator method, the construction and the contrast ratio $\ratio$.\\
\noindent$\bullet$ \textbf{Marginal density estimator.} Since the point of our method is to provide an estimation of the conditional density in cases where the marginal density is relatively easy to estimate (meaning $\ensuremath{\mathcal{Y}} \subseteq \ensuremath{\mathbbm{R}}$), we pick a simple yet effective technique, the univariate kernel density estimation \textit{KDEUnivariate} provided in the $statsmodels$ package. We always keep the default parameters, $i.e.$ gaussian kernels, bandwidth set using the normal reference, and the fast Fourier transform algorithm to fit the kernels.\\
\begin{table}[http!]\label{tab:methods}
\centering
\footnotesize
\begin{tabular}{|l|l|}
\hline
Neural Networks architectures & Other supervised learning classifiers \\
\hline
\hline
MultiLayerPerceptron (\textbf{MLP}\,) & Random Forests (\textbf{RF}\,) \\
\hline
\textbf{MLP}\, w/o Drop-Out nor Batch-Norm (\textbf{MLP}\,:\textbf{no-D.O.}) & Elastic-net \\
\hline
ResNet (\textbf{ResBlock}) \cite{gorishniy_revisiting_2021} & \textbf{XGboost}\, \cite{chen_xgboost_2016} \\
\hline
Gated Linear Unit (\textbf{GLU}) \cite{gorishniy_revisiting_2021} & \textbf{CatBoost}\, \cite{prokhorenkova_catboost_2018} \\
\hline
Self Normalizing Networks (\textbf{SNN}\,) & \textbf{LGBM}\, \cite{ke_lightgbm_2017}) \\
\cite{klambauer_self-normalizing_2017} & \\
\hline
\end{tabular}
\normalsize
\caption{List of discriminator methods evaluated with \textbf{MCD}\,.}
\label{table:classifiers}
\end{table}
\noindent$\bullet$ \textbf{Marginal contrast discriminator.}
We evaluate the performance of $\textbf{MCD}\,$ combined with Neural Networks, Decision Tree based classifiers and Logistic Elastic-net (see table~\ref{tab:methods} for the exhaustive list).
\noindent$\bullet$ \textbf{Dataset construction and ratio:}
We compare in our ablation study (Section~\ref{Sec:ablation}) the Constructions~\ref{const:DwzNiid}, \ref{const:DwzNid}, \ref{const:DwzNiidAD}, \ref{const:DwzNidAD} and \ref{const:DwzNidFram3} in Frameworks~\ref{DATA1}, ~\ref{DATA2} and ~\ref{DATA3}. Following the findings of the ablation study, we use Construction~\ref{const:DwzNid} and set $\ratio = 0.05$ in other experiments.
\subsection{Other benchmarked methods and Application Programming Interface (API)}
\label{sec:benchmarkMethod}
There is a small number of \textbf{CDE}\,{} methods for which a readily available open source implementation in \textit{python}\, exists. One notable difficulty when introducing a new \textbf{CDE}\,{} package is that there is no gold standard API in \textit{python}\, on top of which new packages can build upon. Most existing implementations are standalone, with their own unique syntax for common functions. We choose to include in our benchmark the methods provided by two of the most mature \textit{python}\, projects, the \textit{freelunchtheorem}\, \textit{github}\, repository by \cite{rothfuss_conditional_2019, noauthor_conditional_2022}, and a network of packages created by \cite{dalmasso_conditional_2020} and \cite{pospisil_cdetools_2022}.\\
\noindent The \textit{freelunchtheorem}\, \textit{github}\, provides an implementation of \textbf{KMN}\,, \textbf{N.Flow}\,, \textbf{MDN}\, and \textbf{LSCond}\,. The\textit{freelunchtheorem}\, \textit{github}\, has a quite consistent API across all provided methods. Notably, \cite{rothfuss_conditional_2019, noauthor_conditional_2022}, also provide implementations for several statistical models (\textbf{EconDensity}\,, \textbf{ARMAJump}\,, \textbf{JumpDiffusion}\,, \textbf{LinearGauss}\,, \textbf{LinearStudentT}\,, \textbf{SkewNormal}\, and \textbf{GaussianMixt}\,), which we include in our benchmark (see the density model section~\ref{sec:expdens}).\\
\noindent Meanwhile, the project of \cite{dalmasso_conditional_2020} and \cite{pospisil_cdetools_2022} is built around the \textit{CDEtools}\, \textit{github}\, repository and consists of several repository of varying maturity and ease of use corresponding to each method they implemented (\textbf{RFCDE}\,, f-$\textbf{RFCDE}\,$, $\textbf{FlexCode}\,$, \textbf{Deepcde}\, and \textbf{NNKCDE}\,). Notably, they also provide implementations in Java and R for some of these methods. Their implementation of \textbf{Deepcde}\, allows custom $pytorch$ and $tensorflow$ architectures to be plugged-in, which gave us the opportunity to adapt the architectures and training schemes used with \textbf{MCD}\, to \textbf{Deepcde}\,. As such, the comparison between \textbf{MCD}\, and \textbf{Deepcde}\, is done on equal ground.\\
\noindent In total, we include in our benchmark $10$ other \textbf{CDE}\, methods: \textbf{NNKCDE}\,, \textbf{N.Flow}\,, \textbf{LSCond}\,, \textbf{MDN}\,, \textbf{KMN}\,, \textbf{Deepcde}\,, \textbf{RFCDE}\,, \textbf{f}-\textbf{RFCDE}\,, \textbf{FlexCode}\,:\textbf{NN}\, and \textbf{FlexCode}\,:\textbf{XGboost}\,.\\
\noindent Although it is not the main goal of this work, we provide an overhead over these two projects and our method to facilitate the comparison between them. Each evaluated method is encapsulated in a class which inherits the same unique API from the parent class \textit{ConditionalEstimator}, with same input and output format and global behavior. Similar to \textit{scikit-learn}, the estimator is an instance of the class, with hyper-parameters provided during initialisation ($\_\_init\_\_)$, and the observation matrix and target vector provided (as $numpy$ arrays) when calling the $fit$ function. At predict time however, the estimator prediction is a function called \textit{pdf\_from\_X} which predicts the probability density function on a grid of target values. This package overhead allows us to compare all methods on equal ground: For density models all methods are trained on the same sampled training set. We also use the same grid of target values and test set of observations to evaluate the probability density function of all compared methods. Likewise, for real-world datasets, we use the same dataset train-test splits for all compared methods.\\
\subsection{Estimation of theoretical models}
\label{sec:expdens}
We first evaluate our method on the core task it aims to handle on theoretical models: numerically estimating a conditional density function with respect to a new observation. We choose to evaluate the quality of the prediction empirically: for each predicted and target functions, we evaluate for a grid of target values the \textbf{empirical Kullback-Leibler divergence} (\textbf{KL}\,)
\paragraph{Density models} The \textit{freelunchtheorem}\, package provides $7$ conditional densities implementations for which we have a function to generate a training dataset and a function to evaluate the theoretical density function on a grid of target values given an observation. These 7 models are \textbf{EconDensity}\,, \textbf{ARMAJump}\,, \textbf{JumpDiffusion}\,, \textbf{LinearGauss}\,, \textbf{LinearStudentT}\,, \textbf{SkewNormal}\, and \textbf{GaussianMixt}\,. We refer to the \textit{freelunchtheorem}\, \textit{github}\, documentation \cite{noauthor_conditional_2022} for a detailed description of each model. Although these conditional density models cover a diverse set of cases, we do however introduce two other density models to illustrate the specific drawbacks of some benchmarked methods.\\
\begin{mdframed}
\begin{mymodel}\label{Basic}[\textbf{BasicLinear}\,]:
Let $\ensuremath{p} = 10$ and fix $\ensuremath{p}$ coefficients $\beta = \{ \beta_j \}_{j = 1, \cdots, \ensuremath{p}}$ drawn independently at random, such that $\forall j = 1, \cdots, \ensuremath{p},$ $\beta_j$ is uniformly distributed over $(0,1)$, $i.e.$ $\beta_j \sim \pUU(0,1)$.\\
Construct now our first density model
\begin{itemize}
\item Let $X \sim \pNN(\ensuremath{\boldsymbol{0}}_\ensuremath{p}, \ensuremath{\mathbb{I}}_\ensuremath{p})$ be a gaussian vector.
\item Let $Y \in \ensuremath{\mathbbm{R}}$ be a random variable such that $Y = X^\top \beta + \sigma \epsilon$ where $\epsilon \sim \pNN(0,1)$ and $\epsilon$ and $X$ independent.
\end{itemize}
\end{mymodel}
\end{mdframed}
$\textbf{BasicLinear}\,$ is a very simple linear model included to check that sophisticated methods which can estimate complex models are not outperformed in simple cases. We also add a second model, $\textbf{AsymmetricLinear}\,$, which corresponds to $\textbf{BasicLinear}\,$ with a simple modification: we use asymmetric noise ($|\epsilon|$ instead of $\epsilon$).\\
\begin{mdframed}
\begin{mymodel}\label{Asym}[\textbf{AsymmetricLinear}\,]:
Let $\beta$, $X$ and $\epsilon$ be as in $\textbf{BasicLinear}\,$\ref{Basic}.
In our second density model, $Y$ is as follows:
$$
Y = X^{\top} \beta + \sigma |\epsilon|.
$$
Here, $|\cdot|$ denotes the absolute value.
\end{mymodel}
//
\end{mdframed}
The major difficulty is that the support of the conditional density of $Y$ with respect to $X$ differs from the support of the marginal density of $Y$ (which is $\ensuremath{\mathcal{Y}} = \ensuremath{\mathbbm{R}}$) and depends on the observation $X$.
\subsection{Results on density models}
\label{sec:resultsExperiments}
\paragraph{Evaluation protocol.}
We use $9$ density models (section~\ref{sec:expdens}) as ground truth, on which we evaluate the \textbf{MCD}\,{} with various discriminators and the methods presented in section~\ref{sec:benchmarkMethod}
To generate $\ensuremath{\mathcal{D}^{X,Y}_n}$ for each density model, we sample $\ensuremath{n} = 100$ observations and for each observation we sample one target value using the conditional law of the density model. We train all benchmarked methods on this same dataset. Next, we sample $n_{test} = 100$ observations from the density model to generate a test set. We also generate a unique grid of $10000$ target values, spread uniformly on $\ensuremath{\mathcal{Y}}$. For each observation of the test set, we evaluate the true conditional density function on the grid of target values. Then, for all benchmarked method, we estimate the conditional density for each observation on that same grid of target values and evaluate the empirical Kullback-Leibler (\textbf{KL}\,) divergence defined below.\\
\begin{mdframed}
\textbf{Empirical Kullback-Leibler divergence}.
\noindent\\ Set $\delta= 10^{-6}$ a numerical stability constant. Let $x \in \ensuremath{\mathbbm{R}}^{\ensuremath{p}}$ be an observation of the test set $\mathcal{D}_{\textit{test}}$ and $y\in \ensuremath{\mathbbm{R}}$ be a point on $\mathcal{G}$, a grid of target values to be estimated. Then, for the evaluation of the target value $f_{x}(y)= \max(\pf{Y \pCond X = x}(y),\delta)$ and the predicted value $g_{x}(y) = \max(\pfhat{Y \pCond X = {x}}(y),\delta)$, we define the empirical $\textbf{KL}\,_{\! \delta }$ divergence as follows:
\begin{equation}
\textbf{KL}\, := \textbf{KL}\,_{\! \delta }(f \,\|\, g)= \sum_{x\, \in\, \mathcal{D}_{\textit{test}}} \sum_{y\, \in \, \mathcal{G}} f_{x}(y) \times \ln\left( \frac{f_{x}(y)}{g_{x}(y)}\right).
\end{equation}
\end{mdframed}
\paragraph{Benchmark results.}
\noindent\\
\noindent \ding{226} We first combine the \textbf{MCD}\, method with a classic Multi Layer Perceptron (\textbf{MLP}\,) as discriminator and a kernel estimator as marginal density estimator, named \textbf{MCD}\,:\textbf{MLP}\,. Table~\ref{table:density} depicts the global performance in terms of empirical $\textbf{KL}\,$ divergence
over 9 models of \textbf{MCD}\,:\textbf{MLP}\, compared to 10 others methods, described in section~\ref{sec:benchmarkMethod}.
\begin{itemize}
\item The main take away is that in $6$ out of $9$ cases, \textbf{MCD}\,:\textbf{MLP}\, outperforms all others.
\item On $3$ density models, \textbf{BasicLinear}\,, \textbf{LinearGauss}\, and \textbf{LinearStudentT}\,, the \textbf{KL}\, empirical divergence is less than half of the second best method. Meanwhile, on \textbf{EconDensity}\,, \textbf{N.Flow}\, and \textbf{MCD}\,:\textbf{MLP}\, share the first place.
\item When \textbf{MCD}\,:\textbf{MLP}\, is outperformed, which corresponds to \textbf{JumpDiffusion}\, and \textbf{SkewNormal}\,, the best performing methods are \textbf{N.Flow}\, and \textbf{MDN}\,. Otherwise, the second best performing method is either \textbf{N.Flow}\, or \textbf{NNKCDE}\,.
\end{itemize}
\begin{table}[http]
\scriptsize
\begin{tabular}{l c c c c c c c c c c c}
Empirical \textbf{KL}\, & \rot{\textbf{MCD}\,:\textbf{MLP}\,} & \rot{\textbf{NNKCDE}\,} & \rot{\textbf{N.Flow}\,} & \rot{\textbf{LSCond}\,}& \rot{\textbf{MDN}\,} & \rot{\textbf{KMN}\,} & \rot{\textbf{Deepcde}\,} & \rot{\textbf{RFCDE}\,} & \rot{f-\textbf{RFCDE}\,} & \rot{\textbf{FlexCode}\,:\textbf{NN}\,}&\rot{\textbf{FlexCode}\,:\textbf{XGboost}\,} \\
\hline
\vspace{-0.25cm}
& & & & & & & & & & & \\
\textbf{ARMAJump}\, & 0.573 & 0.929 & \textbf{0.196} & 0.408 & \underline{0.29} & 0.312 & 1.754 & 0.529 & 0.526 & 1.201 & 2.226 \\
\textbf{AsymmetricLinear}\, & \textbf{0.158} & \underline{0.245} & 0.498 & 0.882 & 0.437 & 0.338 & 0.666 & 0.324 & 0.328 & 0.359 & 0.483 \\
\textbf{BasicLinear}\, & \textbf{0.009} & \underline{0.087} & 0.313 & 0.473 & 0.195 & 0.167 & 0.317 & 0.139 & 0.139 & 0.174 & 0.116 \\
\textbf{EconDensity}\, & \textbf{0.006} & 0.01 & \textbf{0.006} & 0.021 & \underline{0.013} & 0.022 & 0.068 & 0.049 & 0.045 & 0.034 & 0.048 \\
\textbf{GaussianMixt}\, & \textbf{0.005} & \underline{0.008} & 0.012 & 0.023 & 0.016 & 0.018 & 0.127 & 0.026 & 0.028 & 0.048 & 0.023 \\
\textbf{JumpDiffusion}\, & \textbf{1.352} & \underline{1.632} & 4.481 & 9.371 & 4.576 & 5.568 & 22.45 & 10.45 & 10.45 & 6.347 & 4.363 \\
\textbf{LinearGauss}\, & \textbf{0.189} & 1.742 & \underline{0.868} & 3.15 & 2.318 & 2.892 & 14.71 & 15.88 & 15.88 & 13.75 & 3.571 \\
\textbf{LinearStudentT}\, & \textbf{0.141} & \underline{0.301} & 6.238 & 9.09 & 3.109 & 3.136 & 7.583 & 2.363 & 2.363 & 1.686 & 0.821 \\
\textbf{SkewNormal}\, & 0.722 & 0.089 & \underline{0.019} & 0.1 & \textbf{0.014} & 0.036 & 18.94 & 0.551 & 0.551 & 0.636 & 2.255 \\
\hline
\end{tabular}
\caption{Evaluation of the empirical \textbf{KL}\, divergence of different \textbf{CDE}\, methods, for $9$ density models with $\ensuremath{n}=100$. \textbf{Best performance} is in bold print, \underline{second best performance} is underlined. Lower values are better. Column $2$ corresponds to the performance of $\textbf{MCD}\,$ combined with the classic \textbf{MLP}\,. Columns $3$ to $12$ show the results of the $10$ other benchmarked methods.}
\label{table:density}
\end{table}
\noindent \ding{226} We also assess the performance of \textbf{MCD}\, combined with other popular supervised learning methods. Table~\ref{table:discriminator} depicts the performance of \textbf{MCD}\, with various discriminators on the same benchmark of density models. The classifiers included are listed in Table~\ref{table:classifiers} and described in section~\ref{sec:imple}.
\begin{itemize}
\item In density model \textbf{ARMAJump}\, where \textbf{MCD}\,:\textbf{MLP}\, is outperformed by other methods, simply removing the Batch-Normalization and Drop-Out is sufficient to obtain the best performance.
\item In density models \textbf{BasicLinear}\,, \textbf{EconDensity}\,, \textbf{GaussianMixt}\,, \textbf{JumpDiffusion}\,, \textbf{LinearGauss}\, and \textbf{LinearStudentT}\,, the results for \textbf{MCD}\,:\textbf{MLP}\, are very close to other \textbf{NN}\, architectures performances. This means that in most cases, \textbf{MCD}\, does not require heavy tuning to perform well.
\item The best discriminator besides \textbf{NN}\, is always either \textbf{CatBoost}\, or \textbf{E.Net}\,.
\item \textbf{NN}\, discriminators are outperformed by other classifiers in only one case, the \textbf{SkewNormal}\, density model. This corresponds to the density model included in our benchmark where all versions of \textbf{MCD}\, are outperformed by another method.
\end{itemize}
\begin{table}[http]
\scriptsize
\begin{tabular}{l c c c c c c c c c c c}
Empirical \textbf{KL}\, & \rot{\textbf{MLP}\,} & \rot{\textbf{SNN}\,} & \rot{\textbf{GLU}} & \rot{\textbf{ResBlock}} & \rot{\textbf{no-D.O.}} & \rot{\textbf{CatBoost}\,} & \rot{\textbf{E.Net}\,} & \rot{\textbf{XGboost}\,} & \rot{\textbf{LGBM}\,} & \rot{\textbf{RF}\,} & \rot{\textbf{XRF}\,} \\
\hline
\vspace{-0.25cm}
& & & & & & & & & & & \\
\textbf{ARMAJump}\, & 0.573 & 1.047 & 0.731 & \underline{0.224} & \textbf{0.1} & 0.241 & 1.09 & 0.598 & 0.953 & 2.265 & 4.469 \\
\textbf{AsymmetricLinear}\, & 0.158 & \textbf{0.05} & 0\textbf{0.05} & \underline{0.055} & 0.318 & 0.2 & 0.262 & 0.274 & 0.28 & 0.279 & 0.319 \\
\textbf{BasicLinear}\, & \underline{0.009} & \textbf{0.008} & 0.01 & \underline{0.009} & 0.108 & 0.059 & 0.083 & 0.113 & 0.098 & 0.094 & 0.106 \\
\textbf{EconDensity}\, & \underline{0.006} & 0.007 & \textbf{0.005} & \textbf{0.005} & \underline{0.006} & 0.012 & 0.016 & 0.06 & 0.07 & 0.305 & 0.444 \\
\textbf{GaussianMixt}\, & \textbf{0.005} & \underline{0.006} & \underline{0.006} & \textbf{0.005} & 0.007 & 0.01 & 0.007 & 0.057 & 0.061 & 0.297 & 0.422 \\
\textbf{JumpDiffusion}\, & \textbf{1.352} & \underline{1.353} & \textbf{1.352} & \textbf{1.352} & \textbf{1.352} & 1.485 & \textbf{1.352} & 5.694 & 5.11 & 10.17 & 19.99 \\
\textbf{LinearGauss}\, & \textbf{0.189} & \textbf{0.189} & \underline{0.19} & \underline{0.19} & \underline{0.19} & 1.274 & \underline{0.19} & 9.33 & 10.99 & 67.46 & 94.76 \\
\textbf{LinearStudentT}\, & \textbf{0.141} & \textbf{0.141} & \textbf{0.141} & \textbf{0.141} & \textbf{0.141} & \underline{0.236} & \textbf{0.141} & 1.58 & 1.027 & 0.912 & 1.617 \\
\textbf{SkewNormal}\, & 0.722 & 0.796 & 0.669 & 0.356 & 0.155 & \textbf{0.083} & 0.833 & 0.223 & \underline{0.12} & 5.036 & 7.289 \\
\hline
\end{tabular}
\caption{Evaluation of the empirical \textbf{KL}\, divergence of different \textbf{MCD}\,{} discriminators, for $9$ density models with $\ensuremath{n}=100$. \textbf{Best performance} is in bold print, \underline{second best performance} is underlined. Lower values are better. Columns $2$ to $6$ correspond to the performance of $\textbf{MCD}\,$ combined with \textbf{NN}\, architectures. Columns $7$ to $12$ show the results of $\textbf{MCD}\,$ combined with other popular classifiers.}
\label{table:discriminator}
\end{table}
\paragraph{Impact of dimensionality.}
\noindent\\
\noindent \ding{226} Then, we check if in cases where \textbf{MCD}\, outperforms all others, our method maintains its good performances when $\ensuremath{p}$, the number of features, changes. Table~\ref{table:features} depicts the impact of the dimensionality of $X$ on the performances of each method in \textbf{BasicLinear}\,, the density model where the performance gap in our benchmark between \textbf{MCD}\, and other methods is the largest.
\begin{itemize}
\item Performances decrease across the board when $\ensuremath{p}$ increases. Although \textbf{BasicLinear}\, is a setting where a larger $\ensuremath{p}$ corresponds to a higher signal to noise ratio, this is not enough to counter the curse of dimensionality.
\item \textbf{MCD}\,:\textbf{MLP}\, outperforms all others at all ranges of $\ensuremath{p}$. Note that at $\ensuremath{p} = 300$, the empirical \textbf{KL}\, of \textbf{MCD}\,:\textbf{MLP}\, is equivalent to that of $\pf{Y}$, the marginal density of the target value. This means that in this high-dimensional case, where \textbf{MCD}\,:\textbf{MLP}\, is not able to capture the link between $X$ and $Y$, it does not overfit the training set, and instead takes a conservative approach.
\item \textbf{NNKCDE}\, maintains good results across the board. Meanwhile, \textbf{MCD}\, combined with \textbf{CatBoost}\, performs almost as well as \textbf{MCD}\,:\textbf{MLP}\, when $\ensuremath{p} = 3$, but its relative performances are average at best when $\ensuremath{p} = 300$.
\end{itemize}
\begin{table}[http]
\centering
\scriptsize
\begin{tabular}{|c||c|c|c|c|c|c|c|}
\hline
\vspace{-0.24cm}
& & & & & & & \\
\multirow{2}{*}{Empirical \textbf{KL}\,}& \textbf{MCD}\, & \textbf{MCD}\, & \multirow{2}{*}{\textbf{NNKCDE}\,} & \textbf{FlexCode}\, & \multirow{2}{*}{\textbf{KMN}\,} & \multirow{2}{*}{\textbf{RFCDE}\,} & \textbf{FlexCode}\, \\
& \textbf{MLP}\, & \textbf{CatBoost}\, & & \textbf{XGboost}\, & & & \textbf{NN}\, \\
\hline
\hline
\vspace{-0.24cm}
& & & & & & & \\
$\ensuremath{p} = \,\,\,\,3$ & \textbf{0.008} & \underline{0.009} & *0.022* & 0.093 & 0.067 & 0.037 & 0.094 \\
$\ensuremath{p} = \,\,10$ & \textbf{0.036} & \underline{0.042} & *0.063* & 0.076 & 0.096 & 0.105 & 0.106 \\
$\ensuremath{p} = \,\,30$ & \textbf{0.115} & 0.202 & \underline{0.154} & 0.196 & *0.181* & 0.238 & 0.22 \\
$\ensuremath{p} = 100$ & \textbf{0.162} & *0.224* & \underline{0.173} & 0.264 & 0.401 & 0.238 & 0.234 \\
$\ensuremath{p} = 300$ & \textbf{0.244} & 0.308 & *0.282* & 0.302 & 0.304 & 0.507 & \underline{0.253} \\
\hline
\end{tabular}
\caption{ Evaluation of the \textbf{KL}\, divergence values for various feature sizes $\ensuremath{p}$, on the \textbf{BasicLinear}\, density model, with $\ensuremath{n}= 100$. \textbf{Best} performance is in bold print, \underline{second best} performance is underlined, *third best* performance is between asterisks. Lower is better. Methods depicted achieve top 4 performances for at least one feature size regime.}
\label{table:features}
\end{table}
\paragraph{Execution time and scalability.}
\noindent\\
\noindent \ding{226}
Next, we evaluate the scability with respect to the size of the dataset of \textbf{MCD}\, combined with either \textbf{MLP}\, or \textbf{CatBoost}\,, two classifiers known to be efficient but slow. We include as reference other methods belonging to the same categories, meaning those based on supervised learning \textbf{NN}\, and Decision Trees respectively. We also include \textbf{NNKCDE}\, and the methods based on variational inference, as they perform well in our benchmark. Table~\ref{table:timing} depicts the computation time of \textbf{MCD}\, and other \textbf{CDE}\, methods for $\ensuremath{n}=30,100,300$ and $1000$, on \textbf{BasicLinear}\,, the density model where it is most beneficial to use \textbf{MCD}\, instead of another method. The reported computation times include all steps (initialization, training, prediction). For \textbf{MCD}\,, this includes both the time taken by the discriminator and the time taken by the estimator. Note also that for \textbf{MCD}\,, we use the ratio $\ratio= 0.05$, meaning the actual training set size is $20$ times larger.
\begin{itemize}
\item The main take away is that \textbf{MCD}\, mostly scales like its discriminator would in a supervised learning setting.
\item Regarding methods based on supervised learning with neural networks, we compare \textbf{MCD}\,:\textbf{MLP}\, with \textbf{FlexCode}\,:\textbf{NN}\, and \textbf{Deepcde}\,. \textbf{FlexCode}\,:\textbf{NN}\, is much faster than \textbf{Deepcde}\, and \textbf{MCD}\,:\textbf{MLP}\,. When using equivalent architectures, \textbf{Deepcde}\, is slower than \textbf{MCD}\, when $\ensuremath{n} = 1000$ (which corresponds to $\ensuremath{N} = \frac{\ensuremath{n}}{\ratio} = 20000$ for \textbf{MCD}\,). This can be partly explained by the fact that \textbf{Deepcde}\, uses a transformation of the target which corresponds to an output layer width of $30$, while $\textbf{MCD}\,$ increases the input size of the network by $1$, since observations and target values are concatenated.
\item Regarding methods based on supervised learning with decision trees, we compare \textbf{MCD}\,:\textbf{CatBoost}\, with \textbf{RFCDE}\, and \textbf{FlexCode}\,:\textbf{XGboost}\,. \textbf{RFCDE}\, is the only method which does not leverage $GPU$ acceleration, yet, it is faster than \textbf{MCD}\,:\textbf{CatBoost}\, and \textbf{FlexCode}\,:\textbf{XGboost}\,.
\item Among the best performing methods in our benchmark, \textbf{NNKCDE}\, is by far the fastest. Meanwhile, the $3$ variational inference methods included, \textbf{MDN}\,, \textbf{KMN}\, and \textbf{N.Flow}\,, are much slower, which is to be expected.
\end{itemize}
\begin{table}[http]
\centering
\tin
\begin{tabular}{|c||c|c|c||c|c|c||c||c|c|c|}
\hline
Category&\multicolumn{3}{|c||}{Decision Tree Based Methods}&\multicolumn{3}{|c||}{\textbf{NN}\, based Methods}& Kernel & \multicolumn{3}{|c|}{Variational inference}\\
\hline
\vspace{-0.22cm}
& & & & & & & & & \\
Method & \textbf{RFCDE}\, & \textbf{MCD}\, & \textbf{FlexCode}\, & \textbf{FlexCode}\, & \textbf{MCD}\, & \textbf{Deepcde}\, & \textbf{NNKCDE}\, & \textbf{MDN}\, & \textbf{N.Flow}\, & \textbf{KMN}\, \\
\hline
\vspace{-0.22cm}
& & & & & & & & & \\
Based on: & \textbf{RF}\, & \textbf{CatBoost}\, & \textbf{XGboost}\, & \textbf{NN}\, & \textbf{MLP}\, & \textbf{MLP}\, & N.Neighbor & \textbf{NN}\, & \textbf{NN}\, & \textbf{NN}\, \\
\hline
\hline
$\ensuremath{n} = \,\,\,\,30$ & 0.044 & 0.46 & 9.574 & 0.018 & 3.133 & 1.943 & 0.01 & 35.46 & 50.74 & 47.92 \\
$\ensuremath{n} = \,\,100$ & 0.149 & 0.369 & 9.57 & 0.017 & 3.149 & 2.11 & 0.022 & 35.45 & 50.72 & 102.7 \\
$\ensuremath{n} = \,\,300$ & 0.448 & 0.446 & 13.19 & 0.017 & 3.132 & 3.225 & 0.04 & 35.65 & 50.62 & 150.6 \\
$\ensuremath{n} = 1000$ & 0.952 & 0.689 & 25.24 & 0.02 & 3.296 & 6.388 & 0.043 & 35.73 & 51.12 & 143.6 \\
\hline
\end{tabular}
\caption{Training Time in seconds for various training set sizes $\ensuremath{n}$, on the \textbf{BasicLinear}\, density model. Row $1$ corresponds to the method category, row $2$ corresponds to the benchmarked \textbf{CDE}\, method and row $3$ corresponds to the underlying supervised learning method used. Column $1$ corresponds to the training set size. Columns $2$, $3$ and $4$ correspond to methods which leverage a supervised learning method based on Decision trees. Columns $5$, $6$ and $7$ correspond to methods which leverage a supervised learning method based on \textbf{NN}\,. Column $8$ corresponds to nearest neighbors kernels. Columns $9$, $10$ and $11$ correspond to three variational inference methods.}
\label{table:timing}
\end{table}
\subsection{Real-world datasets}
\label{sec:realExperiments}
\paragraph{Dataset origins and methodology.}
\noindent\\
\noindent \ding{226} We include in our benchmark $12$ datasets, taken from two sources:
\begin{itemize}
\item The \textit{CDEtools}\,{} framework provides the dataset "Teddy" (see \cite{beck_realistic_2017} for a description). We follow the pre-processing used in the given packages.
\item The \textit{freelunchtheorem}\,{} framework provides $2$ toy datasets, $7$ datasets from the UCI (\cite{asuncion_uci_2007} repository, and one dataset from the kaggle plateform \cite{noauthor_kaggle_nodate} which includes $2$ targets, for a total of $11$ datasets. Here again, we follow the pre-processing used in the given package.
\end{itemize}
\paragraph{Evaluation protocol.}
\noindent\\
\noindent \ding{226}
For all datasets, we standardize the observations and target values, then we perform the same train-test split for all methods benchmarked (manually setting the random seed for reproductibility). Because datasets are of varying sizes and as some methods are extremely slow for large datasets, we only take a subset of observations to include in the training set, doing the split as such. Let $n_{\max}$ be the original size of the dataset, the trainset is of size $\ensuremath{n} = \min(300,\ArrB{\ensuremath{n}_{\max} \times 0.8})$ and the test set is of size $n_{test} = \min(300,n_{\max}-\ensuremath{n})$.\\
\noindent One challenge when benchmarking \textbf{CDE}\, methods is that real-world datasets almost never provide the conditional density function associated to an observation, but instead only one realisation. This means that the usual metrics for \textbf{CDE}\, (eg.: \textbf{KL}\,) cannot be evaluated on these datasets. We nonetheless evaluate our method on real-world datasets, using the negative log-likelihood metric, denoted \text{NLL}\,, to compare the estimated probability density function against the target value.
\begin{mdframed}
\textbf{Empirical Negative Log-likelihood}.
\noindent\\
Set $\delta= 10^{-6}$ a numerical stability constant. Let $(x,y) \in \ensuremath{\mathbbm{R}}^{\ensuremath{p}}\times\ensuremath{\mathbbm{R}} $ be a sample from the test set $\mathcal{D}_{\textit{test}}$, and $g_{x}(y) = \max(\pfhat{Y \pCond X = {x}}(y),\delta)$ be the predicted value, we define the \text{NLL}\, metric as follows:
\begin{equation}
\text{NLL}\, := \text{NLL}\,_{\! \delta }(g)= - \!\!\!\!\sum_{(x,y)\, \in\, \mathcal{D}_{\textit{test}}} \! \ln\left( g_{x}(y)\right).
\end{equation}
\end{mdframed}
\paragraph{Results.}
\noindent\\
\noindent \ding{226} Table~\ref{table:real} depicts the global performance in terms of negative log-likelihood for the $12$ datasets.
\begin{itemize}
\item The main take away is that this time, \textbf{MCD}\,:\textbf{MLP}\, outperforms existing methods in $7$ out of $12$ cases, including the popular datasets BostonHousing and Concrete.
\item On the WineRed and WineWhite datasets, \textbf{MCD}\, lags far behind \textbf{NNKCDE}\, and \textbf{FlexCode}\,. One possible cause is that for these two datasets, the target variable $Y$ takes discrete values: $\ensuremath{\mathcal{Y}} = \{3,4,5,6,7,8\}$, which does not correspond to the regression task for which \textbf{MCD}\, was designed.
\item Besides \textbf{MCD}\,, the top performing methods are \textbf{NNKCDE}\,, \textbf{N.Flow}\,, \textbf{FlexCode}\, (both versions) and \textbf{KMN}\,.
\item Regarding the choice of the discriminator, \textbf{MCD}\,:\textbf{MLP}\, is not outperforming \textbf{MCD}\,:\textbf{CatBoost}\, to the same extent it does on density models. The difference in negative log-likelihood between \textbf{MCD}\,:\textbf{MLP}\, and \textbf{MCD}\,:\textbf{CatBoost}\, is below $0.1$ in $7$ out of $12$ cases.
\item Besides, \textbf{MCD}\,:\textbf{CatBoost}\,{} obtains Top~ 2 performances in $3$ of the $5$ cases where \textbf{MCD}\,:\textbf{MLP}\,{} is outperformed by other methods. Notably, on the Yacht dataset where \textbf{MCD}\,:\textbf{MLP}\,{} performs poorly, \textbf{MCD}\,:\textbf{CatBoost}\,{} outperforms all others by a wide margin. This indicates that this time, \textbf{MLP}\,{} and \textbf{CatBoost}\,{} are complementary, as together they can obtain at least Top~ 2 performances in all cases besides the WineRed and WineWhite datasets.
\end{itemize}
\begin{table}[http]
\centering
\scriptsize
\begin{tabular}{|l||c|c|c|c|c|c|c|}
\hline
\vspace{-0.22cm}
& & & & & & & \\
\multirow{2}{*}{Empirical \text{NLL}\,} & \textbf{MCD}\, & \textbf{MCD}\,& \multirow{2}{*}{\textbf{NNKCDE}\,} & \textbf{FlexCode}\, & \textbf{FlexCode}\, & \multirow{2}{*}{\textbf{KMN}\,} & \multirow{2}{*}{\textbf{N.Flow}\,} \\
& \textbf{MLP}\, & \textbf{CatBoost}\, & & \textbf{NN}\, & \textbf{XGboost}\, & & \\
\hline
\hline
\vspace{-0.22cm}
& & & & & & & \\
BostonHousing & \underline{-0.64} & \textbf{-0.59} & -0.81 & -1.99 & -1.84 & -1.22 & -1.63 \\
Concrete & \textbf{-0.86} & \underline{-1.02} & -1.23 & -2.26 & -1.25 & -2.30 & -2.13 \\
NCYTaxiDropoff:lon. & \underline{-1.30} & \textbf{-1.28} & -1.68 & -2.05 & -2.17 & -2.51 & -2.85 \\
NCYTaxiDropoff:lat. & \textbf{-1.31} & \textbf{-1.31} & \underline{-1.44} & -1.67 & -6.18 & -2.45 & -2.96 \\
Power & \textbf{-0.06} & -0.36 & -0.73 & -1.09 & -0.75 & \underline{-0.35} & -0.39 \\
Protein & \textbf{-0.09} & \underline{-0.42} & -0.77 & -0.83 & -1.38 & -0.68 & -0.54 \\
WineRed & -0.89 & -0.89 & \textbf{3.486} & \underline{1.062} & 0.965 & -0.90 & -2.43 \\
WineWhite & -1.18 & -1.13 & \textbf{2.99} & -0.73 & \underline{-0.63} & -1.7 & -4.18 \\
Yacht & 0.14 & \textbf{0.822} & -0.46 & -1.23 & 0.144 & 0.025 & \underline{0.401} \\
teddy & \textbf{-0.47} & \underline{-0.51} & -0.83 & -0.83 & -1.34 & -0.76 & -0.94 \\
toy dataset 1 & -0.99 & \underline{-0.47} & -0.63 & -0.88 & -1.46 & \textbf{-0.35} & -0.71 \\
toy dataset 2 & -1.40 & \underline{-1.33} & \textbf{-1.31} & -1.54 & -1.43 & \underline{-1.33} & -1.39 \\
\hline
\end{tabular}
\caption{Evaluation of the negative log-likelihood (\text{NLL}\,) for $12$ datasets. \textbf{Best performance} is in bold print, \underline{second best performance} is underlined. Higher values are better. Methods included outperform all others besides \textbf{MCD}\, on at least one dataset.}
\label{table:real}
\end{table}
\section{Ablation}\label{Sec:ablation}
We now present an ablation study of the impact of the construction strategy used to build $\mDwz{\ensuremath{N}}$ and the chosen value for ratio $\ratio$. We also assess the impact of additional data on performances in Framework~\ref{DATA2} and ~\ref{DATA3}. Our experiments are done on the \textbf{AsymmetricLinear}\, density model, which corresponds to a case where \textbf{MCD}\,{} is performing well but there is still room for improvement.\\
\begin{itemize}
\item[$\bullet$] The main take away is that in Framework~\ref{DATA1}, \ensuremath{i.d.}-Construction~\ref{pro:ConsUID} is far better than \ensuremath{i.i.d.}-Construction~\ref{pro:ConsIID}.
\item[$\bullet$] The appropriate ratio $\ratio$ for the \ensuremath{i.d.}-Construction~\ref{pro:ConsUID} should be around $0.05$, meaning $\ensuremath{N} = 20 \times \ensuremath{n}$.
\item[$\bullet$] In Framework~\ref{DATA3}, as soon as two target values are associated to each observation, the \ensuremath{i.d.}-Construction~\ref{pro:ConsUIDMT} can massively improve the performances of \textbf{MCD}\,, which are already very good when using \ensuremath{i.d.}-Construction~\ref{pro:ConsUID}.
\end{itemize}
\paragraph{Construction strategy and ratio $\ratio$}
\noindent\\
\noindent \ding{226} Table~\ref{table:ratio} depicts the impact of the construction strategy and ratio $\ratio$ on the performance in terms of empirical \textbf{KL}\, divergence in the classical Framework~\ref{DATA1} on the \textbf{AsymmetricLinear}\,{} density model.
\begin{itemize}
\item The appropriate ratio \ratio\, for the \ensuremath{i.i.d.}-Construction~\ref{pro:ConsIID} is $0.5$ which corresponds to a balanced distribution between the two classes.
\item It seems clear that the \ensuremath{i.d.}-Construction~\ref{pro:ConsUID} produces much better results than the \ensuremath{i.i.d.}-Construction~\ref{pro:ConsIID}. For the latter, the performances are worse than those obtained with the concurrent method \textbf{NNKCDE}\, (see Table~\ref{table:density}: \textbf{KL}\,=0.245). On the other hand, the \ensuremath{i.d.}-Construction~\ref{pro:ConsUID} obtains Top~1 performances on our benchmark, by a wide margin.
\item For the \ensuremath{i.d.}-Construction~\ref{pro:ConsUID}, it seems preferable to choose a ratio of $0.15$ or $0.05$, which corresponds respectively to a $6$ or $20$ times larger dataset. Indeed, in that case since $\ensuremath{N} = \frac{\ensuremath{n}}{\ratio}$, we have to make a trade-off between the size of the training dataset and the imbalance between the classes.
\item Following these findings, in our benchmark, we choose to use the \ensuremath{i.d.}-Construction~\ref{pro:ConsUID} with a ratio of $0.05$.
\end{itemize}
\begin{table}[http]
\centering
\scriptsize
\begin{tabular}{|l||c|c||c|}
\hline
\vspace{-0.25cm}
& & & \\
Construction & Ratio $\ratio$ & $\ensuremath{N}$ & $\textbf{KL}\,$ \\
\hline
\hline
\vspace{-0.25cm}
& & & \\
\multirow{4}{*}{$\ensuremath{i.i.d.}$-Construction~\ref{const:DwzNiid}} & 0.05 & 50 & 0.3284 \\
& 0.15 & 50 & 0.2865 \\
& 0.5 & 50 & \textbf{0.2771} \\
& 0.85 & 50 & 0.4211 \\
\hline
\vspace{-0.25cm}
& & & \\
\multirow{5}{*}{$\ensuremath{i.d.}$-Construction~\ref{const:DwzNid}} & 0.01 & 10000 & 0.0563 \\
& 0.015 & 6666 & \textbf{0.0546} \\
& 0.05 & 2000 & 0.0550 \\
& 0.15 & 666 & 0.0551 \\
& 0.5 & 200 & 0.0996 \\
\hline
\end{tabular}
\caption{Evaluation of the \textbf{KL}\, divergence of the \textbf{MCD}\,:\textbf{MLP}\, method on the \textbf{AsymmetricLinear}\, density model in Framework~\ref{DATA1} with various values for ratio $\ratio$, with $\ensuremath{i.i.d.}$ and $\ensuremath{i.d.}$ constructions. \textbf{Best} performance for each construction is in bold print.}
\label{table:ratio}
\end{table}
\paragraph{Additional marginal data}
\noindent\\
\noindent \ding{226} Table~\ref{table:marginal} depicts the impact on $\textbf{KL}\,$ performance when using Constructions~\ref{const:DwzNiidAD} and ~\ref{const:DwzNidAD} (corresponding to the \ensuremath{i.i.d.}{} and \ensuremath{i.d.}{} case respectively) in Framework~\ref{DATA2} where additional marginal data is available. We compare the respective benefit of adding only marginal observations ($\ensuremath{n_x} > 0,\, \ensuremath{n_y} = 0$), only marginal target values ($\ensuremath{n_x} = 0,\, \ensuremath{n_y} > 0$), and both marginal observation and marginal target values ($\ensuremath{n_x} > 0, \ensuremath{n_y} > 0$).\\
\begin{itemize}
\item In the \ensuremath{i.i.d.}\,case, using \ensuremath{i.i.d.}-Construction~\ref{const:DwzNiidAD} instead of \ensuremath{i.i.d.}-Construction~\ref{const:DwzNiid} produces substantial improvements in terms of performances, but not enough to outperform the \ensuremath{i.d.}-Construction~\ref{const:DwzNid}. When using the \ensuremath{i.d.}-Construction~\ref{const:DwzNidAD} instead of the \ensuremath{i.d.}-Construction~\ref{const:DwzNid}, the performance gain is smaller, but bear in mind that performances are already very satisfying at that point.
\item In the \ensuremath{i.i.d.}\,case, having access to $\ensuremath{n_y} = \ensuremath{n}$ marginal target values also allows the marginal estimator to be trained on a sample size of $\ensuremath{n_y} + \ensuremath{n} = 2 \ensuremath{n}$, which may explain why the performance gain is larger with marginal target values $\ensuremath{\mathcal{D}_{n_y}^{Y}}$ than with marginal observations $\ensuremath{\mathcal{D}_{n_x}^{X}}$ when using the \ensuremath{i.i.d.}-Constructions~\ref{const:DwzNiidAD}.
\item Meanwhile, in the \ensuremath{i.d.} case, the size of the training dataset $\mDwz{\ensuremath{N}}$ when $\max(\ensuremath{n_x},\ensuremath{n_y})> 0$ is at most $(\ensuremath{n}+ \ensuremath{n_x})(\ensuremath{n}+\ensuremath{n_y})> \ensuremath{n}^2 $, which allows to build an even larger data set ($\ensuremath{N} > \ensuremath{n}^2$). However, in that case, the choice of $\ensuremath{N}$ is constrained by the choice of ratio $\ratio$: $\ensuremath{N} = \frac{\ensuremath{n}}{\ratio}$. Here the appropriate ratio is $\ratio = 0.05$ and $\ensuremath{n} = 100$, meaning $\ensuremath{N} = 2000 \leq \ensuremath{n}^2$. As such, using Construction~\ref{pro:ConsUIDAM} to increase $\ensuremath{N}$ beyond $\ensuremath{n}^2$ is not useful in that setting.
\item The Construction~\ref{pro:ConsUIDAM} does, however, increase the amount of information present in the dataset $\mDwz{\ensuremath{N}}$. Here, the performance gain is higher in the presence of marginal observations $\ensuremath{\mathcal{D}_{n_x}^{X}}$ than marginal target values $\ensuremath{\mathcal{D}_{n_y}^{Y}}$. This may be partly due to the fact that in the \textbf{AsymmetricLinear}\, model, $X \in \ensuremath{\mathbbm{R}}^{10}$ and $Y \in \ensuremath{\mathbbm{R}}$, meaning the observations contain more information than the target values.
\end{itemize}
\begin{table}[http]
\centering
\footnotesize
\begin{tabular}{|l|c|c|c||c|c|c||c|}
\hline
\multicolumn{4}{|c||}{Setting}&\multicolumn{3}{c||}{Construction} & Results\\
\hline
\vspace{-0.22cm}
& & & & & & & \\
Available datasets & $\ensuremath{n}$ & $\ensuremath{n_x}$ & $\ensuremath{n_y}$ & Strategy & Construction & $\ensuremath{N}$ & \textbf{KL}\, \\
\hline
\hline
\vspace{-0.22cm}
& & & & & & & \\
\ensuremath{\mathcal{D}^{X,Y}_n} & 100 & 0 & 0 & & Construction~\ref{const:DwzNiid} & 50 & 0.3456 \\
\ensuremath{\mathcal{D}^{X,Y}_n}, \ensuremath{\mathcal{D}_{n_x}^{X}} & 100 & 100 & 0 & \ensuremath{i.i.d.} & Construction~\ref{const:DwzNiidAD} & 100 & \textbf{0.1204} \\
\ensuremath{\mathcal{D}^{X,Y}_n}, \ensuremath{\mathcal{D}_{n_y}^{Y}} & 100 & 0 & 100 & $\ratio = 0.5$ & Construction~\ref{const:DwzNiidAD} & 100 & \textbf{0.1203} \\
\ensuremath{\mathcal{D}^{X,Y}_n}, \ensuremath{\mathcal{D}_{n_x}^{X}} , \ensuremath{\mathcal{D}_{n_y}^{Y}} & 100 & 25 & 25 & & Construction~\ref{const:DwzNiidAD} & 75 & 0.2058 \\
\hline
\vspace{-0.22cm}
& & & & & & & \\
\ensuremath{\mathcal{D}^{X,Y}_n} & 100 & 0 & 0 & & Construction~\ref{const:DwzNid} & 2000 & 0.0551 \\
\ensuremath{\mathcal{D}^{X,Y}_n}, \ensuremath{\mathcal{D}_{n_x}^{X}} & 100 & 500 & 0 & \ensuremath{i.d.} & Construction~\ref{const:DwzNidAD} & 2000 & \textbf{0.0541} \\
\ensuremath{\mathcal{D}^{X,Y}_n}, \ensuremath{\mathcal{D}_{n_y}^{Y}} & 100 & 0 & 500 & $\ratio = 0.05$ & Construction~\ref{const:DwzNidAD} & 2000 & 0.0546 \\
\ensuremath{\mathcal{D}^{X,Y}_n}, \ensuremath{\mathcal{D}_{n_x}^{X}} , \ensuremath{\mathcal{D}_{n_y}^{Y}} & 100 & 150 & 150 & & Construction~\ref{const:DwzNidAD} & 2000 & 0.0639 \\
\hline
\end{tabular}
\caption{Evaluation of the \textbf{KL}\, divergence values of the \textbf{MCD}\,:\textbf{MLP}\, method on the \textbf{AsymmetricLinear}\, density model in Framework~\ref{DATA1} and ~\ref{DATA2} with various values for $\ensuremath{n}$, $\ensuremath{n_x}$ and $\ensuremath{n_y}$, with $\ensuremath{i.i.d.}$ and $\ensuremath{i.d.}$ constructions. \textbf{Best} performance for $\ensuremath{i.i.d.}$ and $\ensuremath{i.d.}$ are in bold print.}
\label{table:marginal}
\end{table}
\paragraph{Multiple target values per observations}
\noindent\\
\noindent \ding{226} Table~\ref{table:multisample} compares the $\textbf{KL}\,$ performances of \ensuremath{i.d.}-Construction~\ref{const:DwzNidFram3} in Framework~\ref{DATA3}, when more than one target is associated to each observation in the dataset $\ensuremath{\mathcal{D}_{n,m}^{X,\mathbb{Y}}}$. Here we denote $\ensuremath{m}$ the number of observations associated to each target. Remark that when $\ensuremath{m} = 1$, \ensuremath{i.d.}-Construction~\ref{const:DwzNidFram3} is strictly equivalent to \ensuremath{i.d.}-Construction~\ref{const:DwzNid}.\\
\begin{itemize}
\item In the presence of multiple target values per observation, \ensuremath{i.d.}-Construction~\ref{const:DwzNidFram3} allows for unparalleled performances. This can probably be explained by the fact that the goal of the \textbf{CDE}\, task is to determine the relationship between $X$ and $Y$ beyond the conditional expectation, and thus multiple realizations for a single observation better quantify the variance.
\item Besides, it seems that when $\ensuremath{m} > 1$, the appropriate ratio is higher, since the performances for $\ratio = 0.15$ are better than with $\ratio=0.05$, which is not the case when $\ensuremath{m} = 1$.
\end{itemize}
\begin{table}[http]
\centering
\footnotesize
\begin{tabular}{|l||c|c|c||c|}
\hline
Construction & $\ensuremath{m}$ & Ratio $\ratio$ & $\ensuremath{N}$ & $\textbf{KL}\,$ \\
\hline
\hline
\vspace{-0.26cm}
& & & & \\
& & 0.5 & 200 & 0.0620 \\
\ensuremath{i.d.}-Construction~\ref{const:DwzNid} & 1 & \underline{0.15} & 666 & 0.0502 \\
& & \underline{0.05} & 2000 & 0.0501 \\
\hline
\vspace{-0.26cm}
& & & & \\
& & 0.5 & 400 & 0.0520 \\
\ensuremath{i.d.}-Construction~\ref{const:DwzNidFram3} & 2 & \underline{0.15} & 1333 & 0.0438 \\
& & 0.05 & 4000 & 0.0461 \\
\hline
\vspace{-0.26cm}
& & & & \\
& & 0.5 & 2000 & 0.0179 \\
\ensuremath{i.d.}-Construction~\ref{const:DwzNidFram3} & 10 & \underline{0.15} & 6666 & \textbf{0.0167} \\
& & 0.05 & 20000 & 0.0191 \\
\hline
\end{tabular}
\caption{Evaluation of the \textbf{KL}\, divergence values of the \textbf{MCD}\,:\textbf{MLP}\, method on the \textbf{AsymmetricLinear}\, density model in Framework~\ref{DATA1} and ~\ref{DATA3} with various values for ratio $\ratio$ and $\ensuremath{m}$. \textbf{Best} performance is in bold print. \underline{Best} performance ratio for each value of $\ensuremath{m}$ is underlined. Column 2 corresponds to the number of target values associated to each observation.}
\label{table:multisample}
\end{table}
\subsection{Application to images}
In this section we are going to investigate the usefulness of the contrast discriminator $q$ even in cases where densities are not well defined or tractable, that is image datasets. Self-supervised learning tasks and generative modelling are beyond the scope of this chapter, but we nonetheless show a toy experiment related to these tasks on the classic MNIST(cite) dataset.\\
The aim of the experiment is simple: given the left side of an image, can the binary classifier trained with the $\textbf{MCD}\,$ method predict if the right side of the image is appropriate or not. Simply put, we consider the joint density of the $28\times 14$ pixels of the right side of the image \textbf{conditionally} to the $28\times 14$ pixels on the left side of the image. Of course, this is a clear case where the $\textbf{MCD}\,$ method main limitation becomes apparent: the marginal density of the right side of the image cannot be estimated. However, estimating the contrast function can still be relevant.
\subsubsection{Experimental protocol}
To illustrate this, we generate a training set of images using the $\ensuremath{i.i.d.}$ construction strategy, splitting each image in two vertically, the left side corresponding to the observation and the right side to the target. We then train a basic ConvNet. \\
To evaluate the performances of our method, we do as follows: First, we generate a test set consisting of couples of true and false images. To generate each couple, we take an image from the test set, it becomes the true image of the couple. Then we take only the left side of the image and concatenate it with the right side of an other image taken at random. Our main goal is to see if for each couple of images, the predicted contrast value is higher for the true image than the false one. Moreover, when considering the false images, the predicted contrast value should be higher if the right side corresponds to the same digit.
\subsubsection{Results}
For any couple of images of the test set, let $(q(x,y, true)$ and $q(x,y, false))$ denote the discriminator prediction for the true and false image respectively. Recall that $0 \leq q < 1$ and that higher values correspond to more confidence that both sides of the image originate from the same image. We evaluated $(q(x,y, true)$ and $q(x,y, false))$ for $1000$ couple of true/false images, and computed the three following metrics: \\\\
\textbf{Metric 1}: The average predicted contrast.
\begin{itemize}
\item Average $q(x,y)$ value for \textbf{true} images : $0.991$.
\item Average $q(x,y)$ value for \textbf{false} images : $0.013$.
\item Average $q(x,y)$ value for \textbf{false} images when $y_{false}$ is \textbf{the same} digit: $0.054$.
\item Average $q(x,y)$ value for \textbf{false} images when $y_{false}$ is \textbf{a different} digit: $0.009$.
\end{itemize}
\textbf{Metric 2}: The percentage of true/false couples of images where the predicted contrast was higher for the true image compared to the false image.
\begin{itemize}
\item Percentage of times $q(x,y, true) < q(x,y, false)$ : $0.1\%$.
\item Percentage of times $q(x,y, true) < q(x,y, false)$ when $y_{false}$ is \textbf{the same} digit: $1.04\%$.
\item Percentage of times $q(x,y, true) < q(x,y, false)$ when $y_{false}$ is \textbf{a different} digit: $0.0\%$.
\end{itemize}
\textbf{Metric 3}: The percentage of times the probability given by the binary classifier was above the threshold $0.5$.
\begin{itemize}
\item Percentage of times $q(x,y, true) > 0.5$ : $99.4\%$.
\item Percentage of times $0.5 > q(x,y, false)$ : $98.9\%$.
\item Percentage of times $q(x,y, false) > 0.5$ when $y_{false}$ is \textbf{the same} digit: $4.16\%$.
\item Percentage of times $0.5 < q(x,y, false)$ when $y_{false}$ is \textbf{a different} digit: $0.77\%$.
\end{itemize}
Here, $y_{false}$ denotes the right side of the image for the false couple.\\
Clearly, the classifier behaves like a simple but efficient discriminator. The original classes of the images impacts the predicted value as the discriminator predicts higher contrasts when both sides correspond to the same class. It also impacts the performance of the discriminator, since there is not even one case where the predicted contrast value is higher for the false images than for the true image when the false image left and right side correspond to different digits.\\
As a conclusion, in this simple example we obtained a method to estimate if two parts of an image correspond to the same class or not, without ever using explicitly the classes associated to each image.
\begin{figure}[http!]
\centering
\includegraphics[scale=0.33]{Figures/MNIST_meilleures_true.png}
\caption{The $10$ images from the original test set with the highest predicted $q$. These corresponds to the images where the discriminator was the most confident that the left and right side of the image originated from the same image. Comment: These results are satisfying because these examples of MNIST digits are quite representative of the representative digits.
}
\end{figure}
\begin{figure}[http!]
\centering
\includegraphics[scale=0.33]{Figures/MNIST_meilleures_false.png}
\caption{The $10$ images in the test set where the left and right side of the image originate from different images, with the lowest predicted $q$. These corresponds to the images where the discriminator was the most confident that the left and right side of the image originated from different images. Comment: The forth and ninth images look like a digit $8$ but there is a clear gap between the left and right side of the images. These results are satisfying since we would expect the discriminator to reject those images
}
\end{figure}
\begin{figure}[http!]
\centering
\includegraphics[scale=0.33]{Figures/MNIST_pires_true.png}
\caption{The $10$ images from the original test set with the lowest predicted $q$. These corresponds to the images where the discriminator was the least confident that the left and right side of the image originated from the same image. Comment: For the five six images the predicted $q$ value is below the $0.5$ threshold. For the first image, the poor handwriting (the actual digit is a $5$) might excuse the mistake. The five next images are clear mistakes from the discriminator. However, this corresponds to the only five out of a test set of one thousand images
}
\end{figure}
\begin{figure}[http!]
\centering
\includegraphics[scale=0.33]{Figures/MNIST_pires_false.png}
\caption{The $10$ images in the test set where the left and right side of the image originate from different images, with the \textbf{highest} predicted $q$. These corresponds to the images where the discriminator was the least confident that the left and right side of the image originated from different images. Comment: The forth and ninth images do not seem to correspond to a digit at all, and the discriminator failed to reject those. Meanwhile images five six seven eight and ten actually look like a digit which might justify the discriminator mistakes
}
\end{figure}
\begin{figure}[http!]
\centering
\includegraphics[scale=0.33]{Figures/MNIST_meilleures_diff.png}
\caption{ The $10$ couples of images in the test set where the left side is the same for the upper and lower images, while the right side originates from the same image for the upper image and from a different image for the lower image, sorted by difference in terms of $q$. These corresponds to the couples of images where the discriminator was the most confident that the left image was more likely to correspond to the upper right image than the lower right image. Comment: These results are satisfying since for the nine first images, there is no ambiguity. For the tenth image both sides looked like a digit '3' but the upper image corresponds to a better handwriting
}
\end{figure}
\begin{figure}[http!]
\centering
\includegraphics[scale=0.33]{Figures/MNIST_pires_diff.png}
\caption{ The $10$ couples of images in the test set where the left side is the same for the upper and lower images, while the right side originates from the same image for the upper image and from a different image for the lower image, sorted by difference in terms of $q$ in reverse order. These corresponds to the couples of images where the discriminator was the most confident that the left image was more likely to correspond to the upper right image than the lower right image. Comment: These results are satisfying since for the nine first images, there is no ambiguity. For the tenth image both sides looked like a digit '3' but the upper image corresponds to a better handwriting.
}
\end{figure}
\subsection{Related work}
Historically, the first attempts were based on the use of Bayes' formula~\eqref{eq:Bayes0} which transforms the \textbf{CDE}\, into the estimation of two density functions, thus allowing the use of techniques dedicated to density estimation.
\begin{align}
\label{eq:Bayes0}
\pf{Y\pCond X =x}(y) = \frac{\pf{X,Y}(x,y)}{\pf{X}(x)}, \, \pf{X}(x) \neq 0
\end{align}
In this article\,, we address the many real-world applications of supervised learning regressions where we have a one-dimensional target but a large number of features. A major flaw of reformulating a conditional density as the ratio of two densities, is that even if $Y$ is low dimensional, we will still incur the curse of dimensionality if $X$ is high-dimensional. Although techniques exist to alleviate the curse to some extent by leveraging sparsity or other properties of $X$, it would be far easier to reformulate the \textbf{CDE}\, so that only the estimate of the marginal density $\pf{Y}$ is required instead of $\pf{X}$.
\paragraph{Nonparametric density estimation.}
Nonparametric estimation is a powerful tool for density estimation as it does not require any prior knowledge of the underlying density. One of the first intuitions of kernel estimators was proposed by \cite{rosenblatt_remarks_1956} and later by \cite{parzen_estimation_1962}. Kernel estimators were then widely studied ranging from bandwidth selection (\cite{goldenshluger_bandwidth_2011}), non linear aggregation (\cite{rigollet_linear_2006}), computational optimisation (\cite{langrene_fast_2020}) to the extension to conditional densities (\cite{bertin_adaptive_2014}). We refer to \cite{silverman_density_2017} and references therein for interested reader. A very popular and effective nonparametric method is the $k$-Nearest Neighbors (\cite{fix_discriminatory_1989}), but like other nonparametric methods (kernel estimators, histogram \cite{pearson_contributions_1895},...), a main limitation is the curse of dimensionality (\cite{scott_feasibility_1991,nagler_evading_2016}). \cite{silverman_density_2017} showed that, in a density estimation setting, the number of points $n$, needed to obtain equivalent results when fitting a $d$-dimensional random variable, grows at a rate of $n^{\frac{4}{4 + d}}$. Meanwhile, the impact of dimensionality on the computational time also scales exponentially. To the best of our knowledge, the best performing method for kernel estimation, based on a divide-and-conquer algorithm (\cite{langrene_fast_2020}), has a complexity of $\ensuremath{\mathcal{O}} (n \log(n)^{\max(d-1,1)})$. Both of these relationships are compounded, as higher dimensionality means that exponentially more data is required and the computational time relative to the size of the dataset will also grow exponentially.\\
\paragraph{Noise Contrastive methods.}
Another important family of techniques for density estimation is noise-contrastive learning (\cite{gutmann_noise-contrastive_2010}). These techniques reformulate the estimation of the density into a binary classification problem (up to a constant). It consists in introducing a known probability density $g(\cdot)$ and sampling from it a synthetic dataset. The latter is concatenated with the original dataset, then a target value $Z_i$ is associated such that $Z_i$ is equal to $1$ if the observation comes from the original dataset and $0$ otherwise.
A \textbf{contrast} $q(\cdot)$, which can be, under certain conditions on $g$, directly related to the density of the original observations is introduced to obtain an estimation of the density function :
\begin{equation}
\label{eq:noisecontrastive}
q (x):= \ensuremath{\mathbb{P}}[Z=1\pCond X = x]= \frac{\pf{X}(x)}{\pf{X}(x)+g(x)}\quad \text{and}\quad \pf{X}(x) = g(x)\frac{q(x)}{1-q(x)}.
\end{equation}
A binary classifier is then trained to predict this target value conditionally on the associated observation.\\
Contrast learning has been successfully applied in the area of self-supervision learning (\cite{jaiswal_survey_2020,he_momentum_2020}), especially on computer vision tasks (\cite{bachman_learning_2019}).
Many extensions and improvements have been made, including w.r.t. the learning loss function (\cite{khosla_supervised_2021}), data augmentation techniques (\cite{chen_simple_2020}), network architectures (\cite{he_momentum_2020}) and computational efficiency (\cite{yeh_decoupled_2021}). Our proposed method is partially based on this technique, with two major differences. First, our technique addresses \textbf{CDE}\, problem and not density estimation or self-supervised learning. Second, the distribution we choose is unknown, potentially intractable, and/or with a large set of highly dependent components, which violates the usual restrictions for performing noise contrastive density estimation but allows us to taylor the noise distribution precisely to the estimated distribution.
This allows us to fit the noise distribution precisely to the estimated distribution. To the best of our knowledge, the technique closest to our method is designed to evaluate the deviation from the independence setting, $i.e.$ when all random features $\{X_j\}_{j=1,\cdots,\ensuremath{p}}$ are independent, in an unsupervised framework. It has been briefly described in the second edition of \cite{tibshirani_elements_nodate} (pages 495-497) where, based on the noise contrastive reformulation given above with $g(\cdot) = \Pi_{j=1}^{\ensuremath{p}} \pf{X_j}(\cdot)$. Note that $g$ is unknown and corresponds to what we will call later the noise distribution. Nevertheless, noise samples can be generated by applying a random permutation on the feature columns of the dataset, which is sufficient to discover association rules between the $X$ features but not to estimate the density function $\pf{X}$. On the other hand, although each component of $X$ is one-dimensional by definition, the errors made when estimating the marginal densities $\ensuremath{p}$ will compound when estimating $g$, which means that the dimensionality of $X$ is again a limiting factor.
\paragraph{\textbf{CDE}\, reformulation.} There are other ways to reformulate the \textbf{CDE}\,, for example \cite{sugiyama_conditional_2010} propose a reformulation into a Least-Squares Density Ratio (\textbf{LSCond}\,) and \cite{meinshausen_quantile_nodate} into a quantile regression task. Still others take advantage of a reformulation of the \textbf{CDE}\, into a supervised learning regression task. Meanwhile, \textbf{RFCDE}\, (\cite{pospisil_rfcde_2018}) and \textbf{NNKCDE}\, (\cite{pospisil_nnkcde_2020}) are techniques that adapt methods that have proven to be effective to the \textbf{CDE}\, task.
Other methods, such as \textbf{Deepcde}\, (\cite{disanto_photometric_2018}) and \textbf{FlexCode}\, (\cite{izbicki_converting_2017}), go further and design a surrogate regression task that can be run by an off-the-shelf supervised learning method taking advantage of many mature and well-supported open-source projects, $e.g.$ scikit-learn (\cite{pedregosa_scikit-learn_2011}), \textit{pytorch}\, (\cite{paszke_pytorch_2019}), \textit{fastai} (\cite{howard_fastai_2020}) , \textit{keras} (\cite{chollet_keras_2022}), \textit{tensorflow}\, (\cite{martin_abadi_tensorflow_2015}), \textbf{CatBoost}\, (\cite{prokhorenkova_catboost_2018}), \textbf{XGboost}\, (\cite{chen_xgboost_2016}), etc. Our method implementation also has this advantage, since it can take as arguments any class that follows the scikit-learn $init/fit/predict\_proba$ API, which includes our off-the-shelf \textbf{MLP}\, implementations, linear grid units (\textbf{GLU},\cite{gorishniy_revisiting_2021}), \textbf{ResBlock} (\cite{gorishniy_revisiting_2021}) and self-normalizing networks (\textbf{SNN}\,,\cite{klambauer_self-normalizing_2017}).\\
\paragraph{Neural networks and variational inference.}
Long before the current resurgence of interest in deep learning, there were already neural networks designed specifically to handle \textbf{CDE}\,, $e.g.$
\cite{bishop_mixture_1994} adressed the problem of estimating a probability density using Mixture Density Networks (\textbf{MDN}\,). More recently, Kernel Mixing Networks (\textbf{KMN}\,, \cite{ambrogioni_kernel_2017}) are networks trained to estimate a family of kernels to perform the \textbf{CDE}\, task. Another famous variational inference technique is Flow Normalization (\textbf{N.Flow}\,, \cite{rezende_variational_2016}), designed to solve the problem of finding the appropriate approximation of the posterior distribution. A common challenge with most of these methods is scalability in terms of computation resources, which our experimental benchmark confirmed. A \textit{python}\, implementation of \textbf{MDN}\,, \textbf{KMN}\, and \textbf{N.Flow}\, is provided by the $freelunchtheorem$ package (\cite{noauthor_conditional_nodate}), which we included in our benchmark.
\subsection{Our contributions}
Our method, called contrastive marginal discrimination, \textbf{MCD}\,, combines several characteristics of the above methods but without their respective limitations. At a basic level, \textbf{MCD}\, begins by reformulating the conditional density function into two factors, the marginal density function of $Y$ and a ratio of density functions as follows
$$
\pf{Y\pCond X=x}(y) = \pf{Y}(y)\frac{\pf{X,Y}(x,y)}{\pf{X}(x)\pf{Y}(y)},\quad \forall (x,y) \in \ensuremath{\mathcal{X}}\times\ensuremath{\mathcal{Y}} \text{ s.t. }\pf{X}(x)\neq0,\,\, \pf{Y}(y)\neq0
$$
We propose to estimate these two quantities separately. In most real applications of \textbf{CDE}\,, $Y$ is univariate or low-dimensional, while $X$ is not. In these cases, it is much easier to estimate $\pf{Y}$ rather than $\pf{X}$ and $\pf{X,Y}$. In this article\,, we do not focus on how to choose the estimation method for $\pf{Y}$ or introduce new techniques to estimate $\pf{Y}$. By contrast, our experimental results show that out-of-shelf kernel estimators with default parameters perform very well on both simulated density models and real datasets, as expected for univariate distributions.\\
The core of our method is the reformulation of the ratio of the density functions $\pf{X,Y}/\big(\pf{X}\pf{Y}\big)$ into a contrast. In our method, the introduced noise in equation~\ref{eq:noisecontrastive} always corresponds to the density function $g(\cdot) = \pf{X}\pf{Y}$. This is akin to the reformulation proposed by \cite{tibshirani_elements_nodate}, except that we only break the relationship between the two elements of the pair $(X,Y)$ but not between each component of $X$ and $Y$: $\pf{X,Y}(\cdot) = \pf{X}(\cdot)\pf{Y}(\cdot) \frac{q(\cdot)}{1 - q(\cdot)}$. To estimate the joint density $\pf{X,Y}$ it would be necessary to estimate both $\pf{X}$ and $\pf{Y}$. But when we apply Bayes' formula (\ref{eq:Bayes0}), we divide by $\pf{X}$, which disappears from the expression of $\pf{Y\pCond X}$, meaning we only need to estimate $\pf{Y}$ and $q$.\\
Like noise-contrastive methods, \textbf{MCD}\, can leverage \textit{state-of-the-art} supervised learning techniques to perform \textbf{CDE}\,, especially neural networks.
Our numerical experiments reveal \textbf{MCD}\, performances are far superior when using neural networks compared to other popular classifiers like \textbf{CatBoost}\,, \textbf{XGboost}\, or Random Forest. Our benchmark also reveals that our method significantly outperforms in practice \textbf{RFCDE}\,, \textbf{NNKCDE}\,, \textbf{MDN}\,, \textbf{KMN}\,, \textbf{N.Flow}\,, \textbf{Deepcde}\,, \textbf{FlexCode}\, and \textbf{LSCond}\, on most the density models and regression datasets included in our benchmark. Moreover, the \textbf{MCD}\, reformulation enables us to train the binary classifier on a contrast training set much larger than the original dataset. Evermore, \textbf{MCD}\, can easily take advantage of additional data. Unlabeled observations can be directly used to increase the size of the training set, without any drawbacks. Similarly, in the case where each observation is associated with more than one target value, they can all be included in the training dataset.\\
Our main contributions are as follows:
\begin{itemize}
\item We introduce a reformulation of the \textbf{CDE}\, problem into a contrastive learning task which combines a binary classification task and a marginal density estimation task, which are both much easier than \textbf{CDE}\,.
\item We prove that given a training set of size $\ensuremath{n}$ it is always possible to generate a $\ensuremath{i.i.d.}$ training set of size $\ArrB{\frac{\ensuremath{n} }{2}}$ corresponding to the contrast learning task. We also prove that it is always possible to generate a training set of size at most $\ensuremath{n}^2$ in the non $\ensuremath{i.i.d.}$ case.
\item We provide the corresponding construction procedures and the \textit{python}\, implementation. We also provide construction procedures to leverage additional marginal data and multiple targets per observations, which can improve performances significantly.
\item We produce a benchmark of $9$ density models and $12$ datasets. We combine our method with a large set of classifiers and neural networks architectures, and compare ourselves against a large set of \textbf{CDE}\, methods. Our benchmark reveals that \textbf{MCD}\, \textbf{outperforms all the existing methods on the majority of density models and datasets, sometimes by a very significant margin}.
\item We provide a \textit{python}\, implementation of our method compatible with any \textit{pytorch}\, module or \textit{scikit-learn} classifier, and the complete code to replicate our experiments.
\end{itemize}
\noindent\\
The rest of this article\, is organised as follows: section~\ref{Sec:theory} provides a theoretical background for the reformulation. Section~\ref{Sec:experiments} provides the implementation details and evaluates our method on density models and regression datasets, comparing results with the methods implemented in the \textit{python}\, frameworks \textit{CDEtools}\,\cite{dalmasso_conditional_2020,pospisil_cdetools_2022} and \textit{freelunchtheorem}\, \cite{noauthor_conditional_2022,rothfuss_conditional_2019}. Section~\ref{Sec:ablation} provides an ablation study of our method. Section~\ref{Sec:proofs} provides the proofs for theoretical results and the algorithms to construct the training dataset.\\
\section{Proofs and dataset constructions}\label{Sec:proofs}
\subsection{Proof Fact~\ref{fac:MCF}}
Let $(x,y)\in \mathcal{X}\times \mathcal{Y}$ be any couple of values for which we need to prove Fact~\ref{fac:MCF}.
We have by the $Bayes$'s formula:
\begin{equation}
\frac{\pf{Y\pCond X=x}(y)}{\pf{Y}(y)} = \frac{\pf{X,Y}(x,y)}{\pf{X}(x)\pf{Y}(y)},\, \pf{X}(x)> 0, \, \pf{Y}(y)>0 \label{eq:Bayes}
\end{equation}
Then, for any $\ratio \in (0,1)$:
$$
\frac{\pf{X,Y}(x,y)}{\pf{X}(x)\pf{Y}(y)} = \frac{\ratio\pf{X,Y}(x,y)}{\ratio\pf{X,Y}(x,y) + (1 - \ratio)\pf{X}(x)\pf{Y}(y)}\times \frac{\ratio\pf{X,Y}(x,y) + (1 - \ratio)\pf{X}(x)\pf{Y}(y)}{\ratio \pf{X}(x)\pf{Y}(y)}
$$
Let $q(x,y) := \frac{\ratio\pf{X,Y}(x,y)}{\ratio\pf{X, Y}(x,y) + (1 - \ratio)\pf{X}(x)\pf{Y}(y)}$ the marginal constrast function with ratio $\ratio$ defined on Definition~\ref{def:MCF}
\begin{align*}
\frac{\pf{X,Y}(x,y)}{\pf{X}(x)\pf{Y}(y)}&= q(x,y)\times \left(\frac{\pf{X,Y}(x,y)}{\pf{X}(x)\pf{Y}(y)} +\frac{1 - \ratio}{\ratio}\right)\\
\Leftrightarrow
(1-q(x,y))\frac{\pf{X,Y}(x,y)}{\pf{X}(x)\pf{Y}(y)}&= q(x,y)\frac{1 - \ratio}{\ratio} \\
\Leftrightarrow\frac{\pf{Y\pCond X=x}(y)}{\pf{Y}(y)} &= \frac{1-\ratio}{\ratio}\frac{q(x,y)}{1-q(x,y)}
\end{align*}
The last equation is deduced using equation~\eqref{eq:Bayes}.
\subsection{Proof Proposition~\ref{pro:equiv}}\label{sec:Proofequiv}
By condition~\ref{MDC1} of Definition~\ref{def:MDC} we have $Z \sim \pBB(r)$, then
$$
\ensuremath{\mathbb{P}}[Z = 1] = r\ \text{ and} \ \pf{Z }(z)=p^{z}(1-p)^{1-z}.
$$
Moreover, by condition~\ref{MDC3} of Definition~\ref{def:MDC}, we have $\forall (x,y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$, $\pf{W }(x,y) = r\pf{X,Y}(x,y)+ (1-r)\pf{X}(x)\pf{Y}(y)$.
By condition~\ref{MDC4} of Definition~\ref{def:MDC} we have
\begin{align*}
\pf{W \pCond Z = 1}(x,y) &= \pf{X,Y}(x,y)\\
\pf{W \pCond Z = 0}(x,y) &= \pf{X}(x)\pf{Y}(y)
\end{align*}
By Definition~\ref{def:MCF} we have
\begin{align*}
q(x,y) &= \frac{\ratio \times \pf{X,Y}(x,y)}{\ratio \pf{X,Y}(x,y) + (1-\ratio)\pf{X}(x)\pf{Y}(y)}
= \frac{\ensuremath{\mathbb{P}}[Z = 1] \times \pf{W \pCond Z = 1}(x,y)}{\ratio \pf{W \pCond Z = 1}(x,y) + (1-\ratio)\pf{W \pCond Z = 0}(x,y)}\\
&= \frac{\ensuremath{\mathbb{P}}[Z = 1] \times \pf{W \pCond Z = 1}(x,y)}{\pf{W }(x,y)}
= \frac{\ensuremath{\mathbb{E}_{Z}}[\ensuremath{\mathds{1}}_{Z = 1}] \times \left[1\times \pf{W \pCond Z = 1}(x,y)+0\times \pf{W \pCond Z = 0}(x,y)\right]}{\pf{W}(x,y)}\\
&= \frac{\ensuremath{\mathbb{E}_{Z}}[\ensuremath{\mathds{1}}_{Z = 1}] \times \ensuremath{\mathbb{E}_{Z}}[\pf{W \pCond Z=z}]}{\pf{W}(x,y)}
= \frac{\ensuremath{\mathbb{E}_{Z}}[\ensuremath{\mathds{1}}_{Z = 1}\pf{W \pCond Z = z}(x,y)] }{\pf{W}(x,y)}
= \frac{\ensuremath{\mathbb{E}_{Z}}[\ensuremath{\mathds{1}}_{Z = 1}\pf{W ,Z}(x,y,z)] }{\pf{W}(x,y)\pf{Z }(z)}\\
&= \ensuremath{\mathbb{E}_{Z}}\left[\ensuremath{\mathds{1}}_{Z = 1}\times\frac{\pf{Z \pCond W = (x,y)}(z)}{\pf{Z }(z)}\right]
= \ensuremath{\mathbb{E}_{Z}}\left[\ensuremath{\mathds{1}}_{Z = 1}\times\frac{\ensuremath{\mathbb{P}}\left[Z = z\pCond W = (x,y)\right]}{\ensuremath{\mathbb{P}}[Z = z]}\right]\\
&= \ensuremath{\mathbb{E}_{Z}}\left[\ensuremath{\mathds{1}}_{Z = 1}\times\frac{\ensuremath{\mathbb{P}}\left[Z = 1\pCond W = (x,y)\right]}{\ensuremath{\mathbb{P}}[Z = 1]}\right]
= \ensuremath{\mathbb{E}_{Z}}[\ensuremath{\mathds{1}}_{Z = 1}]\frac{\ensuremath{\mathbb{P}}[Z = 1\pCond W = (x,y)]}{\ensuremath{\mathbb{P}}[Z = 1]}\\
&= \ensuremath{\mathbb{P}}[Z = 1 \pCond W = (x,y)] = \ensuremath{\mathbb{E}}[Z \pCond W = (x,y)]
\end{align*}
\subsection{Proof Theorem~\ref{pro:ConsIID} and Construction in the i.i.d. case}
\label{Sec:ProofConsIID}
First construct a random vector $(W,Z)$ satisfying the $\ensuremath{\text{MDcond}}(\ratio)$ with $\ratio \in \ensuremath{(0,1)}$.
\begin{itemize}
\item Consider the random vector $(X,Y)$ admitting $\pf{X,Y}$ as density of probability.
\item Let $\widetilde{Y}$ be a random variable independent of $X$ and $Y$ and of same law $\pf{Y}$ of $Y$ ($\widetilde{Y} \ensuremath{{\buildrel \mathcal{D} \over =}} Y$).
\item Let $\ratio$ be a real number in $\ensuremath{(0,1)}$ and $Z \sim \pBB(\ratio)$.
\item Set $W = (X,Y \ensuremath{\mathds{1}}_{Z = 1} + \widetilde{Y} \ensuremath{\mathds{1}}_{Z = 0})$.
\end{itemize}
Then, for all $(x,y,\widetilde{y}) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}} \times \ensuremath{\mathcal{Y}}$ we have $$\forall z \in \ensuremath{\{0;1\}} \, \pf{W \pCond Z = z}(x,y,\widetilde{y}) = \left\{
\begin{array}{ll}
\pf{X ,Y}(x,y) & \mbox{if } z = 1 \\
\pf{X}(x)\pf{Y}(\widetilde{y}) & \mbox{if } z = 0
\end{array}
\right.$$
\noindent Therefore, $\forall (x,y,z) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}} \times \ensuremath{\{0;1\}}$, $\pf{W \pCond Z = z}(x,y) = \pf{X,Y}(x,y) \ensuremath{\mathds{1}}_{z = 1} + \pf{X}(x)\pf{Y}(y) \ensuremath{\mathds{1}}_{z = 0})$.
Moreover, $\forall (x,y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$
\begin{align*}\label{eq:4imp3lol3}
\pf{W}(x,y) &= \Integ{}{}\pf{W \pCond Z = z}(x,y) \pf{Z}(z) \, dz\\
&= \pf{W \pCond Z = 1}(x,y)\ensuremath{\mathbb{P}}[Z = 1] + \pf{W \pCond Z = 0}(x,y)\ensuremath{\mathbb{P}}[Z = 0]\\
&= \pf{W \pCond Z = 1}(x,y)\ratio + \pf{W \pCond Z = 0}(x,y)(1 - \ratio) \\
&= \ratio\pf{X,Y}(x,y)+ (1-\ratio)\pf{X}(x)\pf{Y}(y).
\end{align*}
Therefore $Z,W$ satisfies Definition~\ref{def:MDC}. Now, consider the original $\ensuremath{n}$-sample $\ensuremath{\mathcal{D}^{X,Y}_n}$ and set $\ensuremath{N} = \ArrB{\ensuremath{n}/2}$. We can now construct the $\mDwz{\ensuremath{N}}$ sample.
\vspace{0.5cm}
\noindent
\begin{minipage}{5.5cm}
\begin{mdframed}
\vspace{-0.1cm}
\begin{const}
\label{const:DwzNiid}
\big[$\ensuremath{i.i.d.}$ $\mDwz{\ensuremath{N}}$\big]
\end{const}
\vspace{-0.1cm}
\end{mdframed}
\end{minipage}
\vspace{0.5cm}\\
Consider the original $\ensuremath{n}$-sample $\ensuremath{\mathcal{D}^{X,Y}_n}$ and set $\ensuremath{N} = \ArrB{\ensuremath{n}/2}$. We can now construct the $\mDwz{\ensuremath{N}}$ sample:\\
\noindent
\textbf{Step (1)}\,\label{stepone}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
First sample $\ensuremath{N}$ independent observations $Z_1, \cdots , Z_{\ensuremath{N}}$ with respect to $\pBB(\ratio)$.
\end{minipage}
\end{tabular}
\vspace{0.5cm}
\noindent\textbf{Step (2)}\,\label{steptwo}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
Next, $\forall i = 1, \cdots , \ensuremath{N}$, set $ W_i = (X_i, Y_i \ensuremath{\mathds{1}}_{Z_i = 1} + Y_{i + \ensuremath{N}} \ensuremath{\mathds{1}}_{Z_i = 0})$.
\end{minipage}
\end{tabular}\\
Since $\ensuremath{N}>0$ and the $\ensuremath{N}$ couples $(W_i, Z_i)_i$ are constructed from the $\ensuremath{N}$-$\ensuremath{i.i.d.}$ quadruplets $(X_i, Y_i, Y_{i + \ensuremath{N}}, Z_i)_i$, they are $\ensuremath{i.i.d.}$.
\subsection{Proof Theorem~\ref{pro:ConsUID} and Construction in the i.d. case}
\label{Sec:ProofConsUID}
Let $n_J$ and $n_M$ two integers such that $1 \leq n_J \leq \ensuremath{n}$ and $1 \leq n_M \leq \ensuremath{n}(\ensuremath{n}-1)$.
\vspace{0.5cm}
\noindent
\begin{minipage}{5.5cm}
\begin{mdframed}
\vspace{-0.1cm}
\begin{const}
\label{const:DwzNid}
\big[$\ensuremath{i.d.}$ $\mDwz{\ensuremath{N}}$\big]
\end{const}
\vspace{-0.1cm}
\end{mdframed}
\end{minipage}
\vspace{0.5cm}
\noindent
\textbf{Step (1)}\,\label{stepone2}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
Construct $\ensuremath{n}^2$ observations $\{(\widetilde{W}_i,\widetilde{Z}_i)\}_{i = 1, \cdots, \ensuremath{n}^2}$ such that:
$\forall j = 0, \cdots, \ensuremath{n} - 1, \, \forall k = 1, \cdots, \ensuremath{n} \, : \,$
\begin{equation}\label{eq:steponelol}
\left\{
\begin{array}{ll}
\widetilde{W}_{j \ensuremath{n} + k} = (X_{j+1}, Y_k) \\
\widetilde{Z}_{j \ensuremath{n} + k} = \ensuremath{\mathds{1}}_{j+1 = k}
\end{array}
\right.
\end{equation}
\end{minipage}
\end{tabular}
\noindent Note that the $\ensuremath{n}^2$ observations are neither independent nor identically distributed and do not satisfy yet the $\ensuremath{\text{MDcond}}$.\\
\noindent
\textbf{Step (2)}\,\label{steptwo2}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
Split the $\ensuremath{n}^2$ couple of observations $\{(\widetilde{W}_i,\widetilde{Z}_i)\}_{i = 1, \cdots, \ensuremath{n}^2}$ into two:
$$
\left\{
\begin{array}{ll}
S_J \,= \{(\widetilde{W}_i,\widetilde{Z}_i)\} : \, \widetilde{Z}_i = 1 \, \forall i \\
S_M = \{(\widetilde{W}_i,\widetilde{Z}_i)\} : \, \widetilde{Z}_i = 0 \, \forall i .
\end{array}
\right.
$$
\end{minipage}
\end{tabular}
\vspace{0.5cm}
\noindent
\textbf{Step (3)}\,\label{stepthree2}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
Sample at random uniformly without replacement $n_J$ observations $(\widetilde{W}_i,\widetilde{Z}_i)$ from $S_J$ and denote $\widetilde{S}_J$ this $n_J$ sample.
\end{minipage}
\end{tabular}\\
\noindent Note that since $\widetilde{Z}_i = 1$ if and only if $j+1 = k$ in equation\eqref{eq:steponelol}, we have
\begin{equation}\label{eq:SJlol1}
\forall (\widetilde{W}_i,\widetilde{Z}_i) \in \widetilde{S}_J, \widetilde{Z}_i = 1 \text{ and }\pf{\widetilde{W}_i \pCond \widetilde{Z}_i = 1} \equiv \pf{X,Y}
\end{equation}
This means that $\widetilde{W}_{j(\ensuremath{n} + 1) + 1} = (X_{j+1},Y_{j+1})$.
\vspace{0.5cm}
\noindent
\textbf{Step (4)}\,\label{stepfour2}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
Sample at random uniformly without replacement $n_M$ observations $(\widetilde{W}_i,\widetilde{Z}_i)$ from $S_M$ and denote $\widetilde{S}_M$ this $n_M$ sample.
\end{minipage}
\end{tabular}\\
\noindent Note that since $\widetilde{Z}_i = 0$ if and only if $j+1 \neq k$ in equation\eqref{eq:steponelol}, we have
\begin{equation}\label{eq:SJlol2}
\forall (\widetilde{W}_i,\widetilde{Z}_i) \in \widetilde{S}_M, \widetilde{Z}_i = 0 \text{ and }\pf{\widetilde{W}_i \pCond \widetilde{Z}_i = 0} \equiv \pf{X}\pf{Y}
\end{equation}
This means that $\widetilde{W}_{j\ensuremath{n} + k} = (X_{j+1},Y_{k})$ (recall $X_l \perp \!\!\! \perp X_k \, \forall l \neq k$).
\vspace{0.5cm}
\noindent
\textbf{Step (5)}\,\label{stepfive2}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
Concatenate the samples $\widetilde{S}_J$ and $\widetilde{S}_M$ and shuffle uniformly to obtain a $\ensuremath{N}$ sample $\mDwz{\ensuremath{N}}= \mathcal{U}\texttt{nif.}\mathcal{S}\texttt{huffle} \left(\{ \widetilde{S}_J; \widetilde{S}_M\}\right)$.
\end{minipage}
\end{tabular}
\vspace{0.5cm}
\noindent Prove now that $\forall i = 1, \cdots , \ensuremath{N},$ the couple $(W_i, Z_i) \in \mDwz{\ensuremath{N}}$ satisfies $\ensuremath{\text{MDcond}}(\frac{n_J}{\ensuremath{N}})$.
\begin{itemize}
\item[\eqref{MDC1}] As we shuffle uniformly the indices, we have $\forall i = 1, \cdots, \ensuremath{N}, \, Z_i \in \mDwz{\ensuremath{N}}$, $Z_i \sim \pBB(\frac{n_J}{\ensuremath{N}})$.
\item[\eqref{MDC2}] By \textbf{Step (1)}\,, it is obvious that all the $W_i$ admit $\ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$ as support.
\item[\eqref{MDC4}] Let $(W_i, Z_i)$ be any element of $\mDwz{\ensuremath{N}}$, then by equation~\eqref{eq:SJlol1}
$$\left\{
\begin{array}{ll}
\pf{W_i \pCond Z_i = 1} \equiv \pf{X,Y} &\mbox{if } Z_i = 1 \\
\pf{W_i \pCond Z_i = 0} \equiv \pf{X}\pf{Y} &\mbox{if } Z_i = 0
\end{array}
\right.$$
\item[\eqref{MDC3}] Moreover, it comes $\pf{W_i} (x,y) = \ratio \pf{X, Y}(x,y) + (1 - \ratio) \pf{X}\pf{Y}$ with $\ratio = \frac{n_J}{\ensuremath{N}}$.
\end{itemize}
\subsection{Proof Theorem \ref{pro:ConsIIDAM} and i.i.d. Construction in the Additional data setting}
\label{Sec:ProofConsIIDAM}
To construct $\mDwz{\ensuremath{N}}= \{(W_i,Z_i)\}_{i = 1, \cdots, \ensuremath{N}}$ a training set of $\ensuremath{N}$ $\ensuremath{i.i.d.}$ observations, we concatenate $3$ datasets denoted $\mDwzRes{\ensuremath{N}_X}$, $\mDwzRes{\ensuremath{N}_Y}$ and $\mDwzRes{\ensuremath{N}_{X,Y}}$ of respective size $\ensuremath{N}_X$, $\ensuremath{N}_Y$ and $\ensuremath{N}_{X,Y}$ such that
$$\mDwz{\ensuremath{N}} = \mDwzRes{\ensuremath{N}_X} \cup \mDwzRes{\ensuremath{N}_Y} \cup \mDwzRes{\ensuremath{N}_{X,Y}}
$$
$$\text{and} \
\left\{\begin{array}{ll}
\ensuremath{N}_X = \min(\ensuremath{n}, \ensuremath{n_x}), &\ensuremath{N}_Y = \min(\ensuremath{n_y}, \ensuremath{n} - \ensuremath{N}_X) \\
\ensuremath{N}_{X,Y} = \ArrB{\frac{\ensuremath{n} - \ensuremath{N}_X - \ensuremath{N}_Y}{2}}, & \ensuremath{N} = \ensuremath{N}_X + \ensuremath{N}_Y + \ensuremath{N}_{X,Y}
\end{array}
\right.
$$
To construct these $3$ preliminary datasets, we first split $$\ensuremath{\mathcal{D}^{X,Y}_n}= \underbrace{\mDxyRes{2\ensuremath{N}_{X,Y}}}_{\text{the first $ 2\ensuremath{N}_{X,Y}$ obs.}} \cup \underbrace{\mDxyRes{\ensuremath{N}_Y}}_{\text{the next $\ensuremath{N}_Y$ obs.}} \cup \underbrace{\mDxyRes{\ensuremath{N}_X}}_{\text{the next $\ensuremath{N}_X$ obs.}} \cup \underbrace{\mathcal{D}}_{\text{the rest.}}
$$
\noindent We consider $\mDxRes{\ensuremath{N}_X}$ and $\mDyRes{\ensuremath{N}_Y}$ the observations in datasets $\ensuremath{\mathcal{D}_{n_x}^{X}}$ and $\ensuremath{\mathcal{D}_{n_y}^{Y}}$ restricted to the $\ensuremath{N}_X$ and $\ensuremath{N}_Y$ first observations respectively.
\vspace{0.5cm}
\noindent
\begin{minipage}{8.5cm}
\begin{mdframed}
\vspace{-0.1cm}
\begin{const}
\label{const:DwzNiidAD}
\big[$\ensuremath{i.i.d.}$ $\mDwz{\ensuremath{N}}$ Additional data\big]
\end{const}
\vspace{-0.1cm}
\end{mdframed}
\end{minipage}
\vspace{0.5cm}
\noindent\textbf{Step (1)}\,\label{stepone3}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
\textbf{Construction of } $\mDwzRes{\ensuremath{N}_{X,Y}}$. If $\ensuremath{N}_{X,Y} = 0$, then $\mDwzRes{\ensuremath{N}_{X,Y}} = \emptyset$, otherwise we construct $\mDwzRes{\ensuremath{N}_{X,Y}}$ from the initial dataset $\mDxRes{\ensuremath{N}_X}$ as described in Construction~\ref{const:DwzNiid}.
\end{minipage}
\end{tabular}
\vspace{0.5cm}
\noindent\textbf{Step (2)}\,\label{steptwo3}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
\textbf{Construction of } $\mDwzRes{\ensuremath{N}_Y}$.First note that if $\ensuremath{N}_Y = 0$, then $\mDwzRes{\ensuremath{N}_Y}= \emptyset$. If $\ensuremath{N}_Y \neq 0$, we proceed as follows:\\
\begin{tabular}[t]{|c}\hspace{-0.5cm}
\begin{minipage}{12cm}
\begin{enumerate}[label=(\roman*)]
\item Sample $\ensuremath{N}_Y$ independent observations $(Z_i)_{i = 1, \cdots, \ensuremath{N}_Y}$ according to a Bernoulli law of parameter $\ratio \in (0,1)$.
\item For all $i = 1, \cdots, \ensuremath{N}_Y$; $\forall (X_i, Y_i) \in \mDxyRes{\ensuremath{N}_Y}$ and $\forall \widetilde{Y}_i \in \mDyRes{\ensuremath{N}_Y}$, set $$W_i = (X_i, Y_{i} \ensuremath{\mathds{1}}_{Z_{i} = 1} + \widetilde{Y}_{i} \ensuremath{\mathds{1}}_{Z_{ i} = 0}).$$
\end{enumerate}
\end{minipage}
\end{tabular}\\
\end{minipage}
\end{tabular}\\
\noindent Note that by construction, $(W_i, Z_{i})_{i=1}^{\ensuremath{N}_Y}$ are $\ensuremath{i.i.d.}$ and follow $\pf{W,Z}$. Moreover, following the same arguments as in proof of Theorem~\ref{pro:ConsIID}, the $\{ (W_i, Z_{i})\}_{i=1}^{\ensuremath{N}_Y}$ satisfy the $\ensuremath{\text{MDcond}}(\ratio)$.
\vspace{0.5cm}
\noindent\textbf{Step (3)}\,\label{stepthree3}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
\textbf{Construction of } $\mDwzRes{\ensuremath{N}_X}$.\\
\begin{tabular}[t]{|c}\hspace{-0.5cm}
\begin{minipage}{12cm}
\begin{enumerate}[label=(\roman*)]
\item Sample $\ensuremath{N}_X$ independent observations $(Z_i)_{i = 1, \cdots, \ensuremath{N}_X}$ according to a Bernoulli law of parameter $\ratio \in (0,1)$.
\item For all $i = 1, \cdots, \ensuremath{N}_X$; $\forall (X_i, Y_i) \in \mDxyRes{\ensuremath{N}_X}$ and $\forall \widetilde{X}_i \in \mDxRes{\ensuremath{N}_X}$, set $$W_i= (X_i \ensuremath{\mathds{1}}_{z = 1}+ \widetilde{X}_i \ensuremath{\mathds{1}}_{z = 0}, Y_i)$$.
\end{enumerate}
\end{minipage}
\end{tabular}
\end{minipage}
\end{tabular}\\
\noindent Note that, by construction $\mDwzRes{\ensuremath{N}_X} = (W_i, Z_{i})_{i=1}^{\ensuremath{N}_X}$ are $\ensuremath{i.i.d.}$ and follow $\pf{W,Z}$. Indeed, the reasoning is similar as in proof of Theorem~\ref{pro:ConsIID}. First construct a random vector $(W,Z)$ satisfying the $\ensuremath{\text{MDcond}}(\ratio)$ with $\ratio \in \ensuremath{(0,1)}$:
\begin{itemize}
\item Let $(X,Y)$ be a random variable admitting $\pf{X,Y}$ as probability density function.
\item Let $Z$ be a random variable following a Bernoulli of parameter $\ratio \in (0,1)$.
\item Let $\widetilde{X}$ be a random variable independent of $(X,Y)$ following the law $\pf{X}$.
\item Set $W = (X_{i} \ensuremath{\mathds{1}}_{Z_{i} = 1} + \widetilde{X}_{i} \ensuremath{\mathds{1}}_{Z_{i} = 0}, Y_i)$.
\end{itemize}
Then, $\forall (x, \widetilde{x},y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}} \times \ensuremath{\mathcal{Y}}$ we have $\forall z \in \{0,1\}$,
$$
\pg{W \pCond Z = z}(x, \widetilde{x},y) = \left\{
\begin{array}{ll}
\pf{X , Y}(x,y) \text{ if }z = 1 \\
\pf{X}(\widetilde{x})\pf{Y}(y) \text{ if }z = 0
\end{array}
\right.$$\\
Then $\forall (x, y, z) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}} \times \{0,1\}$, it comes $$\pf{W \pCond Z = z}(x, y) = \pg{W \pCond Z = z}(x, x,y) = \pf{X , Y}(x,y)\ensuremath{\mathds{1}}_{z = 1}+ \pf{X}(x)\pf{Y}(y) \ensuremath{\mathds{1}}_{z = 0}.$$
Moreover, $\forall (x,y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$; we have by equation~\eqref{eq:SJlol1}:
$$\pf{W}(x, y) = \ratio \pf{X , Y}(x,y) + (1 - \ratio) \pf{X}(x)\pf{Y}(y).$$
So $(W, Z)$ satisfies the $\ensuremath{\text{MDcond}}(\ratio)$.
\vspace{0.5cm}
\noindent\textbf{Step (4)}\,\label{stepfour3}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
\textbf{Concatenation.} Concatenate the $3$ datasets $\mDwzRes{\ensuremath{N}_X}$, $\mDwzRes{\ensuremath{N}_Y}$ and $\mDwzRes{\ensuremath{N}_{X,Y}}$
\end{minipage}
\end{tabular}\\
\vspace{0.5cm}
\noindent To conclude our proof, note that :\\
$\bullet$ Since $\mDxyRes{2\ensuremath{N}_{X,Y}}$, $(\mDxyRes{\ensuremath{N}_X},\mDxRes{\ensuremath{N}_X})$ and $(\mDxyRes{\ensuremath{N}_Y}, \mDyRes{\ensuremath{N}_Y})$ are independent, the datasets $\mDwzRes{\ensuremath{N}_X}$, $\mDwzRes{\ensuremath{N}_Y}$ and $\mDwzRes{\ensuremath{N}_{X,Y}}$ are independent by construction.\\
$\bullet$ Moreover, since $\mDwzRes{\ensuremath{N}_X}$, $\mDwzRes{\ensuremath{N}_Y}$ and $\mDwzRes{\ensuremath{N}_{X,Y}}$ are composed by $\ensuremath{i.i.d.}$ random variables following the law $\pf{W, Z}$, the sample of size $\ensuremath{N} = \ensuremath{N}_{X,Y}+ \ensuremath{N}_X + \ensuremath{N}_Y$,
$$\mDwz{\ensuremath{N}} =\mDwzRes{\ensuremath{N}_X} \cup \mDwzRes{\ensuremath{N}_Y}\cup \mDwzRes{\ensuremath{N}_{X,Y}} $$
is composed by $\ensuremath{i.i.d.}$ random variables following the law $\pf{W, Z}$.
\begin{minipage}{4.3cm}
\begin{mdframed}
\vspace{-0.1cm}
\!\!\!\textbf{Construction of } $\mDwzRes{\ensuremath{N}_{X,Y}}$.
\vspace{-0.4cm}
\end{mdframed}
\end{minipage}\\
\vspace{0.3cm}
If $\ensuremath{N}_{X,Y} = 0$, then $\mDwzRes{\ensuremath{N}_{X,Y}} = \emptyset$, otherwise we construct $\mDwzRes{\ensuremath{N}_{X,Y}}$ from the initial dataset $\mDxRes{\ensuremath{N}_X}$ as described in Construction~\ref{const:DwzNiid} (see the proof of Theorem~\ref{pro:ConsIID}).\\
\\
\begin{minipage}{4.3cm}
\begin{mdframed}
\vspace{-0.1cm}
\!\!\!\textbf{Construction of } $\mDwzRes{\ensuremath{N}_Y}$.
\vspace{-0.4cm}
\end{mdframed}
\end{minipage}\vspace{0.3cm}\\
First note that if $\ensuremath{N}_Y = 0$, then $\mDwzRes{\ensuremath{N}_Y}= \emptyset$. If $\ensuremath{N}_Y \neq 0$, we proceed as follows:\\
\begin{tabular}[t]{|c}\hspace{-0.5cm}
\begin{minipage}{12cm}
\begin{enumerate}[label=(\roman*)]
\item Sample $\ensuremath{N}_Y$ independent observations $(Z_i)_{i = 1, \cdots, \ensuremath{N}_Y}$ according to a Bernoulli law of parameter $\ratio \in (0,1)$.
\item For all $i = 1, \cdots, \ensuremath{N}_Y$; $\forall (X_i, Y_i) \in \mDxyRes{\ensuremath{N}_Y}$ and $\forall \widetilde{Y}_i \in \mDyRes{\ensuremath{N}_Y}$, set $$W_i = (X_i, Y_{i} \ensuremath{\mathds{1}}_{Z_{i} = 1} + \widetilde{Y}_{i} \ensuremath{\mathds{1}}_{Z_{ i} = 0}).$$
\end{enumerate}
\end{minipage}
\end{tabular}\\
\\
Note that by construction, $(W_i, Z_{i})_{i=1}^{\ensuremath{N}_Y}$ are $\ensuremath{i.i.d.}$ and follow $\pf{W,Z}$. Moreover, following the same arguments as in proof of Theorem~\ref{pro:ConsIID}, the $\{ (W_i, Z_{i})\}_{i=1}^{\ensuremath{N}_Y}$ satisfy the $\ensuremath{\text{MDcond}}(\ratio)$.\\
\\
\noindent
\begin{minipage}{4.3cm}
\begin{mdframed}
\vspace{-0.1cm}
\!\!\!\textbf{Construction of } $\mDwzRes{\ensuremath{N}_X}$.
\vspace{-0.4cm}
\end{mdframed}
\end{minipage}\\
\vspace{0.3cm}
First note that if $\ensuremath{N}_X = 0$, then $\mDwzRes{\ensuremath{N}_X}= \emptyset$. If $\ensuremath{N}_X \neq 0$, we consider the datasets $\mDxyRes{\ensuremath{N}_X}$ and $\mDxRes{\ensuremath{N}_X}$, and proceed as follows:\\
First construct a random vector $(W,Z)$ satisfying the $\ensuremath{\text{MDcond}}(\ratio)$ with $\ratio \in \ensuremath{(0,1)}$ following a similar reasoning as in proof of Theorem~\ref{pro:ConsIID}:
\begin{itemize}
\item Let $(X,Y)$ be a random variable admitting $\pf{X,Y}$ as probability density function.
\item Let $Z$ be a random variable following a Bernoulli of parameter $\ratio \in (0,1)$.
\item Let $\widetilde{X}$ be a random variable independent of $(X,Y)$ following the law $\pf{X}$.
\item Set $W = (X_{i} \ensuremath{\mathds{1}}_{Z_{i} = 1} + \widetilde{X}_{i} \ensuremath{\mathds{1}}_{Z_{i} = 0}, Y_i)$.
\end{itemize}
Then, $\forall (x, \widetilde{x},y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}} \times \ensuremath{\mathcal{Y}}$ we have $\forall z \in \{0,1\}$,
$$
\pg{W \pCond Z = z}(x, \widetilde{x},y) = \left\{
\begin{array}{ll}
\pf{X , Y}(x,y) \text{ if }z = 1 \\
\pf{X}(\widetilde{x})\pf{Y}(y) \text{ if }z = 0
\end{array}
\right.$$\\
Then $\forall (x, y, z) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}} \times \{0,1\}$, it comes $$\pf{W \pCond Z = z}(x, y) = \pg{W \pCond Z = z}(x, x,y) = \pf{X , Y}(x,y)\ensuremath{\mathds{1}}_{z = 1}+ \pf{X}(x)\pf{Y}(y) \ensuremath{\mathds{1}}_{z = 0}.$$
Moreover, $\forall (x,y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$; we have by equation~\eqref{eq:SJlol1}:
$$\pf{W}(x, y) = \ratio \pf{X , Y}(x,y) + (1 - \ratio) \pf{X}(x)\pf{Y}(y).$$
So $(W, Z)$ satisfies the $\ensuremath{\text{MDcond}}(\ratio)$.\\
\begin{tabular}[t]{|c}\hspace{-0.5cm}
\begin{minipage}{12cm}
\begin{enumerate}[label=(\roman*)]
\item Sample $\ensuremath{N}_X$ independent observations $(Z_i)_{i = 1, \cdots, \ensuremath{N}_X}$ according to a Bernoulli law of parameter $\ratio \in (0,1)$.
\item For all $i = 1, \cdots, \ensuremath{N}_X$; $\forall (X_i, Y_i) \in \mDxyRes{\ensuremath{N}_X}$ and $\forall \widetilde{X}_i \in \mDxRes{\ensuremath{N}_X}$, set $$W_i= (X_i \ensuremath{\mathds{1}}_{z = 1}+ \widetilde{X}_i \ensuremath{\mathds{1}}_{z = 0}, Y_i)$$.
\end{enumerate}
\end{minipage}
\end{tabular}\\
Note that, by construction $\mDwzRes{\ensuremath{N}_X} = (W_i, Z_{i})_{i=1}^{\ensuremath{N}_X}$ are $\ensuremath{i.i.d.}$ and follow $\pf{W,Z}$.\\
\\
\noindent
\begin{minipage}{4.3cm}
\begin{mdframed}
\vspace{-0.1cm}
\!\!\!\textbf{Concatenation.}
\end{mdframed}
\end{minipage}\\
\vspace{0.1cm}
Now to conclude our proof, note that $\mDwzRes{\ensuremath{N}_X}$, $\mDwzRes{\ensuremath{N}_Y}$ and $\mDwzRes{\ensuremath{N}_{X,Y}}$ are independent by construction, since $\mDxyRes{2\ensuremath{N}_{X,Y}}$, $(\mDxyRes{\ensuremath{N}_X},\mDxRes{\ensuremath{N}_X})$ and $(\mDxyRes{\ensuremath{N}_Y}, \mDyRes{\ensuremath{N}_Y})$ are independent. Moreover, since $\mDwzRes{\ensuremath{N}_X}$, $\mDwzRes{\ensuremath{N}_Y}$ and $\mDwzRes{\ensuremath{N}_{X,Y}}$ samples are $\ensuremath{i.i.d.}$ random variables following the law $\pf{W, Z}$ we have $\mDwz{\ensuremath{N}} =\mDwzRes{\ensuremath{N}_X} \cup \mDwzRes{\ensuremath{N}_Y}\cup \mDwzRes{\ensuremath{N}_{X,Y}} $ a training set of $\ensuremath{N} = \ensuremath{N}_{X,Y}+ \ensuremath{N}_X + \ensuremath{N}_Y$ $\ensuremath{i.i.d.}$ samples following the law $\pf{W, Z}$.
\subsection{Proof Theorem~\ref{pro:ConsUIDAM} and i.d. Construction in the Additional data setting}
\label{Sec:ProofConsUIDAM}
Let $n_J$ and $n_M$ two integers such that $1 \leq n_J \leq \ensuremath{n}$ and $1 \leq n_M \leq (\ensuremath{n} + \ensuremath{n_x})(\ensuremath{n} + \ensuremath{n_y}) - \ensuremath{n}$.
\vspace{0.5cm}
\noindent
\begin{minipage}{8.5cm}
\begin{mdframed}
\vspace{-0.1cm}
\begin{const}
\label{const:DwzNidAD}
\big[$\ensuremath{i.d.}$ $\mDwz{\ensuremath{N}}$ Additional data\big]
\end{const}
\vspace{-0.1cm}
\end{mdframed}
\end{minipage}
\vspace{0.5cm}
\noindent The construction is the same as in the proof of Theorem~\ref{pro:ConsUID}, except we replace \textbf{Step (1)}\, in Construction~\ref{const:DwzNid} with \textbf{Step (1-bis)}\, detailed below.
\vspace{0.5cm}
\noindent\textbf{Step (1-bis)}\,\label{stepone4}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
We first generate $(\ensuremath{n} + \ensuremath{n_x})(\ensuremath{n} + \ensuremath{n_y})$ observations $\{(W_i,Z_i)\}_{i = 1, \cdots, (\ensuremath{n} + \ensuremath{n_x})(\ensuremath{n} + \ensuremath{n_y})}$ by concatenating $4$ sets of samples denoted $\ensuremath{\mathcal{S}}$, $\ensuremath{\mathcal{S}^{\widetilde{X}}}$, $\ensuremath{\mathcal{S}^{\widetilde{Y}}}$ and $\ensuremath{\mathcal{S}^{\widetilde{X},\widetilde{Y}}}$ of size $\ensuremath{n}^2$, $\ensuremath{n} \times \ensuremath{n_x}$, $\ensuremath{n} \times \ensuremath{n_y}$ and $\ensuremath{n_x} \times \ensuremath{n_y}$ respectively.
\vspace{0.5cm}
\textbf{(A)}\,\label{steponeb} \quad \begin{tabular}[t]{||l}
\begin{minipage}[t]{10cm}
Generate the set of samples $\ensuremath{\mathcal{S}}$ exactly like in \textbf{Step (1)}\, of the Construction~\ref{const:DwzNid}.
\end{minipage}
\end{tabular}
\vspace{0.5cm}
\textbf{(B)}\, \quad \begin{tabular}[t]{||l}
\begin{minipage}[t]{10cm}
Construct the set of samples $\ensuremath{\mathcal{S}^{\widetilde{X}}} = \{(W_i,Z_i)\}_{i = 1, \cdots, \ensuremath{n}\times \ensuremath{n_x} }$ of size $\ensuremath{n} \times \ensuremath{n_x}$ as follows:
$\forall j = 0, \cdots, \ensuremath{n} - 1, \, \forall k = 1, \cdots, \ensuremath{n_x}$,
$$
\left\{
\begin{array}{ll}
W_{ j \ensuremath{n_x} + k} = (\widetilde{X}_{k}, Y_{\ensuremath{n}^2 + j + 1}) \\
Z_{ j \ensuremath{n_x} + k} = 0
\end{array}
\right.
$$
\end{minipage}
\end{tabular}
\end{minipage}
\end{tabular}\\
\noindent Since $\ensuremath{\mathcal{D}_{n_x}^{X}}$ and $\ensuremath{\mathcal{D}^{X,Y}_n}$ are independent and their respective elements are $\ensuremath{i.i.d.}$, we have $\forall i = 1 , \cdots , \ensuremath{n}^2 $, $\pf{W_i} \equiv \pf{X}\pf{Y}$.
\vspace{0.5cm}
\hspace{1.8cm} \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
\textbf{(C)}\,\quad \begin{tabular}[t]{||l}
\begin{minipage}[t]{10cm}
Construct the set of samples $\ensuremath{\mathcal{S}^{\widetilde{Y}}} = \{(W_i,Z_i)\}_{i = 1, \cdots, \ensuremath{n}\times \ensuremath{n_y}}$ of size $\ensuremath{n} \times \ensuremath{n_y}$ as follows: $\forall j = 0, \cdots, \ensuremath{n} - 1, \, \forall k = 1, \cdots, \ensuremath{n_y}$,
$$
\left\{
\begin{array}{ll}
W_{ j \ensuremath{n_y} + k} = (X_{ j + 1}, \widetilde{Y}_{k}) \\
Z_{ j \ensuremath{n_y} + k} = 0
\end{array}
\right.
$$
\end{minipage}
\end{tabular}
\end{minipage}
\end{tabular}\\
\noindent Since $\ensuremath{\mathcal{D}_{n_y}^{Y}}$ and $\ensuremath{\mathcal{D}^{X,Y}_n}$ are independent and their respective elements are $\ensuremath{i.i.d.}$, we have $\forall i = 1, \cdots , \ensuremath{n}\times \ensuremath{n_y}$, $\pf{W_i} \equiv \pf{X}\pf{Y}$.
\vspace{0.5cm}
\hspace{1.8cm} \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
\textbf{(D)}\,\quad \begin{tabular}[t]{||l}
\begin{minipage}[t]{10cm}
Construct the set of samples $\ensuremath{\mathcal{S}^{\widetilde{X},\widetilde{Y}}} =\{(W_i,Z_i)\}_{i = 1, \cdots, \ensuremath{n_x} \ensuremath{n_y} }$ of size $\ensuremath{n_x} \times \ensuremath{n_y}$ as follows: $\forall j = 0, \cdots, \ensuremath{n_x} - 1, \, \forall k = 1, \cdots, \ensuremath{n_y}$,
$$
\left\{
\begin{array}{ll}
W_{ j \ensuremath{n_y} + k} = (\widetilde{X}_{j + 1}, \widetilde{Y}_{k}) \\
Z_{ j \ensuremath{n_y} + k} = 0
\end{array}
\right.
$$
\end{minipage}
\end{tabular}
\end{minipage}
\end{tabular}\\
\noindent Since $\ensuremath{\mathcal{D}_{n_x}^{X}}$ and $\ensuremath{\mathcal{D}_{n_y}^{Y}}$ are independent and their respective elements are $\ensuremath{i.i.d.}$, we have $\forall i = 1, \cdots, \ensuremath{n_x} \ensuremath{n_y}$, $\pf{W_i} \equiv \pf{X}\pf{Y}$.
\vspace{0.5cm}
\hspace{1.8cm} \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
\textbf{(E)}\,\quad \begin{tabular}[t]{||l}
\begin{minipage}[t]{10cm}
Finally, concatenate $\ensuremath{\mathcal{S}}$, $\ensuremath{\mathcal{S}^{\widetilde{X}}}$, $\ensuremath{\mathcal{S}^{\widetilde{Y}}}$ and $\ensuremath{\mathcal{S}^{\widetilde{X},\widetilde{Y}}}$ which ends the \textbf{Step (1-bis)}\,.
\end{minipage}
\end{tabular}
\end{minipage}
\end{tabular}\\
\vspace{0.5cm}
\noindent\textbf{(Next-Step)}\,\label{stepfour31}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
Next, do \textbf{Step (2)}\,, \textbf{Step (3)}\,, \textbf{Step (4)}\, and \textbf{Step (5)}\, of the Construction~\ref{const:DwzNid}.
\end{minipage}
\end{tabular}
\vspace{0.5cm}
\noindent Using the same arguments as in the proof of Theorem~\ref{pro:ConsUID}, $\mDwz{\ensuremath{N}}$ satisfies the $\ensuremath{\text{MDcond}}(\ratio)$.
Since $\forall i = \ensuremath{n}^2 +1, \cdots, (\ensuremath{n_x} + \ensuremath{n}) (\ensuremath{n_y} + \ensuremath{n})$, we have $\pf{W_i} \equiv \pf{X}\pf{Y}$ and $Z_i = 0$. Therefore $\forall i = 1, \cdots , (\ensuremath{n_x} + \ensuremath{n}) (\ensuremath{n_y} + \ensuremath{n})$, $\pf{W_i} \equiv \pf{X,Y} \ensuremath{\mathds{1}}_{Z_i = 1} + \pf{X}\pf{Y} \ensuremath{\mathds{1}}_{Z_i = 0}$.
\subsection{Proof Theorem~\ref{pro:ConsUIDMT} and Construction in the non-independent case}
\label{Sec:ProofConsUIDMT}
Let $n_J$ and $n_M$ two integers such that $1 \leq n_J \leq \ensuremath{n} \times \ensuremath{m}$ and $1 \leq n_M \leq \ensuremath{n}(\ensuremath{n}-1)\ensuremath{m}$. We construct the final dataset similary to Construction~\ref{const:DwzNid}, except we replace \textbf{Step (1)}\, with \textbf{Step (1-ter)}\,:\\
\noindent
\begin{minipage}{8.5cm}
\begin{mdframed}
\vspace{-0.1cm}
\begin{const}
\label{const:DwzNidFram3}
\big[$\ensuremath{i.d.}$ $\mDwz{\ensuremath{N}}$ Framework~\ref{DATA3}\big]
\end{const}
\vspace{-0.1cm}
\end{mdframed}
\end{minipage}
\vspace{0.5cm}
\noindent\textbf{Step (1-ter)}\,\label{stepone5}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
Construct $\ensuremath{n}^2\ensuremath{m}$ observations $\{(W_i,Z_i)\}_{i = 1, \cdots, \ensuremath{n}^2\ensuremath{m}}$ such that:
$$
\begin{array}{ll}
\forall j = 0, \cdots, \ensuremath{n} - 1, \,& \forall k = 1, \cdots, \ensuremath{n} \, \forall l = 1, \cdots, \ensuremath{m}, \, \\
& \left\{
\begin{array}{ll}
W_{(j \ensuremath{n} + k)\ensuremath{m} + l} = (X_{j+1}, Y^k_{l}) \\
Z_{(j \ensuremath{n} + k)\ensuremath{m} + l} = \ensuremath{\mathds{1}}_{j+1 = k}
\end{array}
\right.
\end{array}
$$
\end{minipage}
\end{tabular}
\vspace{0.5cm}
\noindent\textbf{(Next-Step)}\,\label{stepfour32}: \quad \begin{tabular}[t]{|l}
\begin{minipage}[t]{10cm}
Next, do {}\textbf{Step (2)}\,, \textbf{Step (3)}\,, \textbf{Step (4)}\, and \textbf{Step (5)}\, of the Construction~\ref{const:DwzNid}.
\end{minipage}
\end{tabular}\\
\noindent Since $\forall j = 0, \cdots, \ensuremath{n} - 1, \, \forall k = 1, \cdots, \ensuremath{n}, \,\, \forall l = 1, \cdots, \ensuremath{m},$
$$
X_{j+1} \perp \!\!\! \perp Y^k_{l} \ iff \ j+1 \neq k,
$$
we can use the same arguments as in the proof of Theorem~\ref{pro:ConsUID} to show that $\forall i = 1, \cdots , \ensuremath{N},$ the couple $(W_i, Z_i) \in \mDwz{\ensuremath{N}}$ satisfies the $\ensuremath{\text{MDcond}}\left(\frac{n_J}{\ensuremath{N}}\right)$.
\section{Introduction}
\input{Introduction}
\section{Marginal Contrastive Discrimination}\label{Sec:theory}
\subsection{Setting}
In this article\,, we consider three frameworks corresponding to three different situation in practice.
\begin{mdframed}
\begin{mydata}\label{DATA1}\textbf{[Independent Identically Distributed Samples]}\\
In this most classic setting, we consider $\ensuremath{\mathcal{D}^{X,Y}_n} = \{(X_i, Y_i) \}_{i=1,\cdots, \ensuremath{n}}\,$ a training dataset of size $\ensuremath{n} \in \ensuremath{\mathbbm{N}}^*$ such that $\forall i = 1, \cdots, \ensuremath{n}$, the $(X_i, Y_i)$ are $\ensuremath{i.i.d.}$ of density $\pf{X,Y}$.
\end{mydata}
\end{mdframed}
\medskip
In practice, it is often the case that additional observations are available but without the associated target values and vice versa (Framework~\ref{DATA2}). In this article\, we show that it is possible to take advantage of these additional samples to increase the size of the training dataset without using any additional unsupervised learning techniques.\\
\begin{mdframed}
\begin{mydata}\label{DATA2}\textbf{[Additional Marginal Data]}
\noindent\\
\noindent In this framework, we still consider a $\ensuremath{i.i.d.}$ training dataset of size $\ensuremath{n} \in \ensuremath{\mathbbm{N}}^*$ of density $\pf{X,Y}$ denoted $\ensuremath{\mathcal{D}^{X,Y}_n} = \{(X_i, Y_i) \}_{i=1,\cdots, \ensuremath{n}}$. Moreover we assume we have one or two additional datasets.
\begin{itemize}
\item Let $\ensuremath{\mathcal{D}_{n_x}^{X}} = \{\widetilde{X}_i \}_{i=1,\cdots, \ensuremath{n_x}}$ be $\ensuremath{i.i.d.}$ an additional dataset of size $\ensuremath{n_x} \in \ensuremath{\mathbbm{N}}$ of density $\pf{X}$.
\item Let $\ensuremath{\mathcal{D}_{n_y}^{Y}} = \{\widetilde{Y}_i \}_{i=1,\cdots, \ensuremath{n_y}}$ be $\ensuremath{i.i.d.}$ an additional dataset of size $\ensuremath{n_y} \in \ensuremath{\mathbbm{N}}$ of density $\pf{Y}$.
\end{itemize}
We assume that $\ensuremath{\mathcal{D}^{X,Y}_n}$, $\ensuremath{\mathcal{D}_{n_x}^{X}}$ and $\ensuremath{\mathcal{D}_{n_y}^{Y}}$ are independent.
\end{mydata}
\end{mdframed}
\medskip
Let us introduce a last framework, the one where more than one target value is associated to the same observation. To our knowledge, the article of (\cite{bott_nonparametric_2017}) is the only attempt to deal with this case. We show in this article\, that our method can exploit and take advantage of these additional targets, again, without requiring an additional learning scheme. This can be the case for example in mechanics when performing fatigue analysis (\cite{bott_nonparametric_2017,manson_fatigue_1965}).\\
\begin{mdframed}
\begin{mydata}\label{DATA3}\textbf{[Multiple Target per Sample]}\\
Let $(X, \mathbb{Y})$ be a couple of random variables taking values in $\ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}^\ensuremath{m}$ of density $\pf{X, \mathbb{Y} }$. Let $\ensuremath{\mathcal{D}_{n,m}^{X,\mathbb{Y}}} = \{(X_i,\mathbb{Y}_i) \}_{i= 1}^{\ensuremath{n}}$ a training dataset of size $\ensuremath{n} \in \ensuremath{\mathbbm{N}}^*$ such that
\begin{itemize}
\item The $\{X_i \}_{i = 1, \cdots, \ensuremath{n}}$ are sampled such that the $X_i$ are $\ensuremath{i.i.d.}$ of density $\pf{X}$.
\item The $\{\mathbb{Y}_i \}_{i = 1, \cdots, \ensuremath{n}}$ are sampled such that the $\mathbb{Y}_i \pCond X_i$ are $\ensuremath{i.i.d.}$ of density $\pf{\mathbb{Y} \pCond X}$.
\end{itemize}
\end{mydata}
\end{mdframed}
\subsection{Contrast function}
Our method, \textbf{MCD}\,, is grounded on a trivial approached based on the successive application of the Bayes' formula \eqref{eq:Bayes0}. \\
We reformulate the problem differently from the existing noise contrastive methods, focusing on the contrast between the joint law $\pf{X,Y}$ and the marginal laws $\pf{X}$ and $\pf{Y}$. To do this, we define (Definition~\ref{def:MCF}) a new contrast $q(\cdot,\cdot)$, called the marginal contrast function.
\begin{mdframed}
\begin{mydef}\label{def:MCF}\textbf{[Marginal Contrast function $\ensuremath{\textbf{MCF}}(\ratio)$]}\\
Let $\ratio \in \ensuremath{(0,1)}$ be a real number. Consider $(X,Y)$ a couple of random variables taking values in $\ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$. The Marginal Contrast Function with ratio $\ratio$ of the couple $(X,Y)$, denoted $q(\cdot,\cdot)$, is defined as:
\begin{align*}
\ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}} &\ensuremath{\longrightarrow} \ensuremath{[0,1)} \\
(x, y) &\ensuremath{\longmapsto} q(x,y) := \frac{\ratio \pf{X,Y}(x,y)}{\ratio\pf{X,Y}(x,y) + (1-\ratio)\pf{X}(x)\pf{Y}(y)}.
\end{align*}
\end{mydef}
\end{mdframed}
\medskip
This new contrast is motivated by the Fact~\ref{fac:MCF}: \textbf{CDE}\, is equivalent to the marginal density of $Y$ and the marginal contrast function $q$. The \textbf{CDE}\,{} task is therefore reduced to the estimation of the constrast and a marginal density.\\
\begin{mdframed}
\begin{myfac}\label{fac:MCF}
Let $\ratio \in \ensuremath{(0,1)}$ be a real number. Consider $(X,Y)$ a couple of random variables taking values in $\ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$. For all $(x, y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$, we have
$$
\pf{Y\pCond X = x}(y) = \pf{Y}(y) \frac{q(x,y)}{1-q(x,y)} \frac{1-\ratio}{\ratio}
$$
where $q(\cdot,\cdot)$ denotes the $\ensuremath{\textbf{MCF}}(\ratio)$.
\end{myfac}
\end{mdframed}
\medskip
In the next section, we determine the conditions (Marginal Discrimination Conditions) under which the contrast function estimation can be transformed into an easy supervised learning estimation problem.
\subsection{Marginal Discrimination Conditions}
To transform the problem of estimating $q$ into a problem of supervised learning, we first need to introduce a couple of random variables $(W, Z)$ satisfying the Marginal Discrimination Condition ($\ensuremath{\text{MDcond}}$) of the couple $(X,Y)$ with ratio $\ratio\in(0,1)$.\\
\begin{mdframed}
\begin{mydef}\label{def:MDC}\textbf{[Marginal Discrimination Condition $\ensuremath{\text{MDcond}}(\ratio)$]}\\
Let $\ratio \in \ensuremath{(0,1)}$ be a real number. Consider $(X,Y)$ two random variables taking values in $\ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$. A couple of random variables $(W, Z)$ is said to satisfy the Marginal Discrimination Condition ($\ensuremath{\text{MDcond}}$) of the couple $(X,Y)$ with ratio $\ratio$ if
\begin{enumerate}[label=(\textbf{Cd~\arabic*})]
\item\label{MDC1} The random variable $Z$ follows a Bernoulli law of parameter $\ratio$ ($Z \sim \pBB(r)$).
\item \label{MDC2} The support of $W$ is $\,\mathcal{W} = \mathcal{X} \times \mathcal{Y}$.
\item \label{MDC3} For all $
(x,y) \in \mathcal{X} \times \mathcal{Y},$ we have $\pf{W }(x,y) = \ratio\pf{X,Y}(x,y)+ (1-\ratio)\pf{X}(x)\pf{Y}(y).
$
\item \label{MDC4} For all $
(x,y,z) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}} \times \ensuremath{\{0;1\}}$, we have
$$ \pf{W \pCond Z=z}(x,y) = \ensuremath{\mathds{1}}_{z = 1}\pf{X,Y}(x,y)+ \ensuremath{\mathds{1}}_{z = 0}\pf{X}(x)\pf{Y}(y).
$$
\end{enumerate}
\end{mydef}
\end{mdframed}
Remark that condition \ref{MDC3} is satisfied if conditions \ref{MDC1},\ref{MDC2} and \ref{MDC4} are verified. These conditions are sufficient to characterise both the joint and marginal laws of the couple $(W, Z)$.
\paragraph{Estimation of the contrast function through supervised learning}
The Proposition~\ref{pro:equiv} specifies how the marginal contrast function $q$ problem can be estimated by a supervised learning task, using either a regressor or a binary classifier, provided that we have access to a sample of identically distributed ($\ensuremath{i.d.}$) of random variables that satisfies the $\ensuremath{\text{MDcond}}(\ratio)$.\\
\begin{mdframed}
\begin{mypropo}\label{pro:equiv}\textbf{[Constrast Estimation]}\\
Let $\ratio \in \ensuremath{(0,1)}$ be a real number. Consider $(X,Y)$ a couple of random variables taking value in $\ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$. For all $(x, y) \in \ensuremath{\mathcal{X}} \times \ensuremath{\mathcal{Y}}$, the Marginal Contrast Function of couple $(X,Y)$ with ratio $r$ denoted by $q$
satisfies the following property:
$$
q(x,y) = \ensuremath{\mathbb{E}}[Z \pCond W = (x,y)] = \ensuremath{\mathbb{P}}[Z = 1 \pCond W = (x,y)].
$$
\end{mypropo}
\end{mdframed}
The proof is given in section~\ref{sec:Proofequiv}. It remains to prove that it is possible to construct a training set of identically distributed $(\ensuremath{i.d.}$) samples of $(W, Z)$ using the elements of the original dataset.
\section{Contrast datasets construction}
\subsection{Classical Dataset (Framework~\ref{DATA1})}
Theorem~\ref{pro:ConsIID} establishes the existence of an $\ensuremath{i.i.d.}$ sample of $(W, Z)$ satisfying the $\ensuremath{\text{MDcond}}(\ratio)$ in Framework~\ref{DATA1}. In its proof (section~\ref{Sec:ProofConsIID}), such of construction based on the original data set is derived. From now and for all $\alpha \in \ensuremath{\mathbbm{R}}$, the quantity $\ArrB{\alpha}$ denote the largest integer value smaller or equal to $\alpha$.
\begin{mdframed}
\begin{mytheo}\textbf{[Construction of an $\ensuremath{i.i.d.}$ training Set]}\\
\label{pro:ConsIID}
Let $\ratio \in \ensuremath{(0,1)}$ be a real number. Consider the dataset $\ensuremath{\mathcal{D}^{X,Y}_n}$ defined in Framework~\ref{DATA1}.\\
\noindent Then, we can construct a dataset $\mDwz{\ensuremath{N}} = \{(W_i, Z_i) \}_{i=1,\cdots, \ensuremath{N}}\,$ of size $\ensuremath{N} = \ArrB{\ensuremath{n}/2}$ of $\ensuremath{i.i.d.}$ observations
satisfying the $\ensuremath{\text{MDcond}}(\ratio)$.
\end{mytheo}
\end{mdframed}
\medskip
Note that, in practice, having access to a larger data set improves the results considerably. By dispensing with the independence property, it is possible to construct a much larger data set without deteriorating the results (see numerical experiments). This is the purpose of Theorem~\ref{pro:ConsUID}\\
\begin{mdframed}
\begin{mytheo}\label{pro:ConsUID}\textbf{[Construction of a larger $\ensuremath{i.d.}$ training Set]}\\
Consider the dataset $\ensuremath{\mathcal{D}^{X,Y}_n}$ defined in Framework~\ref{DATA1}.
Moreover, assume that $\ensuremath{\mathcal{D}^{X,Y}_n}$ is such that $\forall (i,j) \in \{1,\cdots,\ensuremath{n}\}^2$ with $i \neq j$
$$
X_i \neq X_j \ and \ Y_i \neq Y_j
$$
\noindent
Then, for any couple of integers $(n_J,n_M)$ such that
$$\left\{
\begin{array}{l}
1 \leq n_J \leq \ensuremath{n}\\
1 \leq n_M \leq \ensuremath{n}(\ensuremath{n} - 1)
\end{array}
\right.
$$
we can construct a dataset $\mDwz{\ensuremath{N}} = \{(W_i, Z_i) \}_{i=1,\cdots, \ensuremath{N}}$ of size $\ensuremath{N} = n_J + n_M$ of $\ensuremath{i.d.}$ random
observations
satisfying the $\ensuremath{\text{MDcond}}\left(\frac{n_J}{\ensuremath{N}}\right)$.
\end{mytheo}
\end{mdframed}
\medskip
Note first that we can at most construct a dataset of size $\ensuremath{N} = \ensuremath{n}^2$, with $r = \frac{1}{\ensuremath{n}}$. On the other hand, if we want to have $r = \frac{1}{2}$, we can generate a dataset of size $\ensuremath{N} = 2\ensuremath{n}$.
Second, the additional conditions on the dataset are introduced to exclude the trivial case where a larger dataset is constructed by simply repeating the existing samples. In practice, we can always avoid this case by removing redundant samples. Note, however, that the repetition of values occurs with probability $0$, almost surely, because we consider continuous densities.
Finally, the complete construction of such a dataset is described in section~\ref{Sec:ProofConsUID}
\subsection{Additional Marginal Data (Framework~\ref{DATA2})}
Now consider that we have additional features and/or targets for which the target or associated feature is not available. We include this additional data in our training process without using a semi-supervised scheme.\\
\begin{mdframed}
\begin{mytheo}\label{pro:ConsIIDAM}\textbf{[Construction of an $\ensuremath{i.i.d.}$ training set]}\\
Let $\ratio \in \ensuremath{(0,1)}$ be a real number. Consider the datasets defined in Framework~\ref{DATA2}. Set
$$\ensuremath{N} = min\left(\ensuremath{n}, \ArrB{\frac{\ensuremath{n} + \ensuremath{n_x} + \ensuremath{n_y}}{2}}\right),
$$
\noindent then, we can construct $\mDwz{\ensuremath{N}} = \{(W_i, Z_i) \}_{i=1,\cdots, \ensuremath{N}}$ a dataset of size $\ensuremath{N}$ of $\ensuremath{i.i.d.}$ observations satisfying the $\ensuremath{\text{MDcond}}(\ratio)$.
\end{mytheo}
\end{mdframed}
\medskip
This theorem implies that as soon as we have $\ensuremath{n_x} + \ensuremath{n_y} \geq \ensuremath{n}$, we can generate a training set for the discriminator as large as the original set, i.e. $\ensuremath{N} = \ensuremath{n}$. In practice, this can happen in many cases. For example, when data annotation is expensive or difficult, we often have $\ensuremath{n_x} >> \ensuremath{n}$. At the same time, to use contrastive marginal discrimination to estimate the conditional density, we need to know or estimate the marginal density $\pf{Y}$. The proof of this theorem is done in section~\ref{Sec:ProofConsIIDAM}\\
\begin{mdframed}
\begin{mytheo}\label{pro:ConsUIDAM}\textbf{[Construction of a larger $\ensuremath{i.d.}$ training set]}\\
Consider the dataset defined in Framework~\ref{DATA3}. Moreover assume \\
\noindent$\bullet$ The dataset $\ensuremath{\mathcal{D}^{X,Y}_n}$ is such that $\forall (i,j) \in \{1,\cdots,\ensuremath{n}\}^2$ $s.t.$ $i \neq j$
$$
X_i \neq X_j \ and \ Y_i \neq Y_j.
$$
$\bullet$ The datasets $\ensuremath{\mathcal{D}_{n_x}^{X}}{\ensuremath{n_x}}$ and $\ensuremath{\mathcal{D}_{n_y}^{Y}}{\ensuremath{n_y}}$ are $s.t.$ $\forall (i,j) \in\{1,\cdots,\ensuremath{n_x}\}^2$ and $\forall (i',j') \in \{1,\cdots,\ensuremath{n_y}\}^2$
$$
\widetilde{X}_i \neq \widetilde{X}_j \ and \ \widetilde{Y}_{i'} \neq \widetilde{Y}_{j'}
$$
$\bullet$ Moreover, we assume that $\ensuremath{\mathcal{D}^{X,Y}_n}$, $\ensuremath{\mathcal{D}_{n_x}^{X}}$ and $\ensuremath{\mathcal{D}_{n_y}^{Y}}$ are such that $\forall (i,i') \in \{1,\cdots,\ensuremath{n}\}\times \{1,\cdots,\ensuremath{n_x}\}$ and $\forall (j,j') \in \{1,\cdots,\ensuremath{n}\}\times \{1,\cdots,\ensuremath{n_y}\}$
$$
X_i \neq \widetilde{X}_{i'} \ and \ Y_j \neq \widetilde{Y}_{j'}
$$
Then, for any couple of integers $(n_J,n_M)$ such that
$$\left\{
\begin{array}{l}
1 \leq n_J \leq \ensuremath{n}\\
1 \leq n_M \leq (\ensuremath{n} + \ensuremath{n_x})(\ensuremath{n}+\ensuremath{n_y}) - \ensuremath{n}
\end{array}
\right.$$
we can a dataset $\mDwz{\ensuremath{N}} = \{(W_i, Z_i) \}_{i=1,\cdots, \ensuremath{N}}$ of size $\ensuremath{N} = n_J + n_M$ of $\ensuremath{i.d.}$ random observations satisfying the $\ensuremath{\text{MDcond}}(\frac{n_J}{\ensuremath{N}})$.
\end{mytheo}
\end{mdframed}
\noindent Here again, it is possible to build a much larger $\ensuremath{i.d.}$ training dataset under some weak assumption. Indeed, the repetition of values occurs with probability $0$, almost surely. The complete construction of such a dataset is described in section~\ref{Sec:ProofConsUIDAM}
\medskip
\subsubsection{Multiple targets per observations (Framework~\ref{DATA3})}
In Framework~\ref{DATA3}, to each of the $\ensuremath{n}$ observations $X_i$, there exists a $\ensuremath{m}$-associated target $\mathbb{Y}_i=\big(Y_{i,1},\cdots,Y_{i,\ensuremath{m}}\big)$ of $\ensuremath{i.i.d.}$ components such that the $\left(Y_{i,j}\pCond X_i\right)_{j=1,\cdots,\ensuremath{m}}$ are $\ensuremath{i.i.d.}$. In this setting, it is still possible to construct, under some weak assumption, a larger $\ensuremath{i.d.}$ training set satisfying the $\ensuremath{\text{MDcond}}$. Recall, the repetition of values occurs with probability $0$, almost surely. Note that we can construct, at most, a data set of size $\ensuremath{n}^2 \times \ensuremath{m}$, with $\ratio = \frac{1}{\ensuremath{n}}$. On the other hand, if we want to have a ratio of $\ratio = \frac{1}{2}$, the generated dataset will be of size $2\ensuremath{n} \times \ensuremath{m}$.\\
\begin{mdframed}
\begin{mytheo}\label{pro:ConsUIDMT}\textbf{[Construction of a larger $\ensuremath{i.d.}$ training set]}\\
\noindent Consider the dataset $\ensuremath{\mathcal{D}_{n,m}^{X,\mathbb{Y}}} = \{(X_i,\mathbb{Y}_i) \}_{i= 1}^{\ensuremath{n}}$ a training dataset of size $\ensuremath{n} \in \ensuremath{\mathbbm{N}}^*$ defined in Framework~\ref{DATA3}. Assume that \\
$\bullet$ For all $(i,i') \in \{1,\cdots,\ensuremath{n}\}^2$ such that $i \neq i'$
$$
X_i \neq X_{i'}.
$$
$\bullet$ For all $(i,j),(i',j') \in \{1,\cdots,\ensuremath{n}\}\times \{1,\cdots,\ensuremath{m}\}$ such that $i \neq i'$ or $j \neq j'$
$$
Y_{i,j} \neq Y_{i',j'}
$$
\noindent Then, for any couple of integers $(n_J,n_M)$ such that
$$\left\{
\begin{array}{l}
1 \leq n_J \leq \ensuremath{n} \times \ensuremath{m}\\
1 \leq n_M \leq \ensuremath{n} (\ensuremath{n} - 1) \times \ensuremath{m}
\end{array}
\right.$$
we can construct a dataset $\mDwz{\ensuremath{N}} = \{(W_i, Z_i) \}_{i=1,\cdots, \ensuremath{N}}$ of size $\ensuremath{N} = n_J + n_M$ of $\ensuremath{i.d.}$ random observations satisfying the $\ensuremath{\text{MDcond}}\left(\frac{n_J}{\ensuremath{N}}\right)$.
\end{mytheo}
\end{mdframed}
The complete construction of such a dataset is described in section~\ref{Sec:ProofConsUIDMT}
\input{Experiments}
\input{Proofs}
\section{Conclusion}
In this article\,, we consider the problem of conditional density estimation. We introduce a new method, $\textbf{MCD}\,$ inspired by contrastive learning. $\textbf{MCD}\,$ reformulates the initial task into a problem of supervised learning. We present construction techniques to produce contrast dataset of \ensuremath{i.i.d.} or \ensuremath{i.d.} samples with far more observations than in the original dataset. We also provided construction techniques to take advantage of unlabeled observations and more than one target value per observation. We evaluate our method on a benchmark of both density models and real-world datasets, and obtain excellent results in most cases, especially when $\textbf{MCD}\,$ is combined with Neural Networks.\\
There are still many questions left open with regard to the appropriate choice of discriminator and construction strategy, notably the ratio $\ratio$. Besides, assessing the performances of \textbf{MCD}\, on down-stream tasks such as quantile regression, variance estimation or outlier detection is also a promising future avenue of research.
| {'timestamp': '2022-06-06T02:15:02', 'yymm': '2206', 'arxiv_id': '2206.01592', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01592'} | arxiv |
\section{Introduction}
How would this patient's scans look if they had a different \gls{ef}? How would this \gls{us} view appear if I turned the probe by 5 degrees? These are important causality related questions that physicians and operators ask explicitly or implicitly during the course of an examination in order to reason about the possible pathologies of the patient. In the second case, the interventional query of turning the probe is easy to resolve, by performing the action. However, in the first case, we ask a counterfactual question which cannot be answered directly. Indeed, it falls under the third and highest rung of Pearl's~\cite{Pearl2009} hierarchy of causation.
Counterfactual queries probe into alternative scenarios that might have occurred had our actions been different. For the first question of this paper, we ask ourselves how the patient's scans would look if they had a different \gls{ef}. Here, the treatment would be the different ejection fraction, and the outcome, the different set of scans. Note that this is a query that is \emph{counter-to} our observed knowledge that the patients scans exhibited a specific \gls{ef}. As such, standard Bayesian Inference, which conditions on the observed data without any further considerations, is not able to answer this type of question.
\setcounter{footnote}{0}
\noindent\textbf{Related works}:
Generating synthetic \gls{us} images can be performed with physics-based simulators \cite{shams2008real,cong2013fast,Mattausch2014,gao2009fast,burger2012real} and other techniques, such as registration-based methods \cite{ledesma2005spatio}. However, these methods are usually very computationally expensive and do not generate fully realistic images. With the shift toward deep learning, \gls{gan}-based techniques have emerged. They can be based on simulated \gls{us} priors or other imaging modalities (MRI, CT)~\cite{CRONIN2020105583,9110573,Tiago2021,Amirrajab2020,Samaneh2020,Tomar2021} to condition the anatomy of the generated \gls{us} images.
Recently, many works explore machine learning as a tool to estimate interventional conditional distributions~\cite{yoon2018ganite,kocaoglu2018causalgan,louizos2017causal,assaad2021counterfactual}. However, fewer works focus on the counterfactual query estimation. \cite{pawlowski2020deep,oberst2019counterfactual} explore the Abduction-Action-Prediction paradigm and use deep neural networks for the abduction step, which is computationally very expensive. \cite{cuellar2020non} derive a parametric mathematical model for the estimation of one of the probabilities of causation, while \cite{vlontzos2021estimating} use \cite{balke1994counterfactual} to develop deep twin networks.
The computer vision field also has a lot of interest in conditional generation problems. \cite{wang2020imaginator,tulyakov2018mocogan} perform conditional video generation from a video and a discrete class. \cite{ding2020ccgan} uses an image and a continuous value as input to produce a new image. \cite{sauer2021counterfactual,kocaoglu2018causalgan} introduce causality in their generation process, to produce images from classes.
\noindent\textbf{Contributions}: In this paper
(1) We extend the causal inference methodology known as Deep Twin Networks~\cite{vlontzos2021estimating} into a novel generative modelling method (\gls{dtgn} \footnote{\footnotesize D'Artagnan is the fourth Musketeer from the French tale ``The three Musketeers''.}) able to handle counterfactual queries.
(2) We apply our framework on the synthetic MorphoMNIST \cite{castro2019morphomnist} and real-world EchoNet-Dynamic \cite{Ouyang2020} datasets, demonstrating that our method can perform well in both fully controlled environments and on real medical cases.
To the best of our knowledge, this is an entirely novel approach and task, and thus the first time such an approach is explored for medical image analysis and computer vision.
Our work differentiates itself from all other generative methods by combining video generation with continuous conditional input in a new causal framework. This setup supports counterfactual queries to produce counterfactual videos using a semi-supervised approach which allows most standard labelled datasets to be used.
\section{Preliminaries}
\textbf{Structural causal models} \label{Section: Structural causal models}
We work in the Structural Causal Models (SCM) framework. Chapter $7$ of \cite{Pearl2009} gives an in-depth discussion. For an up-to-date, review of counterfactual inference and Pearl's Causal Hierarchy, see \cite{bareinboim20201on}.
As a brief reminder, we define a structural causal model (SCM) as a set of latent noise variables $U=\{u_1,\dots,u_n\}$ distributed as $P(U)$, a set of observable variables $V=\{v_1,\dots, v_m\}$ that is the superset of treatment variables $X$ and confounders $Z$, \emph{i.e.} $X,Z \subseteq V $. Moreover, we require a directed acyclic graph (DAG), called the \emph{causal structure} of the model, whose nodes are the variables $U\cup V$, and its edges represent a collection of functions $F=\{f_1,\dots, f_n\}$, such that $v_i = f_i(PA_i, u_i), \text{ for } i=1,\dots, n,$ where $PA$ denotes the parent observed nodes of an observed variable. These are used to induce a distribution over the observable variables and assign uncertainty over them.
Finally, the $do$-operator forces variables to take certain values, regardless of the original causal mechanism. Graphically, $do(X=x)$ means deleting edges incoming to $X$ and setting $X=x$. Probabilities involving $do(x)$ are normal probabilities in submodel $M_x$: $P(Y=y \mid \text{do}(X=x)) = P_{M_x} (y)$.
\noindent\textbf{Counterfactual inference} \label{Section: two approaches to counterfactual inference}
The latent distribution $P(U)$ allows us to define probabilities of counterfactual queries, $P(Y_{y}=y) = \sum_{u \mid Y_{x}(u)=y} P(u)$. Moreover, one can define a counterfactual distribution given seemingly contradictory evidence and thereby state the counterfactual sentence ``$Y$ would be $y$ (in situation $U=u$), had $X$ been $x$''. Despite the fact that this query may involve interventions that contradict the evidence, it is well-defined, as the intervention specifies a new submodel. Indeed, $ P(Y_{x}={y}' \mid E = {e})$ is given by ~\cite{Pearl2009} as
$ \sum_{{u}}
P(Y_{{x}}({u})={y}')P({u}|{e})\,.$
\noindent\textbf{Twin Networks}
As opposed to the standard \textit{Abduction - Action - Prediction} paradigm, we will be operating under the Twin Model methodology. Originally proposed by Balke and Pearl in \cite{balke1994counterfactual}, this method allows efficient counterfactual inference to be performed as a feed forward Bayesian process. It has also been shown empirically to offer computational savings relative to abduction-action-prediction~\cite{grahamcopy}. A twin network consists of two interlinked networks, one representing the real world and the other the counterfactual world being queried.
Given a structural causal model, a twin network can be constructed and used to compute a counterfactual query through the following steps: First, duplicate the given causal model, denoting nodes in the duplicated model via superscript $^*$. Let $V $ be observable nodes that include the treatment variables $X$ and the confounders $Z$, and let $X^*,Z^* \subseteq V^{*}$ be the duplication of these. Also let $U$ be the unobserved latent noise. Then, for every node $v_i^{*}$ in the duplicated, or ``counterfactual'' model, its latent parent $u_i^{*}$ is replaced with the original latent parent $u_i$ in the original, or ``factual'', model, such that the original latent variables are now a parent of two nodes, $v_i$ and $v_i^{*}$. The two graphs are linked only by common latent parents, but share the same node structure and generating mechanisms. To compute a general counterfactual query $P(Y=y \mid E=e, \text{do}(X=x))$, modify the structure of the counterfactual network by dropping arrows from parents of $X^*$ and setting them to value $X^*=x$. Then, in the twin network with this modified structure, compute the probability $P(Y^*=y \mid E=e, X^*=x)$ via standard Bayesian inference techniques, where $E$ are factual nodes.
\section{Method} \label{sec:dtgn}
\noindent\textbf{Deep Twin Networks}
The methodology we propose is based on Deep Twin Networks. The training procedure and parametrization are borrowed from \cite{vlontzos2021estimating}, which sets the foundation for our causal framework. Deep Twin Networks use two branches, the factual and the counterfactual branch. We denote our factual and counterfactual treatments (inputs unique to each branch) as $X$ and $X^*$, while the confounder (input shared between both branches) is denoted by $Z$. We denote the factual and counterfactual outcomes as $\hat{Y}, \hat{Y}^*$ while the noise, injected midway through the network, and shared by both branches, is denoted by $U_Y$. This information flow sets $Z$ as the data we want to query with $X$ and $X^*$, to produce the outcomes $\hat{Y}$ and $\hat{Y}^*$. These variables will be detailed on a case-specific basis in \Cref{sec:experiments}. See Fig.\ref{figure: deep twin netork architectures_TN} for a visual representation of the information flow.
\noindent\textbf{Synthetic data}
Synthetic data allows for full control over the generation of both ground truth outcomes $Y$ and $Y^*$ along with their corresponding inputs $X$, $X^*$ and $Z$. This makes training the Deep Twin Network trivial in a fully supervised fashion, as demonstrated in our first experiment.
\noindent\textbf{Real-world data}
Theoretically, our approach requires labelled data pairs, but very few datasets are arranged as such. To overcome this limitation and support most standard labeled imaging datasets, we establish a list of features that our model must possess to generate counterfactual videos for the medical domain: (1) produce a factual and counterfactual output that share general visual features, such as style and anatomy, (2) produce accurate factual and counterfactual videos with respect to the treatment variable, and (3) the produced videos must be visually indistinguishable from real ones. In the following, we use the Echonet-Dynamic~\cite{Ouyang2020} dataset to illustrate the method, see \Cref{sec:experiments} for details.
We solve feature (1) by sharing the weights of the branches in the network, such that we virtually train a single branch on two tasks in parallel. To do so, we set the confounder $Z$ as the input video and the treatment $X$ as the labelled \gls{ef}. We train the network to match the factual outcome $\hat{Y}$ with the input video. By doing so, the model learns to retain the style and anatomical structure of the echocardiogram from the confounder. This is presented as \emph{Loss 1} in \Cref{figure: deep twin netork architectures_TN}.
For feature (2) we pre-train an expert network to regress the treatment values from the videos produces by the counterfactual branch, and compare them to the counterfactual treatment. The expert network's weights are frozen when training the Twin model, and alleviates the need for labels to train the counterfactual branch. This loss is denoted as \emph{Loss 2} in \Cref{figure: deep twin netork architectures_TN}.
Finally, feature (3) calls for the well-known \gls{gan} framework, where we train a neural network to discriminate between real and fake images or videos, while training the Twin Network. This constitutes the adversarial \emph{Loss 3} in \Cref{figure: deep twin netork architectures_TN} and ensures that the counterfactual branch produces realistic-looking videos.
With those 3 losses, we can train the generator (i.e. factual and counterfactual branches) to produce pairs of visually accurate and anatomically matching videos that respect their factual and counterfactual \gls{ef}s treatment.
To learn the \textbf{noise distribution} $U_Y$, we follow~\cite{goudet2017learning,vlontzos2021estimating} and without loss of generality we can write $Y=f(X,Z,g(U_Y'))$ with $U_Y'\sim \mathcal{E}$ and $U_Y = g(U_Y')$, where $\mathcal{E}$ is some easy-to-sample-from distribution, such as a Gaussian or Uniform. Effectively, we cast the problem of determining $U_Y$ to learning the appropriate transformation from $\mathcal{E}$ to $U_Y$. For ease of understanding, we will be using $U_Y$ henceforth to signify our approximation $g(U_Y')$ of the true unobserved parameter $U_Y$.
In addition to specifying the causal structure, the following standard assumptions are needed to correctly estimate $\mathbb{E}(Y | do(X), Z)$ \cite{schwab2018perfect}: (1) \emph{Ignorability:} there are no unmeasured confounders; (2) \emph{Overlap:} every unit has non-zero probability of receiving all treatments given their observed covariates.
\begin{figure}[t]
\centering
{
\includegraphics[width=0.95\linewidth]{images/dartagnan/model2.pdf}
}
\caption{
The \gls{dtgn} framework. The green variables are known, the orange are sampled from distributions and the blue are generated by deep neural networks. Factual path is in blue, counterfactual in red. \label{figure: deep twin netork architectures_TN}}
\end{figure}
\section{Experimentation}\label{sec:experiments}
\noindent\textbf{Datasets}
To evaluate \gls{dtgn}, we use two publicly available datasets, the synthetic MorphoMNIST~\cite{castro2019morphomnist} and the clinical Echonet-Dynamic~\cite{Ouyang2020} dataset.
MorphoMNIST is a set of tools that enable fine-grained perturbations of the MNIST digits through four morphological functions, as well as five measurements of the digits. To train our model, we need five elements: an original image, a (counter-)factual treatment $X$($X^*$) and a corresponding (counter-)factual label $Y$($Y^*$). To generate this data, we take 60,000 MNIST images $I_i$ and sample 40 perturbation vectors $p_{i,j}$ for the five possible perturbations, including identity, thus generating 2.4 million images $I_{p_{i,j}}$. The perturbation vectors also encode the relative positions of the perturbations, when applicable. We \textit{measure} the original images to produce vectors $m_i$ and one-hot encode the labels into vectors $l_i$. We decided to perform the causal reasoning over a latent space, rather than image space. To do so, we train a \gls{vqvae} \cite{oord2017neural} to project the MorphoMNIST images to a latent space $\mathcal{H} \in \mathbb{R}^{(q \times h \times w)} $ and reconstruct them. Once trained, the \gls{vqvae} weights are frozen, and we encode all the ground-truth perturbed images $I_{p_{i,j}}$ into a latent embedding $\mathcal{H}_{i,j}$. Afterwards, the \gls{vqvae} is used to reconstruct the generated latent embeddings $\hat{Y}, \hat{Y}^*$ for qualitative evaluation purposes.
The clinical dataset Echonet-Dynamic~\cite{Ouyang2020} consists of 10,030 4-chamber echo\-cardiography videos with $112 \times 112$ pixels resolution and various length, frame rates, image quality and cardiac conditions. Each video contains a single pair of consecutively labelled \gls{es} and \gls{ed} frames. Each video also comes with a manually measured \gls{ef}. For our use case, all videos are greyscaled and resampled to 64 frames, with a frame rate of 32 images per second. All videos shorter than two seconds are discarded, and we make sure to keep the labelled frames. For the resulting 9724 videos dataset, the original split is kept, with 7227 training, 1264 validation and 1233 testing videos.
\begin{figure}[!t]
\centering
\centering
\includegraphics[width=0.12\linewidth]{images/MNIST_val/000001_001_I.png}~~~~
\includegraphics[width=0.12\linewidth]{images/MNIST_val/000001_001_I_px.png}
\includegraphics[width=0.12\linewidth]{images/MNIST_val/000001_001_I_pred.png}~~~~
\includegraphics[width=0.12\linewidth]{images/MNIST_val/000001_001_I_pxs.png}
\includegraphics[width=0.12\linewidth]{images/MNIST_val/000001_001_I_pred_s.png}
\caption{Left to right: original image, GT factual image, predicted factual image, GT counterfactual image, predicted counterfactual image. Factual perturbation is Thinning, Counterfactual perturbation are Thickening and Swelling.}
\label{fig:mnist_images}
\end{figure}
\noindent\textbf{MorphoMNIST} For our synthetic experiment, we define a deep twin network as in~\cite{vlontzos2021estimating} and follow the process we described in the Methods (\Cref{sec:dtgn}). Regarding data organization, we use the elements defined in the section above. We set our confounder $Z_i = [l_i, m_i]$ to contain the one-hot encoded labels as well as the measurement of the original image. We sample two perturbation vectors $p_{i,m}$ and $p_{i,n}$ and their corresponding latent embeddings $\mathcal{H}_{i,m}$ and $\mathcal{H}_{i,n}$, where $n, m \in \llbracket 0, 40\llbracket$, $n \neq m$. We set our input treatments as the perturbations vectors ($X = p_{i,m}$, $X^* = p_{i,n}$) and our ground-truth outcomes as the corresponding latent embeddings of the perturbed images ($Y=\mathcal{H}_{i,m}$, $Y^*=\mathcal{H}_{i,n}$). We sample $U_Y \sim [ \mathcal{N}(0 ,0.25)\bmod{1} + 1 ]$ and disturb the output of the branches of the neural networks that combine $X$ and $X^*$ with $Z$ by multiplying the outputs of both with the same $U_Y$. With this setup, we generate factual and counterfactual perturbed MNIST embeddings from a latent description.
We assess the quality of the results by three means:
(1) \emph{Embeddings' MSE:} We sample a quintuplet ($Z$, $X$, $X^*$, $Y$, $Y^*$) and 1000 $U_Y$. The MSE between all $\hat{Y}_{i}$ and $Y$ are computed and used to order the pairs ($\hat{Y}_i$, $\hat{Y}^*_i$) in ascending order. We keep the sample with the lowest MSE as our factual estimate and compute the MSE between $\hat{Y}^*_0$ and $Y^*$ to get our counterfactual MSE score.
(2) \emph{SSIM:} We use the Structural SIMilarity metric between the perturbed images $I_{gt} = I_{p_{i,j}}$, the images reconstructed by the VQVAE $I_{rec}$ and the images reconstructed from the latent embedding produced by the twin network $I_{pred}$ to get a quantitative score over the images.
(3) \emph{Images:} We sample some images to qualitatively assess best and worst cases scenarios for this framework.
We show the quantitative results in \Cref{tab:metrics}(a), and qualitative results in~\Cref{fig:mnist_images} and in the appendix.
\begin{table}[t]
\centering
\caption{Metrics for MorphoMNIST (a) and EchoNet-Dynamic (b) experiments.}
\begin{subtable}{.6\textwidth}
\centering
\begin{tabular}{|l|cc|}
\hline
Metric & Factual & Counterfactual\\
\hline
MSE($Y$, $\hat{Y}$) & 2.3030 & 2.4232 \\
SSIM($I_{gt}$, $I_{rec}$)$^\dagger$ & 0.9308 & 0.9308 \\
SSIM($I_{rec}$, $I_{pred}$) & 0.6759 & 0.6759 \\
SSIM($I_{gt}$, $I_{pred}$) & 0.6707 & 0.6705 \\
\hline
\end{tabular}
\caption{MSE and SSIM scores. $^\dagger$No ordering is performed as there is no noise involved. \label{tab:mnist_metrics}}
\end{subtable}
\begin{subtable}{.39\textwidth}
\centering
\begin{tabular}{|l|cc|}
\hline
Metric & Factual & Counterf. \\
\hline
R2 & 0.87 & 0.51 \\
MAE & 2.79 & 15.7 \\
RMSE & 4.45 & 18.4 \\
SSIM & 0.82 & 0.79 \\
\hline
\end{tabular}
\caption{\gls{dtgn} LVEF and reconstruction metrics.\label{tab:gan_metrics}}
\end{subtable}
\label{tab:metrics}
\end{table}
\noindent\textbf{Echonet Dynamic}
As stated in~\Cref{sec:dtgn}, our methodology requires an \textbf{Expert Model} to predict the \gls{ef} of any \gls{us} video. To do so, we re-implement the ResNet 2+1D network~\cite{tran2018closer} as it was shown to be the best option for \gls{ef} regression in \cite{Ouyang2020}. We opt not to use transformers as they do not supersede convolutions for managing the temporal dimension, as shown in \cite{reynaud2021ultrasound}.
We purposefully keep this model as small as possible in order to minimize its memory footprint, as it will be operating together with the generator and the frame discriminator. The expert network is trained first, and frozen while we train the rest of \gls{dtgn}. Metrics for this model are presented in the Appendix.
\noindent\textbf{\gls{dtgn}}
We implement the generator as described in \Cref{sec:dtgn}. We define a single deep network to represent both the factual and counterfactual paths. By doing so, we can meet the objectives listed in \Cref{sec:dtgn}. The branch is implemented as a modified ResNet 2+1D \cite{tran2018closer} to generate videos. It takes two inputs: a continuous value and a video, where the video determines the size of the output. For additional details, please refer to \Cref{figure: deep twin netork architectures_TN} and the code.
\noindent\textbf{Discriminator}
We build a custom discriminator architecture using five ``residual multiscale convolutional blocks", with kernel sizes 3, 5, 7 and appropriate padding at each step, followed by a max-pooling layer. Using multiscale blocks enables the discriminator to look at both local and global features. This is extremely important in \gls{us} images because of the noise in the data, that needs to be both ignored, for anatomical identification, and accounted for to ensure that counterfactual \gls{us} images look real. We test this discriminator both as a frame-based discriminator and a video-based discriminator, by changing the 2D layers to 3D layers where appropriate. We note that, given our architecture, the 3D version of the model requires slightly less memory but doubles the processing power compared to the 2D model.
\noindent\textbf{Training the framework}
At each training step, we sample an \gls{us} video ($V$) and its \gls{ef} ($\psi$). We set our factual treatment, $X = \psi$ and our counterfactual treatment $X^* \sim \mathcal{U}(0,\psi-0.1) \cup \mathcal{U}(\psi+0.1,1)$. The confounder $Z$ and the factual ground truth $Y$ are set to the sampled video such that $Z = Y = V$. We compute an L1 reconstruction loss (loss 1) between $\hat{Y}$ and $Y = V$. As we do not have ground truth for the counterfactual branch, we use the frame discriminator and the expert model to train it. Both models take as input the counterfactual prediction $\hat{Y}^*$. The expert model predicts an \gls{ef} $\hat{\psi}$ that is trained to match the counterfactual input $X^*$ with an L1 loss (loss 2). The discriminator is trained as a \gls{gan} discriminator, with $\hat{Y}^*$ as fake samples and $V$ as real samples. It trains the generator with L1 loss (loss 3).
The discriminator and expert model losses are offset respectively by three and five epochs, leaving time for the generator to learn to reconstruct $V$, thus maintaining the anatomy and style of the confounder. Our experiments show that doing so increases the speed at which the network is capable of outputting realistic-looking videos, thus speeding up the training of the discriminator that sees accurate fake videos sooner. Once the generator and discriminator are capable of generating and discriminating realistic-looking videos, the expert network loss is activated and forces the generator to take into account the counterfactual treatment, while the factual treatment is enforced by the reconstruction loss. The losses are also scaled, such that the discriminator loss has a relative weight of 3 compared to the reconstruction and expert loss.
\begin{figure}[!t]
\centering
\begin{minipage}{.35\textwidth}
\centering
\begin{tabular}{cc}
\includegraphics[trim={0 1cm 0 1cm},clip,width=0.5\linewidth]{images/dartagnan/f_es_3D.png} &
\includegraphics[trim={0 1cm 0 1cm},clip,width=0.5\linewidth]{images/dartagnan/f_ed_3D.png} \\
Factual \gls{es} & Factual \gls{ed} \\
\end{tabular}
\end{minipage
\begin{minipage}{.29\textwidth}
\centering
\hfill\includegraphics[width=0.95\linewidth]{images/dartagnan/graph2.png}
\end{minipage}
\begin{minipage}{.35\textwidth}
\centering
\begin{tabular}{cc}
\includegraphics[trim={0 1cm 0 1cm},clip,width=0.5\linewidth]{images/dartagnan/cf_es_3D.png} &
\includegraphics[trim={0 1cm 0 1cm},clip,width=0.5\linewidth]{images/dartagnan/cf_ed_3D.png} \\
Counterf \gls{es} & Counterf. \gls{ed} \\
\end{tabular}
\end{minipage}
\caption{Qualitative results for \gls{dtgn} over the same confounder and noise. Left: factual \gls{es} and \gls{ed} frames. Middle: left ventricle area over time, obtained with a segmentation network as in \cite{Ouyang2020}. Dots represent where the corresponding frames were sampled. Right: counterfactual \gls{es} and \gls{ed} frames.
Anatomy is preserved across videos, while the \gls{ef} fraction is different.
}
\label{fig:quali_echo}
\end{figure}
\noindent\textbf{Metrics}
To match our three objectives, we evaluate this new task on 1) the accuracy of the anatomy and 2) the accuracy of the regressed \gls{ef}.
We obtain the best possible video by sampling 100 $U_Y$ and keeping the $\hat{Y}^*$ with $\hat{\phi}^*$ closest to $X^*$.
We then evaluate our metrics over those ``best'' videos. The anatomical accuracy is measured with SSIM and the \gls{ef} precision is measured using R2, MAE and RMSE scores. Results are shown in \Cref{tab:gan_metrics}.
\noindent\textbf{Qualitative} In \Cref{fig:quali_echo} we show video frame examples to showcase the quality of the reconstructed frames, as well as how the anatomy and style are maintained.
\noindent\textbf{Discussion}
The predicted \gls{ef} has an MAE of 15.7\% which is not optimal. This can come from many factors such as the use of the same dataset to train the Expert model and \gls{dtgn}, the limited number of real videos, or the limited size of the networks due to the necessity of working with three models at once. Those problems could be addressed with hyperparameter search, larger models, as well as additional medical data. For completeness, we compare the performance of \gls{dtgn} with the literature~\cite{wang2020imaginator,tulyakov2018mocogan}, and run additional experiments (see Appendix) with an ablated version of our model for conditional video generation, where it achieves the best SSIM score of 0.72.
\section{Conclusion}
In this paper we introduce \gls{dtgn}, a Deep Twin Generative Network able to produce counterfactual images and videos. We showcase its performance in both a synthetic and a real world medical dataset and achieve visually accurate results and high quantitative scores. In future work, we will explore other treatments, such as changing the heartbeat, as well as less constrained confounders, e.g. image segmentations.\\
\noindent\textbf{Acknowledgements:} This work was supported by Ultromics Ltd., the UKRI Centre for Doctoral Training in Artificial Intelligence for Healthcare (EP/S023283/1), and the UK Research and Innovation London Medical Imaging and Artificial Intelligence Centre for Value Based Healthcare. We thank the NVIDIA corporation for their GPU donations used in this work.
\bibliographystyle{splncs04}
| {'timestamp': '2022-07-01T02:18:23', 'yymm': '2206', 'arxiv_id': '2206.01651', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01651'} | arxiv |
\section{Introduction}
The core and one of the most expensive operations in many machine learning applications is matrix multiplication. Performing such operations locally on a single computer takes a long time. Users would consider outsourcing their matrices to a distributed system for time-sensitive applications to carry out demanding computation tasks. Efficient methods require coding over the input matrices to speed up the computational time, yielding a trade-off among the number of workers needed, tasks performed at each worker, and the total amount of data transmitted. While outsourcing disrupts the computational delays, it leads to data security concerns. This paper aims to develop an efficient, secure distributed matrix multiplication (SDMM) scheme which keeps matrices secure from the potentially colluding servers.
We consider the problem of secure distributed matrix multiplication (SDMM), where a user has two matrices, $A \in \mathbb{F}_q^{a \times b}$, $B \in \mathbb{F}_q^{b \times c}$ and wishes to compute their product, $AB \in \mathbb{F}_q^{a \times c}$, with the assistance of $N$ servers, without leaking any information about either $A$ or $B$ to any server. We assume that all servers are honest but curious (passive) in that they are not malicious and will follow the pre-agreed upon protocol. However, any $T$ of them may collude to eavesdrop and extrapolate information regarding $A$ or $B$.
The setting considered in this paper is proposed in~\cite{ravi2018mmult}, with many follow-up works~\cite{Kakar2019OnTC,koreans,d2019gasp,DOliveira2019DegreeTF, Aliasgari2019DistributedAP,aliasgari2020private,Kakar2019UplinkDownlinkTI,doliveira2020notes,Yu2020EntangledPC,mital2020secure,bitar2021adaptive, hasircioglu2021speeding,ftp-9606447}. The initial performance metric used was the download cost, meaning the total amount of data downloaded by the users from the server. Following papers have also considered the upload costs \cite{mital2020secure}, the total communication costs \cite{9004505, ftp-9606447}, and computational costs \cite{doliveira2020notes}.
Different partitions of the matrices lead to different trade-offs between upload and download costs. In this paper, we consider the most general one, namely, the grid product partition given by \[A = \begin{bmatrix}
A_{i,j}
\end{bmatrix}_{\substack{1\leq i\leq t\\ 1\leq j\leq s}},
B = \begin{bmatrix}
B_{i,j}
\end{bmatrix}_{\substack{1\leq i\leq s\\ 1\leq j\leq d}}\]
such that,
\[\displaystyle AB =
\begin{bmatrix}
M_{1,1} & \cdots & M_{1,d}\\
\vdots & \ddots & \vdots\\
M_{t,1} & \cdots & M_{t,d}\\\end{bmatrix}=\begin{bmatrix}
\sum_{\ell=1}^s A_{i,\ell} B_{\ell,j}\end{bmatrix}_{\substack{1\leq i\leq t\\ 1\leq j\leq d}},\]
where the products $A_{i,\ell} B_{\ell, j}$ are well-defined and of the same size. Under this partition, a polynomial code is a polynomial $h(x)=f_A(x) \cdot f_B(x)$, whose coefficients encode the submatrices $A_{i, j}B_{k,\ell}$. The next step is where the scheme we propose
differs from previous works that use the grid product partition. The user evaluates polynomials $f_A(x)$ (encoding matrix $A$) and $f_B(x)$ (encoding matrix $B$) at powers $\alpha_N, \alpha^2_N, \ldots, \alpha^N_N=1$ of an $N$-th root of unity $\alpha_N$. The $N$ servers compute the product $h(\alpha^i)=f_A(\alpha^i)f_B(\alpha^i)$ for $i\in\{1,\ldots,N\}$. The polynomial $h(x)$ is constructed so that no $T$-subset of evaluations reveals any information about $A$ or $B$ ($T$-security), but so that the user can reconstruct $AB$ given all $N$ evaluations (decodability).
An example of a polynomial scheme for the grid product partition is the secure MatDot codes in \cite{Aliasgari2019DistributedAP} and the entangled polynomial codes in~\cite{8949560}.
In Theorem \ref{theo:scheme}, we characterize the total communication rate
achieved by our proposed scheme:
\begin{theorem}\label{theo:scheme}
Let $t,d,s$ and $T$ be positive integers. Let $A \in \mathbb{F}_q^{a \times b}$, $B \in \mathbb{F}_q^{b \times c}$ be two matrices.
Then, the proposed scheme with partition parameters $(t,d,s)$ and security parameter $T$ securely computes $AB$ with the assistance of
\[
N=
\begin{cases}
(d+1)(t+T)-1, &\text{if }s=1 \\
dst+dT+ts-1+T+1,& \text{if } s> 1
\end{cases}
\]
servers and a total communication rate of
\begin{align}
\mathcal{R} = \left( N\left(\frac{b}{cts}+\frac{b}{asd}+ \frac{1}{td}\right) \right)^{-1} .
\end{align
\end{theorem}
In Theorem~\ref{theo:comparison}, we show that our proposed code matches the recovery threshold of the best-known scheme for inner product partition, \cite{mital2020secure} and also matches GASP codes for outer product partition when $T<t$.
\begin{theorem}\label{theo:comparison}
Let $(t,d,s)$ be the partition parameters and $T$ be the security parameter:
\begin{itemize}
\item If $t=d=1$, meaning inner product partition, then the recovery rate for the proposed scheme matches s+2T, same as scheme in \cite{mital2020secure} without pre-computation.
\item If $s=1$, meaning outer product partition, then the recovery rate for the proposed scheme matches $(d+1)(t+T)-1$, same as for GASP codes, in \cite{9004505}, $T<t$.
\end{itemize}
\end{theorem}
\subsection{Related Work}
For distributed computations, polynomial codes were initially introduced in~\cite{polycodes1} to mitigate stragglers in distributed matrix multiplication. A series of works followed this,~\cite{polycodes2,pulkit,pulkit2,fundamental}.
The literature on SDMM has also studied different variations of the model we focus on here. For instance, in~\cite{nodehi2018limited,jia2019capacity,mital2020secure,akbari2021secure} the encoder and decoder are considered to be separate, in~\cite{nodehi2018limited} servers are allowed to cooperate. In~\cite{kim2019private} the authors consider a hybrid setup between SDMM and private information retrieval where the user has a matrix $A$ and wants to multiply it with a matrix $ B$ belonging to some public list privately.
\subsection{Main Contributions}
Our main contributions are summarized below.
\begin{itemize}
\item We present a generalization for polynomial coding in the context of the secure distributed matrix multiplication problem, considering the grid product partition. This partition allows extending the use of techniques to reduce upload costs.
\item By adapting the Fourier Discrete Transform used in \cite{mital2020secure}, we present a new scheme for SDMM. It reduces the communication load by lowering the recovery threshold. We show that they are secure, decodable, and present their total communication rate in Theorem~\ref{theo:scheme}.
\item In Theorem~\ref{theo:comparison}, we show that \emph{the proposed scheme} matches the recovery threshold of the best-known scheme for inner product partition, \cite{mital2020secure}, and also matches the GASP scheme for outer product partition when $T<t$.
\end{itemize}
\section{A Motivating Example: $d=t=2$ and $T=1$}
\label{sec2}
We begin the description of our proposed scheme with an example, which we present to showcase our scheme. At the end of the section, we assume that each server can compute $\frac{abc}{4}$ scalar operations, meaning additions or multiplications in $\mathbb{F}_q$. Finally, we compare the proposed method with GASP codes that use an outer partition product and the one using an inner partition product.
In this example, a user wishes to multiply two matrices $A \in \mathbb{F}_{q}^{a \times b}$ and $B \in \mathbb{F}_{q}^{b \times c}$ with the assistance of non-colluding helper servers. Consider the following matrices are partitioned as follows
\[A=\begin{bmatrix}
A_{1,1} & A_{1,2}\\mathcal{A}_{2,1} & A_{2,2}
\end{bmatrix}\in \mathbb{F}_q^{a\times b}, \ B=\begin{bmatrix}
B_{1,1} & B_{1,2}\\B_{2,1} & B_{2,2}
\end{bmatrix}\in \mathbb{F}_q^{b\times c}\]
By multiplying the matrices we obtain
\[M=AB=\begin{bmatrix}
A_{1,1}B_{1,1}+A_{1,2}B_{2,1} & A_{1,1}B_{1,2}+A_{1,2}B_{2,2}\\mathcal{A}_{2,1}B_{1,1}+A_{2,2}B_{2,1}&A_{2,1}B_{1,2}+A_{2,2}B_{2,2}.
\end{bmatrix}\]
Since we assume non-colluding servers, i.e, $T=1$, it involves picking two random matrices $R \in \mathbb{F}_{q}^{\frac{a}{2} \times \frac{b}{2}}$ and $S \in \mathbb{F}_{q}^{\frac{b}{2} \times \frac{c}{2}}$.
Consider the (Laurent) polynomials
\begin{align*}
f_A(x)&=A_{1,1} + A_{1,2}x + A_{2,1}x^2+ A_{2,2}x^3 + R x^4,\\ &\mbox{ and } \\
f_B(x)&=B_{1,1} + B_{2,1}x^{-1} + B_{1,2}x^{-5}+ B_{2,2}x^{-6} + S x^{-10}
\end{align*}
We obtain the following degree table for polynomial $h(x) = f_A(x)f_B(x)$:
\[
\begin{array}{c|ccccc}
+ & 0 & 1 & 2 &3& 4 \\
\hline
0& {\color{blue}0 }& 1 & {\color{green}2} & 3 & 4 \\
-1 & -1 & {\color{blue}0} & 1 & {\color{green}2} & 3 \\
-5 & {\color{red}-5} & -4 & {\color{orange}-3} & -2& -1 \\
-6 & -6 & {\color{red} -5} & -4 & \color{orange}{-3} &-2 \\
-10 & -10 & -9 & -8 & -7 & -6 \\\end{array}
\]
leading to a problem to find evaluations points $\mathbb{F}_q$ that minimizes the set
$\{\alpha^{i}: i\in \{-10, -9, \ldots, 4\} \}$ under the following conditions:
\begin{itemize}
\item $|\{\alpha^{-5}, \alpha^{-3}, \alpha^{0}, \alpha^{2}\}|=4$
\item $\{\alpha^{-5}, \alpha^{-3}, \alpha^{0}, \alpha^{2}\} \cap \{\alpha^{-10},\ldots, \alpha^{-6}, \alpha^{-4}, \\ \mbox{\hspace{4.5cm}}\alpha^{-2}, \alpha^{-1}, \alpha, \alpha^{3}, \alpha^{4}\}=\emptyset$
\end{itemize}
Consequently, if $\alpha=\alpha_{13}$ is an $13$-th root of unity, such a condition is satisfied.
\subsection{Computational complexity}
Let $\alpha_{13}\in \mathbb{F}_q$ be a primitive root of unity. The algorithm for computing the multiplication is as follows
\begin{enumerate}
\item \textbf{Encode.} For $i=1,\ldots,13$, the user computes $f_A(\alpha_{13}^i)$ and $f_B(\alpha_{13}^i)$.
\item \textbf{Upload.} The user sends matrices $f_A(\alpha_{13}^i)$ and $f_B(\alpha_{13}^i)$ to Server $i$.
\item \textbf{Server multiplication.} Servers multiply together the received matrices.
\item \textbf{Download.} Servers send the result $f_A(\alpha_{13}^i)\cdot f_B(\alpha_{13}^i)$ back to the user.
\item \textbf{Decode.} The user uses Equation \ref{prop:rootofunity} to obtain the coefficients with degree $-5$, $-3$, $0$, and $2$ or, equivalently, $0$, $2$, $8$, and $10$ since polynomials are evaluated at an 13-th root of unity $\alpha_{13}$. Therefore,
\begin{align*}
A_{1,1}B_{1,1}+A_{1,2}B_{2,1}&=\frac{1}{13}\sum_{i=1}^{13}f_A(\alpha_{13}^i)\cdot f_B(\alpha_{13}^i)\\
A_{1,1}B_{1,2}+A_{1,2}B_{2,2}&=\frac{1}{13}\sum_{i=1}^{13}(\alpha_{13}^i)^5f_A(\alpha_{31}^i)\cdot f_B(\alpha_{13}^i)\\
A_{2,1}B_{1,1}+A_{2,2}B_{2,1}&=\frac{1}{13}\sum_{i=1}^{13}(\alpha_{13}^i)^{11}f_A(\alpha_{13}^i)\cdot f_B(\alpha_{13}^i)\\
A_{2,1}B_{1,2}+A_{2,2}B_{2,2}&=\frac{1}{13}\sum_{i=1}^{13}(\alpha_{13}^i)^3f_A(\alpha_{13}^i)\cdot f_B(\alpha_{13}^i)
\end{align*}
\end{enumerate}
We start with the assumption that addition and multiplication in $\mathbb{F}_q$ take constant time. We consider for simplicity that parameters $a$, $b$, and $c$ are divisible by $2$. We describe below here the complexities of each step:
\begin{enumerate}
\item Computing $f_A(\alpha_{13}^i)$ and $f_B(\alpha_{13}^i)$ requires $2ab$ and $2bc$ $\mathbb{F}_q$-operations, respectively. This translates to $26(ab+bc)$ $\mathbb{F}_q$-operations to compute the $13$ evaluations.
\item The user sends $\frac{13}{4}(ab+bc)$ $\mathbb{F}_q$-elements to the servers.
\item The computational cost to perform the product $f_A(\alpha_{13}^i)f_B(\alpha_{13}^i)$ on each server is $\frac{ac(b-1)}{4}$.
\item Each server sends $\frac{ac}4$ $\mathbb{F}_q$-elements to the user.
\item The decoding step requires up to $\frac{13ac}{2}$ $\mathbb{F}_q$-operations to obtain each coefficient of interest. Since $3$ of those requires exactly $\frac{13ac}{2}$ and one requires $\frac{14ac}{4}$, then in total, we need $23ac$ $\mathbb{F}_q$-operations are required to retrieve the desired product $AB$.
\end{enumerate}
\begin{table*}[ht]
\centering
\begin{tabular}{|P{3cm}||P{3cm}|P{3cm}|P{3cm}|P{3cm}|}
\textbf{Scheme} & \textbf{Upload Cost} & \textbf{Download Cost} & \textbf{Encoding Complexity} & \textbf{Decoding Complexity}\\
\hline
\rule[-2ex]{0pt}{6ex} Proposed Scheme & $\frac{13}{4}(ab+bc)$ & $\frac{13 ac}{4}$& $26(ab+bc)$ & $23ac$ \\ \hline
\rule[-2ex]{0pt}{6ex} GASP& $\frac{7}{2}(ab+bc)$ & $\frac{7ac}{4}$&$28(ab+bc)$&$27ac$\\ \hline
\rule[-2ex]{0pt}{6ex} Scheme in \cite{mital2020secure} & $\frac{3}{2}(ab+bc)$ & $7ac$& $12(ab+bc)$ & $7ac$\\ \hline
\end{tabular}
\caption{Comparison to other methods with limited $\mathbb{F}_q$-operations $\frac{ac(b-1)}{4}$ to compute $f_A(\alpha_{11}^i)f_B(\alpha_{11}^i)$ on each server.}{\label{tab:compare}}
\end{table*}
\begin{remark}
If we consider the time to transmit one, add or multiply two elements in $\mathbb{F}_q$ is equal to $1$, the scheme presented can speedup computational time of multiplying matrices $A \in \mathbb{F}_{q}^{a \times b}$ and $B \in \mathbb{F}_{q}^{b \times c}$ if the dimensions of the matrices satisfy $a > \frac{234}{7}$, $b > \frac{216 a}{-234 + 7 a}$, and $c > \frac{234 a b}{-216 a - 234 b + 7 a b}$ compared to local computation which requires $2abc-ac$ operations using the traditional matrix multiplication.
\end{remark}
In Table \ref{tab:compare}, we present a comparative summary for this example among the proposed method, GASP (which uses outer product partition), and the scheme shown in \cite{mital2020secure} (which inner product partition). For this comparison, we fixed the amount of $\mathbb{F}_q$-operations in each server by $\frac{ac(b-1)}{4}$; therefore, we shall assume parameters $a$, $b$ and $c$ are divisible by $4$.
\begin{remark}\label{rem:fieldsize}
Since the evaluation points are powers of an $N$-th primitive root of unity, the appropriate size $q$ of the field should satisfy $N \mid (q - 1)$. This condition ensures the existence of the multiplicative inverse of $N$ in $\mathbb{F}_q$ so that decodability is guaranteed.
\end{remark}
\section{Proposed Scheme}
This section is devoted to presenting the general construction of the proposed scheme. We perform the same technique as in Section~\ref{sec2} retrieving the $dt$ matrices $\sum_{\ell=1}^sA_{i,\ell} B_{\ell,j}$ from the polynomial $h(x) = f_A(x) \cdot f_B(x)$.
\bigskip
\noindent \textbf{Choosing the Polynomials:} As described in the introduction, the user partitions the matrices $A \in \mathbb{F}_q^{a \times b}$ and $B \in \mathbb{F}_q^{b \times c}$ as $A = \begin{bmatrix}
A_{i,j}
\end{bmatrix}_{\substack{1\leq i\leq t\\ 1\leq j\leq s}}$
$B = \begin{bmatrix}
B_{i,j}
\end{bmatrix}_{\substack{1\leq i\leq s\\ 1\leq j\leq d}}$ with the purpose of getting the matrix multiplication expressed as \[\displaystyle AB =\begin{bmatrix}
\sum_{\ell=1}^s A_{i,\ell} B_{\ell,j}\end{bmatrix}_{\substack{1\leq i\leq t\\ 1\leq j\leq d}},\] where $A_{i,j}\in\mathbb{F}_q^{\frac{a}{t} \times \frac{b}{s}}$ and $B_{i,j}\in\mathbb{F}_q^{\frac{b}{s}\times \frac{c}{t}}$. To obtain $T$-security $R_1, \ldots, R_T \in \mathbb{F}_q^{\frac{a}{t} \times \frac{b}{s}}$ and $S_1, \ldots, S_T \in \mathbb{F}_q^{\frac{b}{s}\times \frac{c}{t}}$ are chosen independently and uniformly at random. We then define $f_A\in \mathbb{F}_q^{\frac{a}{t} \times \frac{b}{s}}[x,x^{-1}]$ and $f_B\in \mathbb{F}_q^{\frac{b}{s}\times \frac{c}{t}}[x,x^{-1}]$ as the following polynomials
\begin{equation}\label{eq:encfunction}
f_A(x) = \sum_{i=1}^t\sum_{j=1}^s A_{i,j}x^{(i-1)s+j-1} + \sum_{k=1}^{T} R_kx^{ts+k-1},
\end{equation}
\begin{multline*}
f_B(x) = \sum_{i=1}^s\sum_{j=1}^d B_{i,j}x^{(1-j)(ts+T)+(1-i)}+ \\+\sum_{k=1}^{T} S_kx^{(-d)(ts+T)-k+1}.
\end{multline*}
\noindent \textbf{Choosing the Field and Evaluation Points:} Let $J\subset \mathbb{Z}$ be a finite set and $p(x)=\sum_{i\in J}M_ix^i\in \mathbb{F}_q^{m_1\times m_2}[x,x^{-1}]$. Define the support set of $p(x)$ to be \[\mathsf{COEF}_{+} (p)= \{i\in J: M_i\neq 0\}.\] To choose the evaluation points in $\mathbb{F}_q$, we need to look for the $N$-th primitive root of unity $\alpha_N$ that minimizes the set of exponents
$\mathsf{COEF}_{+} (f_A) + \mathsf{COEF}_{+} (f_B) = \mathsf{COEF}_{+} (h)$ under the following conditions:
\begin{itemize}
\item $|\{\alpha_N^i: i\in \mathsf{COEF}_{+} (f_A)\}| = ts + T$
\item $|\{\alpha_N^i: i\in \mathsf{COEF}_{+} (f_B)\}| = ds + T$
\item $|\mathcal{I}|=|\{\alpha_N^{(i-1)s + (1-j)(ts+T)}: 1\leq i\leq t, 1\leq j \leq d\}|=td$
\item $\alpha_N^{z}\notin \mathcal{I}$, for any power $z$ of polynomial $h(x)$ associated to coefficients $A_{i,k_1}B_{k_2,j}$ with $k_1\neq k_2$, and any coefficient multiple of $R_k$ or $S_k$.
\end{itemize}
If $s=1$, then a $N=((d+1)(t+T)-1)$-th primitive root of unity satisfies the conditions. Otherwise, if $s>1$, a $N=(dst+dT+ts-1+T+1)$-th primitive root of unity will do so.
Therefore, Remark \ref{rem:fieldsize} establishes the following condition on the size $q$ of the finite field $ ((d+1)(t+T)-1)\mid q$ if $s=1$, or $(dst+dT+ts-1+T+1)\mid q$, otherwise.
\noindent \textbf{Upload Phase:} The proposed scheme uses $N$ servers, as determined in the previous item. The user uploads $f_A(\alpha^i_N)$ and $f_B(\alpha^i_N)$ to each Server $i$.
\noindent \textbf{Download Phase:} The $i$-th server computes the matrix multiplication $f_A(\alpha^i_N)\cdot f_B(\alpha^i_N)$ and sends its result back to the user.
\noindent \textbf{User Decoding:} In Lemma~\ref{lem:decodability}, we show that the user is able to retrieve $\sum_{\ell=1}^sA_{i,\ell} B_{\ell,j}$ from
$\{h(\alpha^i_N): i\in\{1, \dots, N\}\}$. Combining these, the user can decode \[\displaystyle AB =\begin{bmatrix}
\sum_{\ell=1}^s A_{i,\ell} B_{\ell,j}\end{bmatrix}_{\substack{1\leq i\leq t\\ 1\leq j\leq d}}.\]
\section{Proof of Theorem~\ref{theo:scheme}}
We break the proof into different Lemmas. We show that the proposed scheme is decodable, in Lemma~\ref{lem:decodability}, $T$-secure, in Lemma~\ref{lem:tsecure}, and characterize their performance, in Lemma~\ref{lem:comcosts}. These statements combined prove Theorem~\ref{theo:scheme}.
\begin{lemma}\label{lem:decodability}
Let $A \in \mathbb{F}_q^{a \times b}$, $B \in \mathbb{F}_q^{b \times c}$ be two matrices. Given positive integers $t,d,s$ and $T$ let $(t,d,s)$ be the partition parameters, meaning \[A = \begin{bmatrix}
A_{i,j}
\end{bmatrix}_{\substack{1\leq i\leq t\\ 1\leq j\leq s}},
B = \begin{bmatrix}
B_{i,j}
\end{bmatrix}_{\substack{1\leq i\leq s\\ 1\leq j\leq d}}.\]
Then, $\sum_{k=1}^sA_{i,k}B_{k,j}$ can be decoded using $N$ servers, for $1\leq i\leq t$ and $1\leq j\leq d$.
\end{lemma}
\begin{proof}
Let $f_A(x)\in \mathbb{F}_q^{\frac{a}{d} \times \frac{b}{s}}[x,x^{-1}]$ and $f_B(x)\in \mathbb{F}_q^{\frac{b}{s} \times \frac{c}{t}}[x,x^{-1}]$ be polynomials defined by
\begin{align*}f_A(x) = & \sum_{i=1}^t\sum_{j=1}^s A_{i,j}x^{(i-1)s+j-1} + \sum_{k=1}^{T} R_kx^{ts+k-1},\\ f_B(x) = & \sum_{i=1}^s\sum_{j=1}^d B_{i,j}x^{(1-j)(ts+T)+(1-i)}+\\&\hspace{3.5cm}+ \sum_{k=1}^{T} S_kx^{(-d)(ts+T)-k+1}.
\end{align*}
using the grid product partition for matrices $A$ and $B$, and uniformly distributed random $\mathbb{F}_q$-matrices $R_i,S_i$.
Therefore, $h(x)=f_A(x)\cdot f_B(x)$ is a polynomial where the coefficient of degree $(i-1)s + (1-j)(ts+T)$ is $\sum_{\ell=1}^s A_{i,\ell} B_{\ell,j}$, for $1\leq i\leq t$ and $1\leq j \leq d$.
Let us suppose $s=1$. Consider $\alpha_N$ to be an $N=((d+1)(t+T)-1)$-th primitive root of unity. Since we want to retrieve $\sum_{\ell=1}^s A_{i,\ell} B_{\ell,j}$, for $1\leq i\leq t$ and $1\leq j \leq d$, we need to assure that $\alpha_N^{(i-1) + (1-j)(t+T)}$ is not equal to any $\alpha_N^{z}$, for any degree $z$ of polynomial $h(x)$ associated to coefficients containing $A_{i,j}S_k$, $R_kB_{i,j}$ and $R_{j_1}S_{j_2}$, for $i, j, k, j_1, j_2, k_1, k_2$ in their proper intervals with $k_1\neq k_2$.
We explore all the cases here:
\begin{itemize}
\item \underline{Case $A_{i,j}S_k$:} In this first case, we need to show that $$\alpha_N^{(i_1-1) + (1-j)(t+T)} \neq \alpha_N^{(i_2-1)-d(t+T)-k+1}\mbox{,}$$
for $1\leq i_1, i_2 \leq t$, $1\leq j\leq d$ and $1\leq k \leq T$, which is equivalent to
\begin{multline}\label{case1}
(i_1- i_2) + (d+1-j)(t+T)+k-1\equiv \\
\equiv (i_1-i_2)-j(t+T)+k-1\not\equiv 0 \mod N
\end{multline}
Since $-N=(-d-1)(t+T)+1<(i_1-i_2)-j(t+T)+k-1<0$, then Equation \ref{case1} holds true.
\item \underline{Case $R_kB_{i,j}$:} In this case, we want to ensure $$\alpha_N^{(i-1)+(1-j_1)(t+T)} \neq \alpha_N^{(t+k-1)+(1-j_2)(t+T)}\mbox{,}$$
for $1\leq i \leq t$, $1\leq j_1, j_2\leq d$ and $1\leq k \leq T$, which is equivalent to
\begin{equation}\label{case2}
t+k+(j_1-j_2)(t+T)-i\not \equiv 0\mod N
\end{equation}
\end{itemize}
Since $0<t+k+(j_1-j_2)(t+T)-i\leq t+T+(j_1-j_2)(t+T)-i \leq d (t+T)-i < (d+1)(t+T)-1=N$, then Equation \ref{case2} holds true.
\begin{itemize}
\item \underline{Case $R_{j_1}S_{j_2}$:} For the last case, we need to show that
$$\alpha_N^{(i-1) + (1-j)(t+T)} \neq \alpha_N^{(k_1-k_2)+t-d(t+T)} \mbox{,}$$
for $1\leq i \leq t$, $1\leq j\leq d$ and $1\leq k_1, k_2 \leq T$, which is equivalent to
\begin{multline}\label{case3}
i- 1 + (d+1-j)(t+T)+-t+k_2-k_1\equiv \\
\equiv i-j(t+T)-t+k_2-k_1\not\equiv 0 \mod N
\end{multline}
Since $-N=(-d-1)(t+T)+1<i-j(t+T)-t+k_2-k_1<0$, then Equation \ref{case3} holds true.
\end{itemize}
For the case where $s>1$, we also need to consider all the cases $A_{i,k_1}B_{k_2,j}$, $A_{i,j}S_k$, $R_kB_{i,j}$ and $R_{j_1}S_{j_2}$, which follows analogously to the case $s=1$.
Last steps assure $\alpha_N^{z}\notin \{\alpha_N^{(i-1)s + (1-j)(ts+T)}: 1\leq i\leq t, 1\leq j \leq d\}$, for any degree $z$ of polynomial $h(x)$ associated to coefficients $A_{i,k_1}B_{k_2,j}$ with $k_1\neq k_2$, and any coefficient multiple of $R_k$ or $S_k$.
Using the fact that
\begin{equation}\label{prop:rootofunity}
\sum_{i=1}^N(\alpha_N^i)^s=
\begin{cases}
0, &\text{if }N\nmid s \\
N,& \text{if } N \mid s
\end{cases}
,\end{equation}
for any $N$-th primitive root of unity, we ensure
\[\sum_{\ell=1}^sA_{i,\ell} B_{\ell,j} = \frac{1}{N}\sum_{i=1}^{N}(\alpha_N^i)^{\delta_{i,j}}f_A(\alpha_{N}^i)\cdot f_B(\alpha_{N}^i)\mbox{,}\]
where $\delta_{i,j}=-(i-1)s-(1-j)(ts+T)$.
Decodability is then obtained by repeating this process for every $1 \leq i\leq t$ and $1 \leq j\leq d$:
\[\displaystyle AB =\begin{bmatrix}
\sum_{\ell=1}^s A_{i,\ell} B_{\ell,j}\end{bmatrix}_{\substack{1\leq i\leq t\\ 1\leq j\leq d}}.
\]
\end{proof}
Next, we show that the proposed scheme is $T$-secure.
\begin{lemma}\label{lem:tsecure}
The proposed scheme is $T$-secure.
\end{lemma}
\begin{proof}
Since $f_A(x)$ is independent from $B$ and $f_B(x)$ is independent from $A$, proving $T$-security is equivalent to showing that $I(A;f_A(\alpha_{i_1}), \ldots, f_A(\alpha_{i_T}))=I(B;f_B(\alpha_{i_1}), \ldots, f_B(\alpha_{i_T}))=0$. We prove the claim for $f_A(x)$, since the proof for $f_B(x)$ is analogous.
As defined in Equation \ref{eq:encfunction}, $f_A(x)$ is expressed as
\begin{align*}
f_A(x) = & \sum_{i=1}^t\sum_{j=1}^s A_{i,j}x^{(i-1)s+j-1} + \sum_{k=1}^{T} R_kx^{ts+k-1}.
\end{align*}
Then,
\begin{align*}
&I(A;f_A(\alpha_N^{i_1}), \ldots, f_A(\alpha_N^{i_T}))\\
=&H(f_A(\alpha_N^{i_1}), \ldots, f_A(\alpha_N^{i_T})) - H(f_A(\alpha_N^{i_1}), \ldots, f_A(\alpha_N^{i_T})|A)\\
\le & \sum_{j \in \mathcal{T}}H(f_A(\alpha_N^{j})) - H(f_A(\alpha_N^{i_1}), \ldots, f_A(\alpha_{i_T})|A)\\
=& \sum_{j \in \mathcal{T}}H(f_A(\alpha_N^{j})) - H(f_A^{(T)}(\alpha_N^{i_1}), \ldots, f_A^{(T)}(\alpha_N^{i_T})),\\
=& \frac{Tab}{st}\log(q) - H(f_A^{(T)}(\alpha_N^{i_1}), \ldots, f_A^{(T)}(\alpha_N^{i_T}))\\
\end{align*}
where $f_A^{(T)}(x) = \sum_{k=1}^{T} R_kx^{ts+k-1}$.
\bigskip
Since $\alpha_N$ is an $N$-th primitive root of unity, the evaluation points $\{\alpha_N^i: i\in \mathcal{T}\}$ are all different, and the following matrix has full rank.
\small{
\[
\left(\begin{matrix}
R_1(\alpha_N^{i_1ts})&\!R_1(\alpha_N^{i_2ts})&\cdots& R_1(\alpha_N^{i_Tts})\\
R_2(\alpha_N^{i_1(ts+1)})&\!R_2(\alpha_N^{i_2(ts+1)})&\cdots& R_2(\alpha_N^{i_T(ts+1)})\\
\vdots &\! \vdots & \ddots & \vdots\\
R_T(\alpha_N^{i_1(ts+T-1)})&\!R_T(\alpha_N^{i_2(ts+T-1)})&\cdots& R_T(\alpha_N^{i_T(ts+T-1)})\\
\end{matrix}\right)
\]}
This is because the set of $R_i's$ are linearly independent and the evaluation points are different which implies that $f_A^{(T)}(\alpha_N^{i_j})$'s are uniformly distributed in the space of the matrices $M_{\frac{a}{t}\times \frac{b}{s}}(\mathbb{F}_{q})$. Thus,
$H(f_A^{(T)}(\alpha_N^{i_1}), \ldots, f_A^{(T)}(\alpha_N^{i_T})) = \frac{Tab}{st}\log(q)$,
and therefore, $I(A;f_A(\alpha_N^{i_1}), \ldots, f_A(\alpha_N^{i_T}))= 0$.
\end{proof}
We now characterize the total communication rate.
\begin{lemma}\label{lem:comcosts}
Proposed Scheme have total communication rate
\begin{align*}
\mathcal{R} = \left( N\left(\frac{b}{cts}+\frac{b}{asd}+ \frac{1}{td}\right) \right)^{-1} .
\end{align*}
\end{lemma}
\section*{Acknowledgment}
Felice Manganiello is supported by the NSF under grants DMS-1547399.
\bibliographystyle{IEEEtran}
| {'timestamp': '2022-06-06T02:14:19', 'yymm': '2206', 'arxiv_id': '2206.01559', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01559'} | arxiv |
\section{Introduction}\label{sec:intro}
There is no doubt that modern deep learning techniques have dramatically changed the way engineers approach computer vision problems, replacing hand-engineered image processing algorithms with large neural networks trained end-to-end. While this has improved model performances on a range of tasks, it leaves the underlying algorithms opaque. As deep-learned models become ubiquitous for computer-vision applications, this poses a notable concern, sparking a general interest in neural network \textit{interpretability}.
\par Work in neural network interpretability can be divided into two broad categories, that of data \textit{representation}, and data \textit{processing} \cite{gilpin2019explaining}. Much of the interpretability work in computer vision concerns data representation, or \textit{what} the network represents, in the conceptual sense. The focus on representation usually leads to methods for mapping network features back into pixel space, where the researcher can employ their own visual capacities to make inferences about the latent space of the network. Examples of such representational interpretability methods include viewing the output activation maps of a cnn filter \cite{Yosinski_deepviz_toolbox}, the attention map in a visual transformer\cite{dino}, viewing dataset examples or feature visualizations \cite{deepviz,olah2017feature} that maximally excite/inhibit a latent feature, or attribution methods \cite{gradcam,Zeilerdeconvolution,integrad} that highlight pixel regions most responsible for a model's response. Other work \cite{netdissect} ascribes semantic labels to latent features that align with the annotations in densely segmented image sets \cite{datasetade,datasetcontext,datasetintrinsic,datasetparts,datasettextures}.
Much less common are accounts of data processing, e.g. an interpretable sequence of computations that generate representations. So, while a researcher might be confident a feature in their model acts as, say, a brown fur detector, this is not necessarily coupled with a formal understanding of how a brown fur detector is built. In general, while it is often possible to trace how the first layer of features are constructed from weights over the input in a deep net, the computation graph becomes increasingly unwieldy when considering features in later layers.
\par
\begin{figure}
\centering
\includegraphics[width=\textwidth]{circuit_diagram_comp.jpg}
\caption{An \textit{extended circuit diagram} of feature \textit{conv3:56} in Alexnet. See section \ref{sec:diagram} for a full account.}\label{fig:1}
\end{figure}
The architectural constraint of convolutional neural networks allows for greater \textit{data processing} interpretability than many other deep models. The kernel convolution operation not only reduces the number of parameters to contend with by replicating weights across space, but also constrains the function space learnable by the network to a familiar subspace. Kernel convolution operations are typical in hand-engineered image processing algorithms, where single kernels can enable filters for edge detection, sharpening, blurring, spatial frequency filtering, etc \cite{cv_book,sobel}. Composing filters in a hierarchy enables the construction of more complex detectors, with each kernel acting as a spatial template for the arrangement of features from the previous layer. Cammarata et al (2020) \cite{circuitsthread} show that viewing feature visualizations in conjunction with the kernels connecting them provides strong visual intuition for how simple features are combined into complex ones. The authors describe many interesting 'circuits' they’ve discovered in InceptionV1 \cite{inception}, from early circuits encoding curves and basic shapes, to late-layer circuits encoding real-world objects. A prototypical circuit from their work shows how a car feature is constructed with three kernels spatially arranging features in the previous layer for windows, wheels, and car bodies \cite{circuitszoomin}.
\par
Circuits provide a promising framework for interpreting the image filtering processes latent in CNNs, and this work aims to bolster the approach by addressing two related issues. Firstly, when considering the aforementioned 'car circuit' composed of wheel and window features, the immediate questions arise, 'But what then is the wheel circuit? What is the window circuit? I can't fully grasp the car feature without grasping these constituent parts.' As such, it would be useful to \textit{extend} circuit diagrams backwards layer-wise towards the inputs, as diagrammed in Fig \ref{fig:1}. Such a diagram runs the risk of being massive and unparsable, presenting our second issue; which kernels (edges) do we include in the diagram, and how do we avoid over-simplifying our target feature given our exclusions? This concern with over-simplification is also present in the original circuit work; diagramming the car feature with 3 kernels is certainly parsimonious, but ignoring the effects of the hundreds of other kernels in the original filter may result in a much degraded feature.
\par In the present work, we address these issues by re-purposing techniques from neural network pruning for \textit{circuit extraction}. We'll compare the efficacy of several saliency-based pruning methods for extracting sparse sub-networks that preserve a target feature's responses to input images \textit{without fine-tuning}. The differences in responses returned by such a circuit formalize the effect of an interpretability researcher \textit{zooming in} (to use the term from \cite{circuitszoomin}), focusing on some computations while ignoring others, as is a pragmatic necessity. Further, our method allows the researcher to zoom-in in a principled way, by identifying small subsets of computations that approximate the original feature when considered in isolation. In a follow-up set of experiments, we will show how our method can be used to extract \textit{sub-feature} circuits, which preserve feature responses only to a target set of images, dividing complex features into component parts. Lastly, we will explain how sparse circuits can be visualized with our circuit diagramming tool (Fig \ref{fig:1}).
\par
\section{Methods}\label{sec:methods}
\subsection{Notation}\label{sec:notation}
This work concerns convolutional layers in deep neural networks. The \(l\)th convolutional layer takes a stack of \textit{activation maps} as input, \(\boldsymbol{A}^{l-1} \in \mathbb{R}^{C_{\text {in}} \times H_{\text {in }} \times W_{\text {in }}}\) and outputs the activation maps \(\mathbf{A}^{l} \in \mathbb{R}^{C_{\text {out}}\times H_{\text {out}} \times W_{\text {out}}}\). The layer is composed of \(C_{\text {out}}\) \textit{filters} (one for each output channel), each parameterized by weights \(\mathbf{w}^{l}_{c_{\text{out}}} \in \mathbb{R}^{C_{\text {in}} \times K_{h} \times K_{w}}\) and bias \(b^{l}_{c_{\text{out}}} \in \mathbb{R}\). Each filter transforms input activation maps to output maps by;
\begin{equation} \label{eq:filter eq}
\begin{gathered}
\mathbf{A}^{l}_{c_{\text{out}}} = \sum_{c_{\text{in}=1}}^{C_{\text {in}}} \mathbf{w}^{l}_{c_{\text{out}}, c_{\text{in}}} * \boldsymbol{A}^{l-1}_{c_{\text{in}}}+b^{l}_{c_{\text{out}}},
\end{gathered}
\end{equation}
where \(*\) denotes the convolution.
A filter is composed of \(C_{\text{in}}\) 2D \textit{kernels} with weights \(\mathbf{w}^{l}_{c_{\text{out}},c_{\text{in}}} \in \mathbb{R}^{K_{h} \times K_{w}}\) which compute the kernel-wise activation map \(\mathbf{A}^{l}_{c_{\text{out}},c_{\text{in}}} \in \mathbb{R}^{H_{\text {out}}\times W_{\text {out}}}\), before the filter sums these maps element-wise and adds its bias. Individual activations in any activation map are denoted as \(a^{l}_{c_{\text{out}},c_{\text{in}},h,w}\). A \textit{feature} refers to the full function from pixel-space that returns a particular activation, denoted \(\mathcal{F}(x) = a\). An activation map returns the same feature \(H_{\text {out }} \times W_{\text {out }}\) times with respect to the \textit{image patches} in each activation's effective receptive field \cite{recep_field_1,recep_field_2}. For the pruning methods section, \(\boldsymbol{\theta} = \left\{\theta_{j}\right\}_{j=1}^{m}\) refers to the flattened vector of all network parameters.
\subsection{Problem Statement}\label{sec:problem}
We endeavor to simplify the data processing underlying a particular feature by removing parameters from the network, while minimally affecting the feature's activations. We can formulate our \textit{circuit pruning} problem similarly to conventional pruning; given a latent feature \(\mathcal{F}\) in a network and a set of input images (or image patches) \(\mathcal{D}=\left\{\mathbf{x}_{i}\right\}_{i=1}^{n}\), we want to identify a subnetwork parameterized by \(\boldsymbol{\bar{\theta}}\) under a sparsity constraint, such that the change in \(\mathcal{F}\)'s responses to \(\mathcal{D}\) is minimized:
\begin{equation} \label{eq:problem form 1}
\begin{gathered}
\underset{\boldsymbol{\bar{\theta}}}{\arg \min } \Delta\mathcal{F}(\boldsymbol{\bar{\theta}},\boldsymbol{\theta} ; \mathcal{D}):= \sum_{i=1}^{n}\left|\mathcal{F}\left(\boldsymbol{\theta} ;\mathbf{x}_{i}\right) -\mathcal{F}\left(\boldsymbol{\bar{\theta}} ;\mathbf{x}_{i}\right)\right| \\
\text { s.t. } \quad \left\|\boldsymbol{\bar{\theta}}\right\|_{0} \leq \kappa , \quad \bar{\theta}_{j} \in \{\theta_{j},0\} \,\, \forall j \in \{1 \ldots m\}
\end{gathered}
\end{equation}
\(\boldsymbol{\bar{\theta}}\) corresponds to a sparse path of computations through the full network that generates an approximation of the target feature, with no more than \(\kappa\) parameters. The constraint that \( \bar{\theta}_{j} \in \{\theta_{j},0\} \,\, \forall j \in \{1 \ldots m\}\) ensures that we cannot fine-tune the network, that circuits we extract are latent within the network \textit{as is}.
\par
As is typical with pruning problems, finding an optimal \(\boldsymbol{\bar{\theta}}\) cannot be brute forced, as there exist \(m\choose\kappa\) possible parameterizations. Fortunately, many saliency-based approaches to pruning have a similar problem statement to (eq \ref{eq:problem form 1}) in that they endeavor to find a sparse \(\boldsymbol{\bar{\theta}}\) that minimally changes the loss function \(\mathcal{L}\) of the original model. Such methods consider quickly-computable, parameter-wise \textit{saliency criteria} \(\boldsymbol{S}(\theta_{j})\) meant to approximate \(|\Delta\mathcal{L}|\) induced by removing individual parameters. With a simple substitution of \(\mathcal{F}\) for \(\mathcal{L}\), these saliency criteria should be well suited for our problem. We can then replace (eq \ref{eq:problem form 1}) with the simpler problem of identifying a parameterization \(\boldsymbol{\bar{\theta}}\) with maximal cumulative saliency;
\begin{equation} \label{eq:problem form saliency}
\begin{gathered}
\underset{\boldsymbol{\bar{\theta}}}{\arg \max } \boldsymbol{S}_{sum}(\boldsymbol{\bar{\theta}})\coloneqq \sum_{j\in supp(\boldsymbol{\bar{\theta}})}\boldsymbol{S}(\theta_{j}) \\
\text { s.t. } \quad \left\|\boldsymbol{\bar{\theta}}\right\|_{0} \leq \kappa , \quad \bar{\theta}_{j} \in \{\theta_{j},0\} \,\, \forall j \in \{1 \ldots m\}
\end{gathered}
\end{equation}
Where solving problem (eq \ref{eq:problem form 1}) is hard, solving problem (eq \ref{eq:problem form saliency}) is easy, just choose paramaters \(\theta_{j}\) with the top-\(\kappa\) \(\boldsymbol{S}(\theta_{j})\) for inclusion in \(\boldsymbol{\bar{\theta}}\).
\par
In this work we test the efficacy of 3 saliency criteria from the literature on our circuit pruning problem, \textit{SNIP} \cite{snip,mozer_prune}, \textit{FORCE} \cite{FORCE}, and \textit{actgrad} \cite{actgrad}. These are all first order saliency criteria, utilizing gradients. While other methods exist that utilize the Hessian \cite{braindamage,brainsurgeon,grasp}, these are motivated by the observation that training a network with gradient descent should push \(\frac{{\delta\mathcal{L}}}{\delta\boldsymbol{\theta}}\) to 0, but this does not necessarily hold for \(\frac{{\delta\mathcal{F}}}{\delta\boldsymbol{\theta}}\).
\subsection{Circuit SNIP}\label{sec:SNIP}
While the SNIP saliency criterion was originally introduced in \cite{mozer_prune}, Lee et al (2018) \cite{snip} demonstrated the criterion's efficacy for \textit{single-shot} pruning at initialization \cite{grasp,snipit,FORCE}, which utilizes no fine-tuning, making the criterion promising for our application. In SNIP, a binary mask \(\mathbf{c} \in\{0,1\}^{m} \) is inserted into the network, such that the new network is parameterized by \(\mathbf{c} \odot \boldsymbol{\theta}\), where \(\odot\) denotes the Hadamard product. In the original un-pruned network, \(\mathbf{c} = \{1\}^{m}\). When \(c_{j} = 0\), this is equivalent to parameter \(\theta_{j}\) being pruned from the network. The authors reason the importance of parameter \(\theta_{j}\) to be proportional to the effect on the loss were it to be removed, or equivalently \(c_{j} = 0\):
\begin{equation}
\Delta \mathcal{L}_{j}(c_{j} ; \mathcal{D})=\mathcal{L}(c_{j} = 1; \mathcal{D})-\mathcal{L}\left(c_{j} = 0 ; \mathcal{D}\right),
\end{equation}
The authors' \textit{connection sensitivity} saliency criterion considers the gradient of \(\mathcal{L}\) with respect to \(c_{j}\). \(|\partial \mathcal{L} / \partial c_{j}|\) measures the sensitivity of \(\mathcal{L}\) to perturbations of \(c_{j}\), which they regard as an approximation of the \(|\Delta \mathcal{L}_{j}|\) induced by setting \(c_{j}=0\).
Their criterion can be equivalently calculated as the magnitude of parameters multiplied by their gradients:
\begin{equation}
\boldsymbol{S}_{snip}(\boldsymbol{\theta}):=\left|\partial \mathcal{L} / \partial \mathbf{c} \right|=\left|\frac{\partial \mathcal{L}(\boldsymbol{\theta} \odot \boldsymbol{c})}{\partial \boldsymbol{c}}\right|_{\mathbf{c}=\mathbf{1}}=\left|\frac{\partial \mathcal{L}}{\partial \boldsymbol{\theta}} \odot \boldsymbol{\theta}\right|
\end{equation}
We are interested in identifying network parameters that will affect some target feature's average response when removed, rather than the loss. We thus formulate the circuit SNIP saliency criterion with the simple \(\mathcal{F}\) for \(\mathcal{L}\) substitution proposed above:
\begin{equation}
\boldsymbol{S}_{snip}(\boldsymbol{\theta};\mathcal{F}):=\left|\partial \mathcal{F} / \partial \mathbf{c} \right|=\left|\frac{\partial \mathcal{F}}{\partial \boldsymbol{\theta}} \odot \boldsymbol{\theta}\right|
\end{equation}
\subsection{Circuit Force}\label{sec:FORCE}
The above SNIP criterion considers the effects of removing parameters in isolation, where in actuality we are endeavoring to remove many parameters from the network. Removal of a particular \(\theta_{j}\) may have a very different effect when the network is fully-intact versus removal when other parameters are also pruned. Suppose our sparse network is parameterized by \(\boldsymbol{\bar{\theta}}\), then \(\boldsymbol{S}_{snip}(\boldsymbol{\bar{\theta}})\) will certainly be different than \(\boldsymbol{S}_{snip}(\boldsymbol{\theta})\), as the gradients passing through the network will be different. Motivated by this observation, de Jorge et al (2020) \cite{FORCE} (and similarly \cite{snipit}) developed the \textit{FORCE} saliency criterion (foresight connection sensitivity), which attempts to identify important parameters for the resultant sparse network, despite the unfortunate circularity that this sparse network is supposed to be identified \textit{by way of} the saliency criterion. The author's make a subtle adjustment to the saliency-based pruning problem statement (eq \ref{eq:problem form saliency});
\begin{equation} \label{eq:problem form force}
\begin{gathered}
\underset{\boldsymbol{\bar{\theta}}}{\arg \max } \boldsymbol{S}_{force\_sum}(\boldsymbol{\bar{\theta}})\coloneqq \sum_{j\in supp(\boldsymbol{\bar{\theta}})}\boldsymbol{S}_{snip}(\bar{\theta_{j}}) \\
\text { s.t. } \quad \left\|\boldsymbol{\bar{\theta}}\right\|_{0} \leq \kappa , \quad \bar{\theta}_{j} \in \{\theta_{j},0\} \,\, \forall j \in \{1 \ldots m\}.
\end{gathered}
\end{equation}
They still endeavor to find a \(\boldsymbol{\bar{\theta}}\) with maximum cumulative saliency, but when parameter-wise saliency is measure in the pruned network, rather than the original network as in (eq \ref{eq:problem form saliency}).
\par
Unfortunately (eq \ref{eq:problem form force}) is not trivial to solve as is (eq \ref{eq:problem form saliency}), but the authors reason an approximate solution can be obtained by iteratively masking an increasing number of parameters, recomputing \(\boldsymbol{S}_{snip}(\boldsymbol{\bar{\theta}})\) at each step to get the next mask by way of (eq \ref{eq:problem form saliency}). Let's call the network parameterization after the first masking iteration \(\boldsymbol{\bar{\theta}}_{1}\), the second \(\boldsymbol{\bar{\theta}}_{2}\), up to the final iteration \(T\) with a parameterization at the desired sparsity \(\boldsymbol{\bar{\theta}}_{T}\). The motivating intuition for this iterative sparsification follows from the observation that the fewer parameters are masked from \(\boldsymbol{\theta}\) to obtain \(\boldsymbol{\bar{\theta}}_{1}\), the better the \textit{gradient approximation} \(\frac{\delta\mathcal{L}(\boldsymbol{\theta})}{\delta\boldsymbol{\theta}} \approx \frac{\delta\mathcal{L}(\boldsymbol{\bar{\theta}}_{1})}{\delta\boldsymbol{\bar{\theta}}}_{1}\) should hold, and we can use \(\boldsymbol{S}_{snip}(\boldsymbol{\theta})\) to approximate \(\boldsymbol{S}_{snip}(\boldsymbol{\bar{\theta}}_{1})\). This logic is inductive; \(\boldsymbol{S}_{snip}(\boldsymbol{\bar{\theta}}_{1})\) is a better approximation of \(\boldsymbol{S}_{snip}(\boldsymbol{\bar{\theta}}_{2})\) than \(\boldsymbol{S}_{snip}(\boldsymbol{\theta})\) (as there are fewer parameters masked between \(\boldsymbol{\bar{\theta}}_{1}\) and \(\boldsymbol{\bar{\theta}}_{2}\)), \(\boldsymbol{S}_{snip}(\boldsymbol{\bar{\theta}}_{3})\) is better approximated by \(\boldsymbol{S}_{snip}(\boldsymbol{\bar{\theta}}_{2})\) than any of the previously computed scores, etc. In general \(S(\boldsymbol{\theta}_{T})\) should be calculated with many iterations of \(\boldsymbol{S}_{snip}\), resulting in a small difference in the masks between iterations, to optimize (eq \ref{eq:problem form force}). In this work we implement \textit{FORCE} with 10 iterations and the exponential decay scheduler from \cite{FORCE}, which
were shown to be effective hyper-parameters in the original work (\textit{appendix}). We note that while optimizing (eq \ref{eq:problem form force}) may lead to a \textit{trainable} model parameterization with high connection sensitivity (as was the intention in the original work), we explicitely want to minimize \(\Delta\mathcal{F}(\boldsymbol{\theta},\boldsymbol{\theta}_{T})\). With \textit{FORCE}, at each iteration we are approximating \textit{an approximation}, \(\Delta\mathcal{F}(\boldsymbol{\theta}_{i-1},\boldsymbol{\theta}_{i})\). This could lead to divergence from \(\mathcal{F}\), depending on the accuracy of the iterative approximations.
\par
\subsection{Circuits by Taylor Expansion}\label{sec:taylor}
Another way of deriving an approximation for \(\Delta \mathcal{L}\) given the removal of a parameter is by Taylor approximation. This approach was employed successfully by Molchanov et al (2019) \cite{actgrad} for the pruning of convolutional filters. Their saliency criterion concerns the activations in the network, rather than the weights themselves. Suppose some particular activation $a_{j}$ in the network were to be masked (set to 0), then the first order Taylor approximation of the loss is:
\begin{equation} \label{eq:taylor 1}
\mathcal{L}(a_{i}=0) = \mathcal{L}(a_{i}) - \frac{\delta \mathcal{L}}{\delta a_{i}}a_{i}
\end{equation}
As per usual, the authors wanted their salience criteria for an activation to approximate the magnitude of the change in loss when that activation is masked, which can be approximated with (eq \ref{eq:taylor 1});
\begin{equation}\label{eq:taylor orig}
\boldsymbol{S}_{actgrad}(a_{i}):=\left| \mathcal{L}(a_{i}) - \mathcal{L}(a_{i}=0) \right| = \left|\frac{\partial \mathcal{L}}{\partial a_{i}} \odot a_{i}\right|
\end{equation}
As we did for SNIP, we can formulate an equivalent circuit saliency criterion by substituting \(\mathcal{L}\) with \(\mathcal{F}\):
\begin{equation}\label{eq:taylor circuit}
\boldsymbol{S}_{actgrad}(\boldsymbol{a};\mathcal{F}):= \left|\frac{\partial \mathcal{F}}{\partial \boldsymbol{a}} \odot \boldsymbol{a}\right|
\end{equation}
Notice that this criterion is equivalent to \(\mathbf{S}_{snip}\), applied to activations as opposed to weights. Relatedly, the above taylor derivation is applicable to \(\mathbf{S}_{snip}\), and as such we denote this saliency criteria \(\mathbf{S}_{actgrad}\), rather than \(\mathbf{S}_{taylor}\) as in \cite{actgrad}.
\subsection{Structured Pruning of Kernels}
It is sometimes practical to prune \textit{structurally}, i.e. with respect to architecturally related groups of parameters. In the case of CNNs, this has typical meant pruning entire convolutional filters \cite{actgrad,thinet,filterentropy,filterentropy,ganpruning,filteredge,autofilter,softfilter,globalfilter,oraclefilter}, as this leads to models that are resource efficient when implemented with BLAS \cite{BLAS} libraries. Our goal is not resource efficiency, but rather to extract interpretable circuits from the model, and as such we will prune with respect to individual convolutional \textit{kernels} \cite{kernel_pruning_interpret,kernel_pruning,kernel_regularization,kernelexplore}. Kernels constitute the edges of our desired circuit diagrams (Fig \ref{fig:1}), thus an extracted circuit with kernel sparsity should make for a maximally parsable diagram. To compute \textit{kernel-wise} saliency scores, we simply average the saliency scores of the parameters within each kernel. For \(\boldsymbol{S}_{snip}\) (and by extension \(\boldsymbol{S}_{force}\)), this is the average saliency of each of the kernel's weights. For \(\boldsymbol{S}_{actgrad}\), we average activations across the kernel-wise activation map. For a kernel \(k\) with weights \(\mathbf{w}\) and kernel-wise activation map \(\boldsymbol{A}\);
\begin{equation} \label{eq:kernel snip}
\boldsymbol{S}_{snip}(k) \coloneqq \frac{1}{K_{w}K_{h}}\sum_{w=1}^{K_{w}}\sum_{h=1}^{K_{h}}\boldsymbol{S}_{snip}({w_{h,w}})
\end{equation}
\begin{equation}\label{eq:kernel actgrad}
\boldsymbol{S}_{actgrad}(k) \coloneqq \frac{1}{H_{\text{out}}W_{\text{out}}}\sum_{w=1}^{W_{\text{out}}}\sum_{h=1}^{H_{\text{out}}}\boldsymbol{S}_{actgrad}({a_{h,w}})
\end{equation}
Pruning kernels to sparsity \(\kappa\) requires sorting the kernel-wise saliency scores and keeping the top-\(\kappa\) kernels, as before.
\section{Experiments}\label{sec:experiments}
All of the following experiments were conducted with a single NVIDIA \textit{GeForce RTX 2080 Ti} GPU. All feature visualizations in this work were generated using the \textit{Lucent} library \cite{lucent} (under an Apache License 2.0), a PyTorch implementation of \textit{Lucid} \cite{olah2017feature}, using the default hyper-parameters.
\subsection{Methods Comparison}\label{sec:methodcompare}
\par
To test our circuit pruning methods for feature preservation, we pruned circuits for features in an Imagenet \cite{imagenet_cvpr09} trained Alexnet \cite{alexnet}. We tested two versions of this model, one trained in the typical manner, as is available through the Pytorch modelzoo \cite{pytorch}, and one we trained with hierarchical group sparsity regularization \cite{hierarch_reg}. This regularization encourages groups of parameters (kernels and filters) towards zero magnitude during training \textit{(appendix)}. If we endeavor to find sparse circuits within a model, we reason it is useful to start with a model that already sparsely achieves the objective. We selected 20 random features from the last 3 of the model's convolutional layers on which to test our methods. For each feature, we average the activations it returns to a subset of 2000 random images from Imagenet (2 images per category). This is the value for \(\mathcal{F}\) we use to compute kernel-wise saliency scores for each pruning method. As a baseline method, we additionally compute a \textit{magnitude} kernel-wise saliency score, equal to the average magnitude of each weight in the kernel;
\begin{equation} \label{eq:magnitude}
\boldsymbol{S}_{magnitude}(k) \coloneqq \frac{1}{K_{w}K_{h}}\sum_{w=1}^{K_{w}}\sum_{h=1}^{K_{h}}|w_{h,w}|
\end{equation}
Using these saliency scores, we then extracted circuits at 13 sparsities, preserving 99\%-.1\% of the \textit{relevant} kernels with highest saliency. By \textit{relevant}, we mean kernels that could possibly influence the target feature's activations. These include all the kernels in the preceding layers and those kernels that belong to the feature's filter itself, but no other kernels from that filter's layer or later layers. For each of these extracted circuits, we computed the absolute value of the Pearson correlation between the original, un-pruned features' activations to the 2000 images and the corresponding circuit features' activations. This metric measures the linearity of the relationship between the circuit feature and the original feature.
\par
Fig \ref{fig:2} shows how well feature activations were preserved (|Pearson's R|), as a function of circuit sparsity, with separate lines for the three pruning methods, as well as the magnitude baseline method. The results show that \textit{actgrad} is generally most effective for the Alexnet model, while \textit{actgrad}, \textit{SNIP} and \textit{FORCE} perform similarly on the regularized Alexnet. \textit{FORCE} shows a slight improvement with respect to the other metrics at the highest sparsities measured (though this effect is minimal, with a higher correlation of only \( \Delta R \approx .08\). The results in \cite{FORCE} showed \textit{FORCE} is most effective in the high sparsity regime, and our results converge with this finding. Overall, all methods are able to extract sparse feature-preserving circuits well, outperforming the baseline magnitude saliency criterion.
\par
These circuit extraction experiments also show that features in Alexnet are not homogenously sparse. Some features can maintain a high correlation with the full-model feature counterpart, even at extreme sparsities, while other features degrade quickly as more kernals are pruned. To get the full picture of the distribution of feature sparsities, we moved beyond the 60 features tested for methods comparison and next extracted circuits for every feature in the last 3 convolutional layers of Alexnet (896 features), using the \textit{actgrad} method. We did not test all these features in the previous methods comparison experiment due to the long compute times for the \textit{FORCE} method.
Fig \ref{fig:3} shows these distributions of correlations for both models. Nearly all features tested are preserved (Pearson's R > .99) at sparsities up to ~50\% in the regularized model. At higher sparsities (\(\geq 20\%\)) there is increasingly high variance in the correlations across features, but individual features can be identified that are well preserved at even the highest sparsity tested (.1\% of relevant kernels kept).
\begin{figure}
\centering
\begin{minipage}{0.4\textwidth}
\centering
\includegraphics[width=\textwidth]{method_comparison_all.png}
\caption{methods comparison.}\label{fig:2}
\end{minipage}\hfill
\begin{minipage}{0.6\textwidth}
\centering
\includegraphics[width=\textwidth]{alexnet_sparse_noconv2_pearson_boxplot_actxgrad_withsparse_big.png}
\caption{distributions of circuit/model feature correlations}\label{fig:3}
\end{minipage}
\end{figure}
\subsection{Sub-Feature Circuits}\label{sec:subfeature}
The circuits we've extracted so far attempt to capture features as a whole, maintaining their responses to a broad sample of image patch inputs, but it may be useful for an interpretability researcher to extract \textit{sub-feature} circuits, which preserve responses to a targeted selection of image patches. We are motivated here by the observation of \textit{poly-semantic} \cite{polysemanticandreas,olah2017feature,circuitszoomin,polysemanticvec} features in CNNs, which respond selectively and highly to seemingly disparate semantic categories. Poly-semantic features may be composed of multiple, separable circuits with their own constituent kernels, with each circuit responsible for detecting only one of the semantic categories. The \textit{general} circuit for a poly-semantic feature would then be the union of these category-wise circuits. In this case, an interpretability researcher should study these sub-feature circuits independently, as they constitute distinct image filtering processes. These sub-feature circuits would have the additional benefit of being ostensibly sparser than the general circuit for a feature.
\par
To identify candidate poly-semantic features for our \textit{sub-feature} extraction experiments, we took a data-driven approach. For each feature \(\mathcal{F}^{l}_{j}\) in the regularized Alexnet convolutional layers, we identified the top 300 individual activations it produced in response to the ImageNet training set, under the constraint that no two activations belong to the same activation map (are responses to different parts of the same image). Let \(\mathbf{a}^{l}_{j} = \{a_{j,i}\}_{i=1}^{300}\) refer to these activations, and \(\mathcal{D}^{l}_{j} = \{\mathbf{x}^{l}_{j,i}\}_{i=1}^{300}\) refer to the corresponding image patches in each activation's effective receptive field. We then consider layer \(l\)'s \textit{population} response to \(\mathcal{D}^{l}_{j}\), a set of 300 \textit{activation vectors} \(\mathcal{P}^{l}_{j}\):
\begin{equation} \label{eq:population vecs}
\mathcal{P}^{l}_{j} := \{p^{l}_{j,i}\}_{i=1}^{300} :=
\{\{\mathcal{F}_{h}^{l}(\mathbf{x}^{l}_{j,i})\}_{h=1}^{C_{\text{out}}}\}_{i=1}^{300}
\end{equation}
We reason that for a candidate poly-semantic feature \(\mathcal{F}_{j}^{l}\), the set \(\mathcal{P}^{l}_{j}\) should be clusterable. This would suggest \(\mathcal{D}^{l}_{j}\)
is represented as distinct groups in layer \(l\)'s representation space, while the supposed poly-semantic feature \(\mathcal{F}_{j}^{l}\) makes no such distinction, as its activations \(\mathbf{a}^{l}_{j}\) are all very high, given our selection criteria for \(\mathbf{a}^{l}_{j}\).
\par
We used HDBScan clustering \cite{HDBScan} to search for features with clusterable \(\mathcal{P}^{l}_{j}\) (under a BSD 3-Clause license). HDBScan works well in high-dimensions and requires only a minimum cluster size as its hyperparameter (we used 10). It will return anywhere from 0 to 30 clusters (300/10), allowing us to ignore filters that don't show good clustering, and dissect other filters with respect to potentially many semantic groups (although in practice this approach rarely returned more than 2 clusters) (\textit{appendix}).
\par
\begin{figure}
\centering
\begin{minipage}{0.49\textwidth}
\centering
\includegraphics[width=\textwidth]{905_combined_fig.png}
\caption{terrier/metal sub-feature circuits from clusters}\label{fig:4}
\end{minipage}\hfill
\begin{minipage}{0.49\textwidth}
\centering
\includegraphics[width=\textwidth]{905_mixed_combined_fig.png}
\caption{sub-feature circuits from mixed cluster}\label{fig:5}
\end{minipage}
\begin{minipage}{0.49\textwidth}
\centering
\includegraphics[width=\textwidth]{1057_combined_fig.png}
\caption{monkey/text sub-feature circuits}\label{fig:6}
\end{minipage}\hfill
\begin{minipage}{0.49\textwidth}
\centering
\includegraphics[width=\textwidth]{circle_combined_fig.png}
\caption{large/small circle sub-feature circuits}\label{fig:7}
\end{minipage}
\end{figure}
Fig \ref{fig:4} shows the results of a pruning experiment on feature \textit{Conv5:9} in regularized Alexnet. Our clustering analysis revealed this as a candidate poly-semantic filter, returning two distinct clusters, \(\mathcal{P}_{1}\) and \(\mathcal{P}_{2}\). Qualitatively, the image patches corresponding to \(\mathcal{P}_{1}\) and \(\mathcal{P}_{2}\) (\(\mathcal{D}_{1}\) and \(\mathcal{D}_{2}\)) look distinct, with one cluster corresponding to terrier faces, and the other corresponding to metal cylinders with horizontal lines, as can be seen in the sample of image patches in the top right of Fig \ref{fig:4}. Next, we extracted different circuits for \textit{Conv5:9}, which were intended to preserve \textit{Conv5:9}'s responses to either \(\mathcal{D}_{1}\) or \(\mathcal{D}_{2}\), using saliency scores \(\boldsymbol{S}_{actgrad}(\mathbf{k};\mathcal{F};\mathcal{D}_{1})\) and \(\boldsymbol{S}_{actgrad}(\mathbf{k};\mathcal{F};\mathcal{D}_{2})\). Rather than prune circuits from the full model, we start pruning from the \textit{general circuit}, extracted in the previous experiment (sec \ref{sec:methodcompare}), at 50\% sparsity. This general circuit shows a very high correlation to the original filter's activations (>.999 Pearson R). We extract the sub-filter circuits at 70 linearly spaced sparsities, preserving 49.99\%-.5\% of the relevant kernels in the original model. The line plot in Fig \ref{fig:4} shows how these sub-filter circuits' activations deviate from the general circuit's activations as a function of sparsity. The Y-axis shows a normalized measure of this deviation. For a sub-feature circuit parameterized by \(\boldsymbol{\bar{\theta}}\) and the general circuit by \(\boldsymbol{\theta}_{gen}\);
\begin{equation} \label{eq:F norm}
\Delta\mathcal{F}_{norm}(\boldsymbol{\theta}_{gen},\boldsymbol{\bar{\theta}};\mathcal{D}) := \frac{\Delta\mathcal{F}(\boldsymbol{\theta}_{gen},\boldsymbol{\bar{\theta}};\mathcal{D})}{\frac{1}{n}\sum_{i=1}^{n}\mathcal{F}(\boldsymbol{\theta}_{gen};\mathbf{x}_{i})}
\end{equation}
With this metric, we can see how the sub-circuit's activations deviate from the general circuit's activations as a proportion of the general circuit's activation magnitude. The solid lines show how the activations the circuit was meant to preserve deviate from the respective general circuit activations. Overall, we were able to extract sub-feature preserving circuits to high levels of sparsity.
\par
Critically, we next examined how well these sub-feature circuits responded to the other cluster's image patches (dotted lines). If the circuits act as distinct feature detectors, these responses should be far less preserved. The dotted lines in this plot clearly deviate at lower sparsities than the solid lines; we've identified circuits that preserve \textit{Conv5:9} responses to only terriers but not metal cylinders, and visa-versa. To quantify the extent to which these specific sub-feature circuits involve different computations, we computed the intersection over union (IoU) of the sets of kernels belonging to each circuit. We compare the circuits at the last sparsity for which our \(\Delta\mathcal{F}_{norm}\) remains below .15 for each circuits' target activations. This intersection over union is shown as a function of layer depth in the bottom-right of Fig \ref{fig:4}. It seems the two sub-feature circuits utilize the same layer 1 computations (gabors, center-surround filters etc.) but deviate from one another in subsequent layers. We also render feature visualizations for these extracted circuits, shown above the IoU plot. These show a clear distinction between the sub-feature circuits as well.
Fig \ref{fig:6} shows the same analyses again, but for feature conv5:161, which is poly-semantic across monkey faces and written text.
\par
As a control analysis, we extracted two new sub-feature circuits, this time with respect to a random 50/50 split of image patches from \(\mathcal{D}_{1}\) and \(\mathcal{D}_{2}\). We hypothesized that these sub-feature circuits would not be separable. The results are shown in Fig \ref{fig:5} and confirm our hypothesis, indicated by the overlap between the solid and dashed lines, and the high IoU plot across the layers. Thus, for this feature, while separable sub-feature circuits exist for processing terrier faces and metal cylinders, they do not exist for any arbitrary set of images.
\par
Finally, to test whether separable sub-feature circuits could be extracted without utilizing our clustering procedure, we attempted to \textit{split} feature \textit{Conv4:53} in a hypothesis-driven way. The top 300 highest activating image patches for \textit{Conv4:53} show cocentric circles (\textit{appendix}), and we hypothesized there may be separable circuits responsible for the feature's response to large circles versus small circles, resulting in a scale-invariant circle detector. We attempt to isolate these circuits by extracting with respect to the two simple images in the top right of Fig \ref{fig:7}, fit to the effective receptive field of \textit{Conv4:53}. The pattern of data in Fig \ref{fig:7} reveals that this feature can indeed be split into separable circuits with respect to these images.
\section{Extended Circuit Diagrams}\label{sec:diagram}
Circuit pruning allows us to extract sparse sub-networks from a CNN that preserve the responses of targeted features. This reduces the size of features' computation graphs, and allows for detailed inspection of how rich features are built. To facilitate this inspection, we have developed a tool for \textit{extended circuit diagrams}. Fig \ref{fig:1} shows an extended circuit diagram for \textit{conv3:56}, a feature that can be preserved at high sparsities according to our pruning experiments (sec \ref{sec:methodcompare}). Following Olah et al (2020) \cite{circuitszoomin}, edges in this diagram represent convolution with a 2D kernel, and vertices represent filters. Edge lines are colored based on the inhibition/excitation of their corresponding kernel (red for excitation, blue for inhibition, and gray for a mixture). The width of each edge line is proportional to the \textit{actgrad} saliency score it received when pruning the circuit. Feature visualizations are displayed over their corresponding vertex, rendered with respect to the circuit, \textit{not the original model} (unlike \cite{circuitszoomin}). This ensures the visualization is representative of the filtering operations displayed in the diagram. Additionally, our sparse circuit extraction allows for rendering of the \textit{entire} circuit graph, with kernels/edges all the way back to the first convolutional layer (also unlike \cite{circuitszoomin}). We visualize the first layer's features directly, by rendering the weights of each filter's 3 kernels as the visualization's 3 color channels.
Regarding Fig \ref{fig:1}, where feature \textit{conv3:56} had 12864 kernels preceding kernels in the original model, we've extracted a feature approximating circuit with only 210 kernels. Even at this high sparsity, Fig \ref{fig:1} is still a complex graph that's difficult to parse as a static image. To remedy this, our full circuit diagramming tool comes equipped with a point-click GUI that allows the user to isolate individual vertices in the graph, with their incoming and outgoing edges. (\textit{appendix}).
\par
\section{Conclusion \& Future Work}\label{sec:conclusion}
In this work, we repurpose 3 saliency-based pruning methods for the extraction of feature preserving \textit{circuits}. We compare the efficacy of these methods, finding they are similarly effective, and better than magnitude-based pruning. We then demonstrate how sparse circuits can be extracted that preserve features' responses to only a selection of images. These extracted circuits constitute sparse image-filtering algorithms, which can be analyzed with our circuit diagramming tool. We've limited the current work to analyses of Alexnet, as our circuit diagramming tool does not currently support architectures with branching or skip connections. In the future we will extend this work to other CNN models. Additionally, our current experiments in 'sub-filter' pruning are largely hypothesis-driven, in the future we would like to develop data-driven methods for identifying separable sub-filter circuits in a network.
\bibliographystyle{authordate1}
| {'timestamp': '2022-06-06T02:16:16', 'yymm': '2206', 'arxiv_id': '2206.01627', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01627'} | arxiv |
\section{Encoders as projectors}
A good \emph{learned representation} has many desiderata \citep{bengio2013representation}. The perhaps most elementary constraint placed over most learned representations is that a given observation $\vec{x}$ should have a \emph{unique} representation $\vec{z}$, at least in distribution. In practice this is ensured by letting the representation be given by the output of a function, $\vec{z} = g(\vec{x})$, often represented with a neural network. Having a unique representation for a given observation is important for downstream tasks, as otherwise the downstream loss function is complicated by having to be defined on sets \citep{zaheer2018deep}.
Uniqueness of representation is also important when a human investigator seeks information about the phenomenon underlying data, e.g.\@ through visualizations, as uniqueness is a ubiquitous assumption.
The \emph{autoencoder} \citep{rumelhart1986learning} is an example where uniqueness of representation is explicitly enforced, even if its basic construction does not suggest unique representations. In the most elementary form, the autoencoder consists of an \emph{encoder} $g_{\psi}: \R^D \rightarrow \R^d$ and a \emph{decoder}
$f_{\phi}: \R^d \rightarrow \R^D$, parametrized by $\psi$ and $\phi$, respectively.
These are trained by minimizing the \emph{reconstruction error} of the training
data $\{ \vec{x}_1, \ldots, \vec{x}_N \}$,
\begin{align}
\psi^*, \phi^* = \argmin_{\psi, \phi} \sum_{n=1}^N \| f(g(\vec{x}_n)) - \vec{x}_n \|^2.
\end{align}
Here $d$ is practically always smaller than $D$, such that the output of the encoder
is a low-dimensional latent representation of high-dimensional data. The data is assumed
to lie near a $d$-dimensional manifold $\M$ spanned by the decoder.
\begin{figure}
\centering
\includegraphics[width=0.4\textwidth]{figures/reach-roll.pdf}
\hspace{9mm}
\includegraphics[width=0.4\columnwidth]{figures/global_reach.pdf}
\vspace{-3mm}
\caption{\emph{Left:} The projection of a point (yellow) onto a nonlinear manifold can take
unique (green) or multiple values (red) depending on the reach of the manifold. When training data is inside the reach, the encoder can match the projection resulting in more trustworthy representations.
\emph{Right:} The global reach defines a region around the manifold $\M$ consisting of all points below a certain distance to $\M$. This captures both local manifold curvature as well as global shape.
}
\label{fig:encoding_vs_projecting}
\end{figure}
For a given decoder, we see that the optimal choice of encoder is the
projection onto $\M$, i.e.
\begin{align}
g_{\text{optimal}}(\vec{x}) &= \proj_{\M}(\vec{x}) = \argmin_{\vec{z}} \| \vec{x} - f(\vec{z}) \|^2.
\end{align}
For any \emph{nonlinear} choice of decoder $f$, this optimal encoder does \emph{not} exists everywhere. That is, multiple best choices of latent representation may exist for a given point, as the projection is not unique everywhere. As the learned encoder enforces a unique representation, it will choose arbitrarily among the potential representations.
In this case, any analysis of the latent representations can be misleading, as it does not contain the information that another choice of representation would be equally as good.
\textbf{In this paper} we investigate the \emph{reach} of the manifold $\M$ spanned
by the decoder $f$. This concept, predominantly studied in geometric measure theory, informs us
about regions of observation space where the projection onto $\M$ is unique,
such that trustworthy unique representations exist. If training data resides inside
this region we may have hope that a suitable encoder can be estimated, leading
to trustworthy representations. The classic \emph{reach} construction is global in nature,
so we develop a local generalization that gives a more fine-grained estimate of the
uniqueness of a specific representation. We provide a new local, numerical, estimator of
this reach, which allows us to determine which observations can be expected to have unique
representations, thereby allowing investigations of the latent space to disregard
observations with non-unique representations. Empirically we find that in large autoencoders, practically all data is outside the reach and risk not having a unique representation. To counter this, we design a reach-based regularizer that penalizes decoders for which unique representations of given data do not exist. Empirically, this significantly improves the guaranteed uniqueness of representations with only a small penalty in reconstruction error.
\section{Reach and uniqueness of representation}
Our starting question is \emph{which observations $\vec{x}$ have a unique representation $\vec{z}$ for a given decoder $f$?} To answer this, we first introduce the \emph{reach} \citep{federer:1959} of the manifold spanned by decoder $f$. This is a \emph{global} scalar that quantifies how much points can deviate from the manifold while having a unique projection. Secondly, we contribute a generalization of this classic geometric construct to characterize the local uniqueness properties of the learned representation.
\subsection{Defining reach}
The nearest point projection $\proj_{\M}$ is a well-defined function on all points for which there exists a unique nearest point. We denote this set
\begin{align*}
\Unp(\M) = \{\vec{x}\in \R^D : \vec{x}\text{ has a unique nearest point in }\M\},
\end{align*}
where $\M = f(\R^d)$ is the manifold spanned by mapping the entire latent space through the decoder. Observations that lie within $\Unp(\M)$ are certain to have a unique optimal representation, but there is no guarantee that the encoder will recover this. With the objective of characterizing the uniqueness of representation, the set $\Unp(\M)$ is a good starting point as here the encoder at least has a chance of finding a representation that is similar to that of a projection.
However, for an arbitrary manifold $\M$ it is generally not possible to explicitly find the set $\Unp(\M)$. Introduced by \citet{federer:1959}, the \emph{reach} of $\M$ provides us with an implicit way to understand which points are in and outside $\Unp(\M)$.
\begin{definition}\label{def:reach}
The \emph{global reach} of a manifold $\M$ is
\begin{align}
\reach(\M) = \inf_{\vec{x}\in \M} r_{\text{max}}(\vec{x}),
\end{align}
where
\begin{align}
r_{\text{max}}(\vec{x}) = \sup\{r> 0 : B_r(\vec{x})\subset \Unp(\M)\}.
\end{align}
Here $B_r$ denotes the open ball of radius $r$.
\end{definition}
Hence, $\reach(\M)$ is the greatest radius $r$ such that any open $r$-ball centered on the manifold lies in $\Unp(\M)$.
In the existing literature, the \emph{global reach} is referred to as the \emph{reach}; we emphasize the global nature of this quantity as we will later develop local counterparts.
Definition~\ref{def:reach} does not immediately lend itself to computation. Fortunately, \citet{federer:1959} provides a step in this direction, through the following result.
\begin{theorem}[\citet{federer:1959}]
Suppose $\M$ is a manifold, then
\begin{align}\label{eq:fed_reach_calc}
\reach(\M) = \inf_{\substack{ \vec{x}, \vec{y} \in \M\\ \vec{y}-\vec{x}\notin T_\vec{x}\M}} \frac{\norm{\vec{x}-\vec{y}}^2}{2\norm{P_{N_\vec{x}\M}(\vec{y}-\vec{x})}},
\end{align}
where $P_{N_\vec{x}\M}$ is the orthogonal projection onto the normal space of $\M$ at $\vec{x}$. If $\vec{y}-\vec{x}\in T_\vec{x}\M$ for all pairs $\vec{x},\vec{y}\in \M$ we let $\reach(\M) = \infty$, as $\M$ will be flat and the projection unique everywhere.
\end{theorem}
%
For our objective of understanding which observations have a unique representation, i.e.\@ are inside $\Unp(\M)$, the global reach provides some information. Specifically, the set
\begin{align}
\M_r = \left\{ \vec{x} | \inf_{\vec{y} \in \M} \norm{\vec{y} - \vec{x}} < \reach(\M) \right\}
\end{align}
is a subset of $\Unp(\M)$. This implies that observations $\vec{x}$ that are inside $\M_r$ will have a unique projection, such that we can expect the representation to be unique. The downside is that since $\reach(\M)$ is a global quantity, $\M_r$ is an overly restrictive small subset of $\Unp(\M)$.
%
Fig.~\ref{fig:encoding_vs_projecting}(right) illustrates this issue. Note how the global reach in the example is determined by the \emph{bottleneck}\footnote{Not to be confused with \emph{bottleneck network architectures} or the \emph{information bottleneck}.} of the manifold. Even if this bottleneck only influences the uniqueness of projections of a single point, it determines the global reach of the entire manifold. This implies that many points exist outside the reach which nonetheless has a unique projection.
\subsection{Pointwise normal reach}
\begin{wrapfigure}[7]{r}{0.25\textwidth}
\vspace{-13.5mm}
\includegraphics[width=0.25\textwidth]{figures/proof.pdf}
\vspace{-4mm}
\caption{Notation for the proof of theorem~\ref{thm:r_n_in_normal_dir}.}
\label{fig:proof}
\end{wrapfigure}
%
In order to get a more informative notion of reach, we now develop a local version, which we, for reasons that will be clear, call the \emph{pointwise normal reach}. For ease of notation denote
\begin{align}
R(\vec{x}, \vec{y}) = \frac{\norm{\vec{x}-\vec{y}}^2}{2\norm{P_{N_\vec{x}\M}(\vec{y}-\vec{x})}}
\end{align}
for $\vec{x},\vec{y}$ with $\vec{y}-\vec{x}\notin T_\vec{x}\M$, else we let $R(\vec{x},\vec{y}) = \infty$.
We then define the pointwise normal reach as the local infimum of eq.~\ref{eq:fed_reach_calc}.
\begin{definition}[Pointwise normal reach]\label{def:local_normal_reach}
At a point $\vec{x} \in \M$, the pointwise normal reach is
\begin{align}
r_N(\vec{x}) = \inf_{\vec{y} \in M} R(\vec{x},\vec{y}).
\end{align}
\end{definition}
In theorem~\ref{thm:r_n_in_normal_dir} below we prove that the local estimate $r_N(\vec{x})$ describes how far we can move along a normal vector at $\vec{x}$ and still stay within $\Unp(\M)$. This is useful as we know that $\vec{x}$ will lie in the normal space of $\M$ at $\proj_\M(\vec{x})$ (\citet{federer:1959} Thm. 4.8).
%
\begin{theorem}\label{thm:r_n_in_normal_dir}
For all $x\in \M$
\begin{align}
B_{r_N(\vec{x})}(\vec{x}) \cap N_{\vec{x}} \M \subset \Unp(\M),
\end{align}
where $N_{\vec{x}} \M$ denotes the normal space at $\vec{x}$.
\end{theorem}
\begin{proof}
Suppose for the sake of contradiction that there exists $\vec{w}\in \left(B_{r_N(\vec{x})}(\vec{x}) \cap N_{\vec{x}}\M\right)\cap \Unp(\M)^c$. That is, there exists $\vec{y}_1,\vec{y}_2 \in \M$ such that
\begin{align}
d(\vec{w}, \M) = \norm{\vec{y}_1-\vec{w}} = \norm{\vec{y}_2-\vec{w}},
\end{align}
where $d(\vec{w}, \M) = \inf_{\vec{x}\in \M} \norm{\vec{x}-\vec{w}}$.
In particular, we know there exists $\vec{y}\in \M$ such that
\begin{align}
\norm{\vec{y}-\vec{w}}\leq \norm{\vec{x}-\vec{w}} < r_N(\vec{x}).
\end{align}
Now, let $\theta_1$ denote the (acute) angle between $T_\vec{x}\M$ and $\vec{y}-\vec{x}$, and let $\theta_2$ denote the angle between $\vec{y}-\vec{x}$ and $\vec{w}-\vec{x}$. The sum of $\theta_1$ and $\theta_2$ is a right angle, see Fig.~\ref{fig:proof}. Let $t$ be the distance from $\vec{x}$ to $\vec{y}$. The altitude through the vertex $\vec{w}$ divides $\vec{y}-\vec{x}$ into two line segments. Denote the length of the segment from the foot of the altitude to $\vec{x}$, $t_1$, and the length of the segment from the foot to $\vec{y}$, $t_2$. Note, $t_2$ will always be less or equal to $t_1$, as $\norm{\vec{y}-\vec{w}}\leq \norm{\vec{x}-\vec{w}}$.
By the definition of cosine, $\cos \theta_2 = \frac{t_1}{\norm{\vec{w}-\vec{x}}} \geq \frac{t/2}{\norm{\vec{w}-\vec{x}}}$. At the same time $
\cos\theta_2 = \cos(\pi/2-\theta_1) = \sin \theta_1 = \frac{d}{t},
$
where $d = \norm{P_{\vec{w}-\vec{x}}(\vec{y}-\vec{x})}$, and as $\vec{w}-\vec{x}\in N_\vec{x}\M$, $d\leq \norm{P_{N_\vec{x}\M}(\vec{y}-\vec{x})}$.
Thus, we have $\frac{t/2}{\norm{\vec{w}-\vec{x}}} < \frac{d}{t}< \frac{\norm{P_{N_\vec{x}\M} (\vec{y}-\vec{x})}}{t}$, implying $R(\vec{x},\vec{y})\leq \norm{\vec{w}-\vec{x}}$, which contradicts $r_N(\vec{x}) \leq R(\vec{x},\vec{y})$.
\end{proof}
In lemma~\ref{thm:local_reach_bouds} below we show that the pointwise normal reach bounds the reach. For this, we need theorem~4.8(7) from \citet{federer:1959}
\begin{lemma}[\citet{federer:1959}]
Let $\vec{x},\vec{y}$ be points on $\M$ with $r_{\text{max}}(\vec{x}) > 0$, and let $\vec{n}$ be a normal vector in $N_{\vec{x}}\M$, then
\begin{align}
\inner{\vec{n}}{\vec{y}-\vec{x}} \leq \frac{\norm{\vec{y}-\vec{x}}^2\norm{\vec{n}}}{2r_{\text{max}}(\vec{x})}
\end{align}
\end{lemma}
\begin{lemma}\label{thm:local_reach_bouds}
For all $\vec{x} \in \M$ we have that
\begin{align}
\inf_{\vec{y}\in B_{2r_N(\vec{x})}(\vec{x})\cap \M} r_N(\vec{y}) \leq r_{\text{max}}(\vec{x}) \leq r_N(\vec{x}).
\end{align}
\end{lemma}
%
\begin{proof}\phantom{\qedhere}
Applying the result from Federer to the vector $\vec{n} = \frac{P_{N_\vec{x}\M}(\vec{y}-\vec{x})}{\norm{P_{N_\vec{x}\M}(\vec{y}-\vec{x})}}$ gives
\begin{align}
r_{\text{max}}(\vec{x})\leq \frac{\norm{\vec{x}-\vec{y}}^2\norm{\vec{n}}}{2\norm{\vec{n}}\norm{\vec{x}-\vec{y}}\cos\theta},
\end{align}
where $\theta$ is the angle between $\vec{x}-\vec{y}$ and $\vec{n}$. Hence, $\cos\theta = \frac{\norm{P_{N_\vec{x}\M}(\vec{y}-\vec{x})}}{\norm{\vec{y}-\vec{x}}}$. Thus, for all $\vec{y}\in \M$
\begin{align}
r_{\text{max}}(\vec{x}) \leq \frac{\norm{\vec{x}-\vec{y}}^2}{2\norm{P_{N_\vec{x}\M}(\vec{y}-\vec{x})}},
\end{align}
proving the right inequality.
%
Consider $B = B_{r_N(\vec{x})}(\vec{x})$. Suppose there exists $\vec{w} \in B$ with $\vec{w} \notin \Unp(\M)$. Then $\vec{w} \notin N_\vec{x}\M$. Hence there exists $\vec{y}_1,\vec{y}_2\in \M$ such that
$
d(\vec{w}, \M) = \norm{\vec{y}_1 - \vec{w}} = \norm{\vec{y}_2 - \vec{w}} < r_N(\vec{x}).
$
From \citet{federer:1959} theorem 4.8 we know that $\vec{w}\in N_{\vec{y}_1}\M, N_{\vec{y}_2}\M$. Combining this with lemma \ref{thm:r_n_in_normal_dir} gives that $r_N(\vec{y}_1),r_N(\vec{y}_2) \leq d(\vec{w},\M)$ and that $d(\vec{x},\M)< \norm{\vec{w}-\vec{x}}$. We also have that $\norm{\vec{y}_1-\vec{x}},\norm{\vec{y}_2-\vec{x}}\leq 2 r_N(\vec{x})$.
Combining these inequalities gives us that the distance from $\vec{x}$ to any point not in $\Unp(\M)$ is greater than $\inf_{\vec{y}\in B_{2r_N(\vec{x})}(\vec{x}) \cap \M} r_N(\vec{y})$, which implies that
\begin{equation}
\inf_{\vec{y} \in B_{2r_N(\vec{x})}(\vec{x}) \cap \M}r_N(\vec{y}) \leq r_{\text{max}}(\vec{x}).
\tag*{\qed}
\end{equation}
\end{proof}
We presented the theoretical analysis under the assumption that $\M = f(\R^d)$ is a manifold. Although the theoretical results can be extended to arbitrary subsets of Euclidean space, the experimental setup requires the Jacobian to span the entire tangent space. This might not be the case if $\M$ has self-intersections. The theory can be extended to handle such self-intersections, but this significantly complicates the algorithmic development. See the appendix for a discussion.
\subsection{Estimating the pointwise normal reach}
The definition of $r_N$, prompts us to minimize $R(\vec{x},\vec{y})$ over all of $\M$, which is generally infeasible and approximations are in order. As a first step towards an estimator, assume that we are given a finite sample $\mat{S}$ of points on the manifold. We can then replace the infimum in definition~\ref{def:local_normal_reach} with a minimization over the samples. Using that the projection matrix onto $N_{\vec{x}}\M$ is given by $P_{N_\vec{x}\M} = \mat{I} - \mat{J}(\mat{J}\T \mat{J})\ensuremath{^{-1}} \mat{J}\T$, we get the following estimator
\begin{align}
\hat r_N(\vec{x}) = \min_{\vec{y}\in \mat{S}} \frac{\norm{\vec{y}-\vec{x}}^2}{2\norm{(\mat{I}-\mat{J}(\mat{J}\T\mat{J})\ensuremath{^{-1}} \mat{J}\T)(\vec{y}-\vec{x})}},
\label{eq:reach_est}
\end{align}
where $\mat{J} \in \mathbb{R}^{D \times d}$ is the Jacobian matrix of $f$ at $\vec{x}$. Note that since we replace the infimum with a minimization over a finite set, we have that $\hat r_N(\vec{x}) \geq r_N(\vec{x})$.
There are different choices of sampling sets $\mat{S}$. Given a trained autoencoder, a cheap way to obtain samples is to use the reconstructed training data as the sampling set. This will generally be sufficient if the training data is dense on the manifold, but this is rarely the case in high data dimensions.
%
The following lemma provides us a way to restrict the area over which we must minimize.
%
\begin{lemma}
For any $\vec{x}, \vec{y} \in \M$
\begin{align}
R(\vec{x},\vec{y}) \geq \frac{1}{2} \norm{\vec{x}-\vec{y}}.
\end{align}
\end{lemma}
\begin{proof}
Recall that $\vec{y}-\vec{x} = P_{N_\vec{x}\M}(\vec{y}-\vec{x}) + P_{T_\vec{x}\M}(\vec{y}-\vec{x})$, as $\R^D = T_\vec{x}\M \oplus N_\vec{x}\M$. Hence $\norm{\vec{y}-\vec{x}} \geq \norm{P_{N_\vec{x}\M}(\vec{y}-\vec{x})}$. The statement, thus, follows from the definition of $R$.
\end{proof}
\begin{wrapfigure}[10]{r}{0.55\textwidth}
\begin{minipage}{0.55\textwidth}
\vspace{-8mm}
\begin{algorithm}[H]
\caption{Sampling-based reach estimator}\label{alg:sample}
\begin{algorithmic}
\STATE radius $\gets r_0$
\STATE reach $\gets \infty$
\FOR{$i \gets 1, \ldots, $ num\_batches}
\STATE samples $\gets$ \texttt{sample\_ball}($\vec{x}, \text{radius}, \text{batch\_size}$)
\STATE projected $\gets$ \texttt{decode}(\texttt{encode}(samples))
\STATE reach $\gets \min\left(\text{reach}, \texttt{reach\_est}(\vec{x}, \text{projected})\right)$
\STATE radius $\gets 2 \cdot$ reach
\ENDFOR
\end{algorithmic}
\end{algorithm}
\end{minipage}
\end{wrapfigure}
%
The lemma points towards a simple computational procedure for numerically estimating the pointwise normal reach, which is explicated in algorithm~\ref{alg:sample}. Here $\texttt{reach\_est}$ refers to the application of eq.~\ref{eq:reach_est}.
The algorithm samples uniformly inside a ball centered on $\vec{x}$ and repeatedly shrinks the radius of the ball as tighter estimates of the reach are recovered. We further use the autoencoding reconstruction as an approximation to the projection of $\vec{x}$ onto $\M$.
\subsection{Is a point within reach?}
Suppose that a point $\vec{x} \in \R^D$ is represented by a point on the manifold $f(\vec{z})$. From definition~\ref{def:reach} we know that $\vec{x}$ has a unique nearest point on the manifold if
\begin{align}\label{eq:r_max_boud}
\norm{\vec{x}-f(\vec{z})} < r_{\text{max}}(f(\vec{z})).
\end{align}
A point $\vec{x}$ which does not satisfy this inequality risks not having a unique nearest point, and hence no unique representation. From lemma~\ref{thm:local_reach_bouds} we know that $r_{\text{max}}(f(\vec{z})) \leq r_N(f(\vec{z}))$. So $\vec{x}$ risks not having a unique nearest point if
\begin{align}
\norm{\vec{x}-f(\vec{z})} \geq r_N(f(\vec{z})) \geq r_{\text{max}}(f(\vec{z})).
\end{align}
We note that to show that $\norm{\vec{x}-f(\vec{z})} \geq r_N(f(\vec{z}))$, it is enough to compute
\begin{align}
\hat r_N(f(\vec{z})) = \inf_{\substack{\vec{y}\in \M\cap B_{2\norm{\vec{x}-f(\vec{z})}}(f(\vec{z})) \\ \vec{y} \neq f(\vec{z})}} R(f(\vec{z}), \vec{y}),
\end{align}
i.e.\@ limit the search to a ball of radius $2\norm{\vec{x}-f(\vec{z})}$. Thus, when we only need to determine if a point is inside the pointwise normal reach, we can pick $r_0 = 2\norm{\vec{x}-f(\vec{z})}$ in Algorithm~\ref{alg:sample}.
Notice that given any set of points on the manifold, the resulting estimation of $r_N$ will always be larger than the true value. It means that any point which lies outside the estimated normal reach, will in fact lie outside the true normal reach. However, a point which lies inside the estimated normal reach, risks lying outside the true normal reach, and thus not having a unique projection.
\subsection{Regularizing for reach}
The autoencoder minimizes an $l_2$ error which is directly comparable to the pointwise normal reach. This suggests a regularizer that penalizes if the $l_2$ error is larger than the pointwise normal reach. In practice, we propose to use
\begin{align}
\mathcal{R}(\vec{x}) &= \texttt{Softplus}\left( \norm{f\left(g(\vec{x})\right) - \vec{x}} - \hat r_N\left( f\left(g(\vec{x})\right)\right) \right).
\end{align}
The reach-regularized autoencoder then minimizes
\begin{align}
\mathcal{L} &= \sum_{n=1}^N \| f(g(\vec{x}_n)) - \vec{x}_n \|^2 + \lambda \sum_{n=1}^N \mathcal{R}(\vec{x}_n),
\end{align}
where we in practice use $\lambda=1$. We also experimented with a \texttt{ReLU} activation instead of \texttt{Softplus}, but found the latter to yield more stable training. When estimating the pointwise normal reach, $\hat r_N$, we apply Algorithm~\ref{alg:sample} with an initial radius of $r_0 = 2 \| f(g(\vec{x}_n)) - \vec{x}_n \|$.
\section{Experiments}
Having established a theory and algorithm for determining when a representation can be expected to be unique, we next investigate its use empirically. We first compute the pointwise local reach across a selection of models to see if it provides useful information. We then carry on to investigate the use of reach regularization. \footnote{The code is available at \url{https://github.com/HeleneHauschultz/is_an_encoder_within_reach}.}
\begin{SCfigure}
\includegraphics[width=0.7\columnwidth]{figures/reach_reg.pdf}
\caption{\emph{Left:} An autoencoder trained on noisy points scattered along a circular arc. \emph{Right:} The manifold spanned by the decoder of an autoencoder trained with reach regularization. In both panels, the gray circles illustrates the estimated pointwise normal reach at points along the autoencoder curve.}
\label{fig:no_reg_reach}
\end{SCfigure}
\subsection{Analysing reach}
\subsubsection{Toy circle}\label{subsec:circle}
We start our investigations with a simple toy example to get an intuitive understanding. We generate observations along a circular arc with added Gaussian noise of varying magnitude. Specifically, we generate approximately $400$ points as $z \mapsto t\left(\sin(z), -\cos(z)\right) + 1.5\cos(z)\epsilon$, where $\epsilon \sim \mathcal{N}(0,1)$. On this, we train an autoencoder with a one-dimensional latent space. The encoder and decoder both consist of linear layers, with three hidden layers with $128$ nodes and with ELU non-linearities.
Figure~\ref{fig:no_reg_reach}(left) shows the data alongside the estimated manifold and its pointwise normal reach.
We observe that the manifold spanned by the decoder has areas with small reach, where the manifold curves to fit the noisy data. The pointwise normal reach seems to well-reflect the curvature of the estimated manifold. The plot illustrates how some of the points end up further away from the manifold than the reach. For some of the points, this is not a problem, as they still have a unique projection onto the manifold. However, some of the points are equally close to different points on the manifold, such that their representation cannot be trusted.
\begin{figure}[t]
\centering
\includegraphics[width=\columnwidth]{figures/celeba/celeba-val-recon2.png}
\vspace{-6mm}
\caption{CelebA validation set reconstructions.}
\label{fig:celeba-val-recon}
\end{figure}
\subsubsection{CelebA}
To investigate the reach on a non-toy dataset, we train a deep autoencoder on the CelebA face dataset \citep{celeba}. The dataset consists of approximately $200\,000$ images of celebrity faces.
We train a symmetric encoder-decoder pair that maps the $64 \times 64 \times 3$ images to a $128$ dimensional latent space, and back. The encoder consists of a single 2d convolution operation without stride followed by six convolution operations with stride 2, resulting in a $1 \times 1 \times C$ image. We use $C=128$ channels for all convolutional operations, a filter size of 5 and Exponential Linear Unit (ELU) non-linearities. The decoder is symmetric, using transpose convolutions with stride 2 to upsample and ending with a convolution operation mapping to $64 \times 64 \times 3$. The model is trained for 1M gradient updates on the mean square error loss, with a batch size of 128, using the Adam optimizer with a learning rate of $10^{-4}$.
Example reconstructions on the validation set are provided in Fig.~\ref{fig:celeba-val-recon}.
After training we estimate the reach of the validation set using the sampling based approach (Alg.~\ref{alg:sample}). Fig.~\ref{fig:plots}(left) plots the reconstruction error $\norm{\vec{x} - f(\vec{z})}$ versus the pointwise normal reach. We observe that almost all observations lie outside the pointwise normal reach, implying that we cannot guarantee a unique representation. This is a warning sign that our representations need not be trustworthy.
\begin{figure}
\includegraphics[width=\columnwidth]{figures/celeba/plots.pdf}
\vspace{-4mm}
\caption{
\emph{Left:} Estimated reach for CelebA validation samples plotted against the L2 error. Samples below the diagonal red line does not have a unique encoder.
\emph{Center:} Normalized reach as a function of batches used to estimate the reach.
The normalized reach is the estimated pointwise normal reach divided by the estimated pointwise normal reach after the first batch.
The hyperball sampling reach estimator quickly converges.
\emph{Right:} Sensitivity analysis of the hyperball sampling reach estimator to the initial hyperball radius. The reach of CelebA validation samples are estimated with initial radii $r_0=1.0$ and $r_0=0.01$ respectively and their final reach after 100 batches are plotted against each other.
}
\label{fig:plots}
\end{figure}
Next we analyze the empirical convergence properties of our estimator on the CelebA autoencoder. Fig.~\ref{fig:plots}(center) shows the average pointwise normal reach over the validation set as a function of the number of iterations in the sampling based estimator. We observe that the estimator converges after just a few iterations, suggesting that the estimator is practical.
The estimator relies on an initial radius for its search. Fig.~\ref{fig:plots}(right) shows the estimated pointwise normal reach on the validation set, plotted for two different initial radii. We observe that the estimator converges to approximately the same value in both cases, suggesting that the method is not sensitive to this initial radius. However, initializing with a tight radius will allow for faster convergence.
\subsection{Reach regularization}
Having established that the pointwise normal reach provides a meaningful measure of uniqueness, we carry on to regularize accordingly.
\subsubsection{Toy circle}
Returning to the example from section~\ref{subsec:circle}, we train an autoencoder of the same architecture with the reach regularization. We pretrain the network $100$ epochs without regularization, and then $2000$ iterations with reach regularization. \looseness=-1
Fig.~\ref{fig:no_reg_reach}(right) shows that reach regularization gives a significantly smoother manifold than without regularization (left panel). The gray circles on the plot indicate that almost all the points are now within the pointwise normal reach, and arguably the associated representations are now more trustworthy.\looseness=-1
\subsubsection{MNIST}
Next we train an autoencoder on 5000 randomly chosen images from the classes 2, 4 and 8 from MNIST \citep{lecun1998gradient}. We use a symmetric architecture reducing to two dimensional representation through a sequence of $784\rightarrow500\rightarrow250\rightarrow150\rightarrow100\rightarrow50\rightarrow2$ linear layers with ELU non-linearities. We pretrain 5000 epochs without any regularization, and proceed with reach regularization enabled. Fig.~\ref{fig:mnist_reg}(left) shows the percentage of points which lies within reach of the estimated manifold. We observe that reach regularization slightly increases the reconstruction error, as any regularization would, while significantly increasing the percentage of points that are known to have a unique representation. This suggests that reach regularization only minimally changes reconstructions while giving a significantly more smooth model, which is more reliable.
Figure~\ref{fig:mnist_reg}(center) shows the latent representations given by the pretrained autoencoder without regularization, while Fig~\ref{fig:mnist_reg}(right) shows the latent representations after an additional 200 epochs with reach regularization. The latent representations with corresponding data points outside reach, that is, where the reconstruction error is greater than the pointwise normal reach at the reconstructed point is plotted in red. The points inside reach are plotted in green. We observe that after regularization, significantly more points can be expected to be unique and thereby trustworthy. Note that the latent configuration is only changed slightly after reach regularization, which suggests that the expressive power of the model is largely unaffected by the reach regularization.
\begin{figure}
\includegraphics[width=\textwidth]{figures/mnist_latent.pdf}
\vspace{-4mm}
\caption{The effect of reach regularization on an MNIST model.
\emph{Left:} The plot shows that the percentage of points within reach increases, while the $l_2$-loss is nearly unchanged.
We plot the loss curve from the initial 5000 epochs without regularization, to show how the $l_2$-loss behaves when regularizing.
\emph{Center \& right:} Latent representations of the MNIST autoencoder before and after the reach regularization. The red numbers are outside the reach, while green are within. Reach regularization smoothens the decoder to increase reach with minimal changes to both reconstructions and latent configuration.
}
\label{fig:mnist_reg}
\end{figure}
\section{Related work}
Representation learning is a foundational aspect of current machine learning, and the discussion paper by \citet{bengio2013representation} is an excellent starting point. As is common, \citet{bengio2013representation} defines a representation as the output of a function applied to an observation, implying that a representation is unique. In the specific context of autoencoders, we question this implicit assumption of uniqueness as many equally good representations may exist for a given observation. While only studied here for autoencoders, the issue applies more generally when representations span submanifolds of the observation space.
In principle, probabilistic models may place multimodal distributions over the representation of an observation in order to reflect lack of uniqueness. In practice, this rarely happens. For example, the highly influential \emph{variational autoencoder} \citep{kingma:iclr:2014, rezende:icml:2014} amortizes the estimation of $p(\vec{z}|\vec{x})$ such that it is parametrized by the output of a function. Alternatives relying on Monte Carlo estimates of $p(\vec{z}|\vec{x})$ do allow for capturing non-uniqueness \citep{pmlr-v70-hoffman17a}, but this is rarely done in practical implementations. That Monte Carlo estimates provide state-of-the-art performance is perhaps indicative that coping with non-unique representations is important. Our approach, instead, aim to determine which observations can be expected to have a unique representation, which is arguably simpler than actually finding the multiple representations.
Our approach relies on the reach of the manifold spanned by the decoder. This quantity is traditionally studied in geometric measure theory as the reach is informative of many properties of a given manifold. For example, manifolds which satisfy that $\reach(\M)> 0$ are $C^{1,1}$, i.e.\@ the transition functions are differentiable with Lipschitz continuous derivatives. In machine learning, the reach is, however, a rarely used concept. \citet{Fefferman2016} investigates if a manifold of a given reach can be fitted to observed data, and develops the associated statistical test. Further notable exceptions are the multichart autoencoder by \citet{schonsheck2020chart}, and the adaptive clustering of \citet{besold2020adaptive}. Both works rely on the reach as a tool of derivation. Similarly, \citet{chae2021likelihood} relies on the assumption of positive reach when deriving properties of deep generative models. These works all rely on the global reach, while we have introduced a local generalization.
The work closest to ours appears to be that of \citet{aamari2019estimating} which studies the convergence of an estimator of the global reach \eqref{eq:fed_reach_calc}. This only provides limited insights into the uniqueness of a representation as the global reach only carries limited information about the local properties of the studied manifold. We therefore introduced the pointwise normal reach alongside an estimator thereof. This gives more precise information about which observations can be expected to have a unique representation.
\vspace{-3mm}
\section{Discussion}
\vspace{-2mm}
The overarching question driving this paper is \emph{when can representations be expected to be unique?}
Though commonly assumed, there is little mathematical reason to believe that the choice of optimal representation is generally unique. The theoretical implications of this is that enforcing uniqueness on non-unique representations leads to untrustworthy representations.
We provide a partial answer for the question in the context of autoencoders, through the introduction of the \emph{pointwise normal reach}. This provides an upper bound for a radius centered around each point on the manifold spanned by the decoder, such that any observation within the ball has a unique representation. This bound can be directly compared to the reconstruction error of the autoencoding to determine if a given observation might not have a unique representation. This is a step towards a systematic quantification of the reliability and trustworthiness of learned representations.
Empirically, we generally find that most trained models do not ensure that representations are unique. For example, on CelebA we found that almost no observations were within reach, suggesting that uniqueness was not ensured. This is indicative that the problem of uniqueness is not purely an academic question, but one of practical importance.
We provide a Monte Carlo estimator of the pointwise normal reach, which is guaranteed to upper bound the true pointwise normal reach. The estimator is easy to implement, with the main difficulty being the need to access the Jacobian of the decoder. This is readily accessible using forward-mode automatic differentiation, but it can be memory-demanding for large models.
It is easy to see that the sample-based pointwise normal reach estimator converges to the correct value in the limit of infinitely many samples. We, however, have no results on the rate of convergence. In practice we observe that the estimator converges in a few iterations for most models, suggesting the convergence is relatively fast. In practice, the estimator, however, remains computationally expensive.
While we can estimate the pointwise normal reach quite reliably even for large models within manageable time, the estimator is currently too expensive to use for regularization of large models. On small models, we observe significant improvements in the uniqueness properties of the representations at minimal cost in terms of reconstruction error. This is a promising result and indicative that it may be well-worth using this form of regularization. While more work is needed to speed up the estimating of pointwise normal reach, our work does pave a path to follow.
\begin{ack}
This work was supported by research grants (15334, 42062) from VILLUM FONDEN. This project has also received funding from the European Research Council (ERC) under the European Union's Horizon 2020 research and innovation programme (grant agreement 757360). This work was funded in part by the Novo Nordisk Foundation through the Center for Basic Machine Learning Research in Life Science (NNF20OC0062606). Helene Hauschultz is partly financed by Aarhus University Centre for Digitalisation, Big Data and Data Analytics (DIGIT)
\end{ack}
\small
| {'timestamp': '2022-06-06T02:13:41', 'yymm': '2206', 'arxiv_id': '2206.01552', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01552'} | arxiv |
\section{Introduction}
We describe a real-world application that identifies semantically similar questions in English language business telephone calls between a customer and a sales or support agent. Identifying questions with similar meanings but different formulations provides insight into customer conversations that can be used for business analytics or for training agents on how to respond better to customer needs.
Pre-trained contextualized embeddings such as those that can be extracted from BERT \citep{devlin-etal-2019-bert} and GPT-2 \citep{radford2019language} have become essential building blocks for natural language processing (NLP) solutions. Embeddings extracted from these models can be used directly in unsupervised NLP applications, such as clustering and similarity comparison. Starting with pre-trained models reduces the need for expensive training and is particularly important in real-world settings, where high-quality data annotation is a major challenge.
At our company we offer transcription of calls via automatic speech recognition and natural language understanding services for business conversations that enable product features such as sentiment analysis, identification of action items, and note-taking.
Questions play a key role in natural conversation. It would be of great value to users if we could group questions asked in the calls that are semantically similar, giving our clients deeper insight in what types of questions their customers are asking. It is worth noting here that questions that arise naturally in the course of human-to-human conversation are quite different from the reading comprehension questions in public question answering datasets such as Stanford Question Answering Dataset (SQuAD) \citep{rajpurkar-etal-2016-squad}, making this problem all the more challenging. We provide a detailed comparison in section 4.1.
In this work, we demonstrate that the representations of question sentences only occupy a narrow cone in the output embedding space, a property known as \textit{anisotropy} \citep{ethayarajh-2019-contextual}. This property makes it difficult to directly use the embeddings as input to semantic comparison functions. Then, we show how Sentence-BERT \citep{reimers-gurevych-2019-sentence}, a fine-tuned model based on BERT can overcome this problem and improve the performance in our applied task. Additionally, we propose an exemplar-based semantic matching approach to efficiently find sentences that are semantically similar to a specific topic.
\begin{table*}[t]
\centering
\begin{tabular}{| p{2cm} | p{3cm}| p{3cm} | p{3cm}| p{3cm}|}
\textbf{Topic} &
\textbf{Exemplar 1} &
\textbf{Exemplar 2} &
\textbf{Exemplar 3} &
\textbf{Exemplar 4} \\
\hline
Pricing &
How much is it monthly? &
What’s the lowest price? &
What is this like in terms of pricing? &
How much do you charge?\\
\hline
Contact Information &
Can I get your name? &
Can you give me your email address? &
What is your last name? &
Would you mind giving me the phone number? \\
\end{tabular}
\caption{Selected exemplar questions for topics “Pricing” and “Contact Information”}
\label{table1}
\end{table*}
\section{Background}
\subsection{Pre-trained Contextualized Embeddings}
There have been various pre-trained contextualized models based on deep neural networks in recent years. They include:
\begin{itemize}
\item BERT \citep{devlin-etal-2019-bert}: one of the most popular large pre-trained models. Pooling over the last hidden state of BERT can be used as the sentence representation in many applications. Additionally, BERT prepends a \textit{CLS} token (short for ``classification'') to the start of each input sentence, which is trained by the Next Sentence Prediction task to represent sentence-level classification.
\item GPT-2 \citep{radford2019language}: A large pre-trained language model that shows superior results in many NLP tasks. We use the pooling of the last hidden state as the representation of the sentence.
\item Sentence-BERT (SBERT) \citep{reimers-gurevych-2019-sentence}: A modification of pre-trained BERT that is fine-tuned on Natural Language Inference (NLI) \citep{bowman-etal-2015-large} and Semantic Textual Similarity (STS) \citep{cer-etal-2017-semeval} datasets. SBERT achieves better performance than BERT in semantic textual similarity benchmarks.
\end{itemize}
\subsection{Industry Applications}
At our company, we provide VoIP (Voice over Internet Protocol) telephony for businesses, with products for sales and support call centres. Calls are optionally recorded and transcribed using an in-house Automatic Speech Recognition (ASR) system. In addition to transcription, we offer NLP analysis of our in-house transcripts, e.g., identifying and extracting questions asked by customers in calls.
We group extracted questions into semantically related sets. Questions within a set may vary in their syntactic structure but have similar or equivalent meaning. For instance, people can ask questions in various forms when inquiring about pricing, such as “What does it cost?”, “How much is it?” or “What’s the price of that?”
Grouping related questions can help managers better coach their agents and prepare answers for commonly asked questions. Since hand-labelling our call transcripts would be expensive and time-consuming, we leveraged the rich semantic and syntactic information encoded in contextualized embeddings to build a semantic matching pipeline that requires no supervision or data labelling.
\section{Methods}
\subsection{Sentence Representation}
We experiment with several contextualized embedding models, using these models to construct sentence representations for our question dataset. For each model, we also test different methods for extracting embeddings as the sentence representations. The models and representations in our experiments include:
\begin{itemize}
\item BERT base: we compare using the \textit{CLS} token versus average pooling of the last hidden layer, with an embedding size of 768, noted as “BERT-base-cls” and “BERT-base-mean'' respectively.
\item GPT-2: average pooling of last hidden state with a size of 768, referred to as “GPT2-mean”.
\item SBERT base fine-tuned on the NLI and STS datasets: we compare using the \textit{CLS} token and average pooling of the last hidden layer with an embedding size of 768. These are referred to as “SBERT-base-cls” and “SBERT-base-mean'' respectively.
\end{itemize}
\begin{table*}[t]
\centering
\begin{tabular}{| c| c| c | c|}
&
\textbf{Average question length} &
\textbf{Median question length} &
\textbf{Percentage of stop words} \\
Our data&
8.12 &
7 &
64.4\% \\
SQuAD&
10.20 &
10 &
46.0\% \\
\end{tabular}
\caption{Comparison between questions in our data and SQuAD, each with 10,000 samples}
\label{table2}
\end{table*}
\subsection{Exemplar-based Semantic Matching}
We propose an efficient semantic matching formula that leverages the power of sentence representations from pre-trained models, and uses them directly to find semantically similar sentences for predefined semantic catgeories.
Based on discussions with customers, we identified frequently occurring topics that provide business insight. For each predefined question topic, we manually identify a few exemplar sentences exhibiting a variety of lexical and syntactic formulations to use as the references for the semantic matching. Table 1 gives selected exemplars for two business topics, “Pricing” and “Contact Information”.
We compare two formulae for measuring semantic similarity given the sentence embeddings. The first formula is an unweighted similarity score of any query against the topic defined as:
\begin{equation}
\label{eq:1}
score = \frac{\sum_{i=1}^{N} \cos (q, s_i)}{N}
\end{equation}
\(N\) is the number of exemplar sentences, \(q\) denotes the embedding representation of the query sentence, while \(s_i\) is the embedding representation of the \(i^{th}\) exemplar sentence. Cosine similarity is used as the measurement of similarity as it is the most commonly used directional metric in vector space. We pair the query sentence with each exemplar question and compute the cosine similarity score, then average over the number of exemplars.
We compare the unweighted score to a weighted similarity score defined as:
\begin{equation}
\label{eq:2}
score = \frac{\sum_{i=1}^{N} p_i}{N}
\end{equation}
where if \(\cos (q, s_i) < threshold\):
\[
p_i=\cos (q, s_i)
\]
else:
\[
p_i=w\cdot N
\]
When measuring a match between a given new question with exemplars, the unweighted score treats all exemplar questions equally, whereas the weighted score emphasizes matches to specific exemplars.
The \(threshold\) is a manually chosen parameter based on the \(90^{th}\) percentile of the cosine similarity score distribution over all pairs in our semantic matching candidate pool. The parameter \(w\) is a manually selected constant (typically in the range \( w \epsilon [3, 5]\) in our application) that biases towards highly similar pairs.
\begin{figure*}[t]
\centering
\includegraphics[width=0.63\textwidth]{figure1.png}
\caption{The cosine similarity score distribution of sentence embedding vectors from different models. }
\label{fig1}
\end{figure*}
\begin{figure*}[t]
\centering
\includegraphics[width=0.3\textwidth]{figure2-1.png}\quad
\includegraphics[width=0.3\textwidth]{figure2-2.png}\quad
\includegraphics[width=0.3\textwidth]{figure2-3.png}
\medskip
\includegraphics[width=0.3\textwidth]{figure2-4.png}\quad
\includegraphics[width=0.3\textwidth]{figure2-5.png}
\caption{Pairwise cosine similarity heatmap for four question sentences, where \(t1\): "How much does it cost?", \(t2\): "What is the price for subscription?", \(t3\): "What's the name of the company?", \(t4\): "What's the total height of the vehicle?"}
\label{fig2}
\end{figure*}
\section{Experiment}
\subsection{Dataset}
Our data are customer support and sales call transcripts. A customer support call is typically an interaction in which a customer calls into a support centre with a problem or question relating to a particular product or service offered by the company, and then a customer service representative of the company tries to understand and solve the problem to the customer's satisfaction. A sales call is typically an interaction in which a sales representative calls a client or potential client to discuss a potential sale of a product, or subscription to a product, either to negotiate pricing or to discuss the client’s product-specific needs (or some combination of both).
From these transcripts we automatically identified and extracted customer-side questions. Note that these questions are part of a real, human conversation, and thus are mostly short in length, and use context-dependent devices such as pronouns. For instance, under the topic of “Pricing”, typical questions include examples like “How much does it cost?” or “What’s the price for monthly subscription?” In addition, as our transcripts are produced by our ASR engine directly from speech, some sentences may contain transcription errors.
The questions that occur naturally in human conversation are very different from the questions found in public NLP data sets such as SQuAD. The SQuAD questions test reading comprehension. The questions can be interpreted without prior discourse context.
Table 2 shows a comparison between SQuAD and our naturally occurring questions found in our data. The SQuAD questions are longer compared to our data. However, the percentage of stop words in our data indicates that questions asked in human conversations tend to use more stop words than those in SQuAD.
\begin{table*}
\centering
\begin{tabular}{| c| c| c | c|}
&
Prec@50 &
Prec@100 &
Prec@200 \\
BERT-base-cls &
0.16 &
0.09 &
0.05 \\
BERT-base-mean &
0.74 &
0.55 &
0.37 \\
GPT2-mean &
0.04 &
0.04 &
0.03 \\
SBERT-base-cls &
0.92 &
0.88 &
0.79 \\
SBERT-base-mean &
0.98 &
0.90 &
0.78 \\
\end{tabular}
\caption{Semantic matching precision with unweighted score at three cutoff points: 50, 100 and 200.
}
\label{table3}
\end{table*}
\begin{table*}[t]
\centering
\begin{tabular}{| p{3.5cm}| c| c | c| c| c|}
&
Prec@50 &
Prec@100 &
Prec@150 &
Prec@200 &
HR@Prec=0.9 \\
SBERT-base-mean with unweighted score &
0.98 &
0.90 &
0.86 &
0.78 &
0.0100 \\
SBERT-base-mean with weighted score &
0.98 &
0.93 &
0.87 &
0.79 &
0.0123 \\
\end{tabular}
\caption{Comparison of weighted and unweighted similarity score with SBERT-base-mean. Weighted score slightly outperforms unweighted ones at cutoff points.}
\label{table4}
\end{table*}
\subsection{Similarity Score Distribution}
To better understand the distribution of sentence embeddings produced by each contextualized model and how they perform when directly used in similarity evaluation, we conducted the following experiments to test the similarity score distribution for each model: we sampled 1,000 question sentences from our dataset, and calculated the cosine similarity for all pairs of embeddings.
Figure 1 shows the calculated pairwise question cosine similarity distributions for different contextualized models. The similarity scores from BERT and GPT-2 follow a narrow distribution, i.e. any two questions have high cosine similarity, whether they are semantically related or not. Use of the BERT \textit{CLS} token or average pooling of the last hidden layer as the sentence representations does not greatly affect the pairwise similarity spread. In contrast, the SBERT scores exhibit a much wider distribution. Recall that SBERT was fine-tuned on natural language inference tasks, which is clearly beneficial for the task of determining the semantic similarity of questions.
\citep{ethayarajh-2019-contextual} refers to the phenomenon of very strong cosine similarity between vector representations as \textit{anisotropy}. The author shows that anisotropy is found in word-level representations across all layers in many contextualized models including BERT and GPT-2. Our experiment further shows that it also applies to sentence-level representations in BERT and GPT-2. Anisotropy can be problematic when using embeddings directly for sentence similarity comparison tasks, as all sentences are similar in some senses. As shown in Figure 2, we tested the pairwise cosine similarity of four different question sentences. Only \(t1\) and \(t2\) should have relatively high score as they are semantically close, but BERT and GPT-2 produced similar high scores for all pairs that cannot be distinguished easily. While SBERT successfully differentiated pairs according to their semantic relevance.
\subsection{Evaluation}
\subsubsection{Selecting Exemplars}
In this experiment, we seeded a question topic “Pricing” for the semantic matching. Following the procedures described in section 3.2, we selected ten questions related to “Pricing” as our exemplars. As a practical matter, ten exemplars is a reasonable number to ask a domain specialist to provide for a new topic. These exemplar questions are all semantically similar but differ in syntactic formulation, such as “How much does it cost?” and “What’s the price for the monthly subscription?”. We use embeddings from the testing models as sentence representations and conduct the semantic matching on 10,000 sampled question sentences from our dataset described in section 4.1.
\subsubsection{Metrics}
Section 3.2 proposes two score computation methods for semantic matching, we can therefore rank the samples by the score using either approach. Since our dataset is unlabelled, our internal raters manually evaluated the precision at certain cutoff points after ranking: top 50, top 100 and top 200 samples with highest similarity score. This metric is noted as \textbf{Prec@50} to describe the precision at top 50 samples in below experiments.
Because we do not have labels for our data, we are not able to calculate recall. Instead we calculate the “hit rate” defined as:
\begin{equation}
\label{eq:3}
HR = \frac{number\;of\;predicted\;positive\;samples}{number\;of\;all\;samples}
\end{equation}
To compare the hit rate of different approaches, we set a target precision score and calculate the hit rate at that precision level. \textbf{HR@Prec=0.9} denotes the hit rate of the level when the precision is 0.9
\begin{figure*}[t]
\centering
\includegraphics[width=1\textwidth]{figure3.png}
\caption{“Pricing” questions in our dashboard.}
\label{fig3}
\end{figure*}
\subsubsection{Performance Comparison}
In Table 3, we evaluate unweighted semantic matching using (\ref{eq:1}) for different embedding models. It is clear that SBERT, a BERT variant that was fine-tuned on inferences tasks, performs better at measuring the semantic similarity of sentences. Also, for BERT and SBERT, using mean as sentence representation outperforms \textit{CLS} token in this task. However, sentence representations from GPT-2 performs poorly thus are not a good fit for semantic comparison.
In discussions with business users, we have observed that when reading reports, false positives are highly distracting. We therefore require a precision score of 0.9 or higher. As Table 4 shows, the weighted score using (\ref{eq:2}) has slightly higher precision at all cutoff points, it also provides a 23\% relative improvement in hit rate over the unweighted score. This results in a higher density of true positives in the analytics reports that collate the semantically similar questions.
\section{Early-Stage Deployment}
We have implemented a data visualization dashboard (Figure 3) based on the best semantic matching approach described above (SBERT-mean with weighted similarity score). The dashboard groups semantically similar questions for topics of interest to managers such as “Pricing” and “Contact Information”. The dashboard is currently available for users enrolled in an early adopter program.
The dashboard helps the call center businesses collect and group questions asked by the customers. More importantly, it provides managers with information that they could use to coach agents (e.g. by drilling down to review the occurrence of specific questions in transcribed conversations) so that they can better prepare answers for the commonly asked questions in calls.
\section{Conclusion}
We showed that when evaluating using a directional similarity metric, sentence-level representations produced by out-of-the-box contextualized embedding models such as BERT and GPT-2 are anisotropic, which makes them unsuitable for semantic similarity comparison tasks such as grouping semantically similar questions found in natural, human-to-human conversations. However, SBERT, which fine-tunes BERT model on NLI and STS datasets mitigates the anisotropy issue, thereby improving the performance of the semantic comparisons. Combining the best sentence embedding representation with the weighted scoring functions yields more precise groupings of semantically similar sets of the naturally-occurring questions in our dataset.
The business solution that we have described only requires a few exemplar question sentences as seeds, to yield performance that meets our user needs. The solution does not require expensive data labelling to train a supervised classifier. We have implemented a visualization dashboard using this solution for our early enrolled users.
\bibliographystyle{acl_natbib}
| {'timestamp': '2022-06-06T02:14:53', 'yymm': '2206', 'arxiv_id': '2206.01585', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01585'} | arxiv |
\section{Introduction}
Unmanned Aerial Vehicles (UAVs) are being used in many diverse operations in a range of fields at present, including but not limited to aerial surveillance, search and rescue operations, parcel delivery, and agriculture \cite{droneUse,zaheer2016aerial}. However, one of the most critical design issues for UAVs is that they often suffer from short flight time, typically tens of minutes, mainly due to their high power requirements and limited battery capacity \cite{thibbotuwawa2018energy,hu2020energy}. Thus, it is important to correctly estimate the flight time and range to ensure reliable operation and energy-efficient path planning. To accomplish this, an accurate drone energy consumption model is essential, which enables quantifying the impact of different factors, i.e., wind speed, payload, ground speed, altitude, etc., affecting the energy consumption of drones in various scenarios.
However, it is a challenging task to incorporate all such factors into a single energy consumption model. There are numerous factors related to the drone design (weight, number of rotors, battery weight/efficiency, avionics), the environment (wind conditions, weather, ambient temperature), drone dynamics (acceleration, angle of attack, flight angle/altitude), and operational requirements (flight time, payload). Existing models on drone energy consumption focuses on certain aspects of drones and usually consider a subset of factors~\cite{ref1}. Some models can only be applied to particular conditions such as hovering largely ignoring the impact of the air speed~\cite{model2}. There are models focusing more on drones acting like fixed-wing aircrafts~\cite{ref4} or more like helicopters~\cite{model2}. This results in conflicting predictions across different energy consumption models despite same input parameters and trajectories~\cite{ref1}. Apart from the models taking theoretical approaches~\cite{ref4,model2,model3,model4}, there have been attempts to use regression models~\cite{model5,Prasetia} to match the model better to the realistic measurements. In particular, black box modeling of drones also reports decent results across the missions starting from take-off to return~\cite{Prasetia}. The work also reports that to account for impacts of control profiles, which is often ignored in other models, a time-series machine learning methods needs to be investigated.
In this paper, we aim at comparing some prominent drone energy consumption models in the literature and propose a long-short term memory (LSTM) deep learning-based architecture, useful for prediction of time-series data, for energy consumption model of drones. Despite such efforts to accurately model the drone energy consumption and decent accuracy reported in the literature, there has been few works on directly comparing different types of models on a real measured data. Our efforts to apply the energy consumption models to a recently published measurement data~\cite{ref5}, have shown that significant discrepancies exist between the predicted values and the independently-collected real-world measurement. Therefore, we consider a deep learning approach to create an energy consumption model that considers all aspects of flight (take-off, landing, cruising, hovering) from empirical data and the prediction results have been compared with model-based approaches fitted to the real-world data.
The key contributions in this paper can be summarized as follows:
\begin{itemize}
\item We evaluate the performance of several existing drone energy consumption models using the specific realistic dataset \cite{ref5}.
\item We propose a learning-based approach using the Long-Short Term Memory (LSTM) deep learning based architecture for power consumption prediction of drones.
\item We carry out sensitivity analysis on the trained LSTM model to give some insights on feature importance, i.e., interpretability of the model.
\end{itemize}
The remainder of this paper is organised as follows. Section \ref{TB} elaborates the technical background on some prominent drone energy consumption models in the literature. Section \ref{design} presents our key research problem and propose the LSTM-based system architecture to address the design issue. Section \ref{result} discusses our evaluation results using different models. Finally, Section \ref{conclusion} concludes the paper.
\section{Background: Drone Power Models} \label{TB}
In this section, we introduce drone energy models used in the literature.
Prior works on path planning algorithms assume drone energy models for evaluating battery usage.
As the flight distance and the number of turns a drone makes determines the paths, energy consumption models regards the factors important in estimating the energy consumption~\cite{ref2}.
Other factors such as wind speed, wind angle, and altitude are not considered in the work.
More elaborate models consider the impact of acceleration and deceleration~\cite{ref3}.
Several tests were performed in this study which focuses on three main performance metrics: straight line distance, the effects of velocity, and the effects of turning.
The study has shown that higher speeds result in lower overall energy consumption and higher turning angles resulted in higher overall energy consumption.
Analysis of all aspects of on-board electronics to form total energy consumption is also explored and is validated using empirical data from a commercial drone~\cite{additionalref1}. Energy consumption primarily comes from the motors, followed by communications, processors, and sensors. Communications, processors, and sensors were discovered to be minimal in contribution but not negligible in total energy consumption.
Among such models, we selected representative ones to be investigated in this paper also designated as ``five fundamental models for drone energy consumption of steady level flight’' in a recent survey~\cite{ref1}, dubbed D’Andrea, Dorling et al., Stolaroff et al., Kirchstein, and Tseng energy models.
\subsection{D’Andrea Energy Model}
The D’Andrea energy model is based on the drone’s lift-to-drag ratio~\cite{model1,ref1}. The formula is optimised for steady drone flight and uses the drone’s mass, airspeed, lift-to-drag ratio, and the power transfer efficiency of the battery. The model comes in two variations; a standard variation with no account for wind, and one that does account for wind in terms of headwind experienced by the drone.
The model is further expanded by implementing “empty returns”, which occurs when the drone drops off the payload before taking the return flight~\cite{ref4}.
The model makes several assumptions to create their energy consumption model. The payload of the drone is no heavier than 2~kg and has an operating range of 10~km. A lift-to-drag ratio of a constant value is selected, inspired by helicopter lift-to-drag ratios and used for comparison with them. Variables such as cruising speed during missions are set to a predetermined value of 45 km/h. The power transfer efficiency is set to 0.5 \cite{model1}. A constant $p_{avio}$ is added to account for vehicle avionics.
\begin{equation}
P = \frac{\sum_{k=1}^{3} m_k v_a}{370 \eta r} + p_{avio},
\end{equation}
where $m_k$ represents the mass of each drone component including drone weight $(k=1)$, battery weight $(k=2)$ and payload weight $(k=3)$. $v_a$ is the drone airspeed, i.e., the speed of drone relative to air, $\eta$ is the power transfer efficiency, $r$ is the lift-to-drag ratio, and $p_{avio}$ is the power required for drone avionics \cite{ref1}.
\subsection{Dorling et al. Energy Model}
The Dorling energy model only takes into consideration drone hovering, and thus, cannot detail energy consumption for the take-off, cruising, and landing~ \cite{model2,ref1}. However, this model does consider the components used in the drone such as the number of rotors and propeller area. Through testing, the equations that dictate the energy consumption was reduced to a linear function dependent on the battery and payload of the drone.
The model is derived from the equation used to calculate the power of a helicopter and is adapted for multi-rotors. The mass components of drone $m_k$ are used as parameters alongside gravity ($g$), air density ($\rho$), number of rotors ($n$), and propeller area ($\zeta$).
\begin{equation}
P = \frac{g (\sum_{k=1}^{3} m_k) ^{\frac{3}{2}}}{\sqrt{2n\rho\zeta}}
\end{equation}
\subsection{Stolaroff et al. Energy Model}
The Stolaroff energy model designs its model using the physics of drone flight including the forces experienced by the drone due to its weight, parasitic drag, and induced drag~\cite{model3,ref1}.
The model accounts for heavy winds by utilising an adapted version of the previous model by using the angle of attack of the drone. However, it was noted that large values of the angle of attack resulted in unstable results. The model consists of the thrust produced ($T$), angle of attack ($\alpha$), power transfer efficiency ($\eta$), and the induced speed caused by the drone ($v_i$). It can be presented as follows:
\begin{equation}
P = \frac{T ( v_a sin(\alpha) + v_i)} {\eta}
\end{equation}
where $T=g\sum_{k=1}^{3}m_k + 0.5 \rho \sum_{k=1}^{3} C_{D_k} A_k v_a^{2}$ with the drag coefficient $C_{D_k}$, and the projected area perpendicular to travel of each drone component $A_k$ \cite{ref1}.
\subsection{Kirchstein Energy Model}
The Kirchstein energy model is based on the drone’s environmental conditions and flight trajectory~\cite{model4,ref1}. It is another component model with a focus on optimised take-off angle, cruising altitude, level flight, descent, and landing. This model takes into consideration a wide range of factors such as the power required for climbing, avionics, and different power losses resulting from the electric motor and power transmission inefficiencies. The model covers the power consumption from air drag from the drone’s profile and the rotor profile, the lift required for flight, the climb to the designated altitude, and power supplied to any electronics on-board.
\begin{equation}
P = \frac{1}{\eta} (\kappa Tw + \frac{1}{2}\rho(\sum_{k=1}^{3} C_{D_k} A_k)v_a^{3} + \kappa_2(g\sum_{k=1}^{3} m_k)^{1.5} +\kappa_3(g\sum_{k=1}^{3} m_k)^{0.5} v_a^{2}) + \frac{P_{avio}}{\eta_c},
\end{equation}
where $\kappa, \kappa_2, \kappa_3$ are constants, $w$ is the downwash coefficient, and $\eta_c$ is the battery charging efficiency \cite{ref1}.
\subsection{Tseng Energy Model}
The Tseng energy model differs from the other energy models as it consists of a nine-term nonlinear regression model created from collected data~\cite{model5}. This model was created from horizontal and vertical speeds and accelerations, payload, mass, and wind speed data gathered from empirical testing. The drone used for data collection was a DJI Matrice 100 and tested for payloads of 0, 0.3, and 0.6 kg. The drone used for testing consisted of three experiments that recorded the drone’s ability to hover without any input or movement, ability to climb and descend, and ability to move horizontally. The model assesses the impact of motion through these tests and the payload weights to create the model. A 3DR Solo drone was also used to create an alternative version of the model for smaller sized drones with the expression for energy consumption shown below. Note that the model is essentially a function of payload mass $m_3$ and the airspeed $v_a$ \cite{ref1}.
\begin{equation}
P = -2.595v_a + 0.197 m_3 + 251.7.
\end{equation}
\section{Data-Driven Model and Proposed LSTM Architecture} \label{design}
In this section, we introduce the data-driven model to fit the realistic dataset~\cite{ref5}. We first present the problem statement for the model fitting task, then we present details for the dataset, and finally we demonstrate the proposed architecture.
\subsection{Problem Statement}
The key problem that we are considering here is to build an energy consumption model which can take a sequence of input feature data from a drone and predict the corresponding energy consumption of the drone as output. More specifically, the input data essentially captures the characteristics, dynamics and environmental context, e.g., wind speed, payload, ground speed, for the drone under test in a given scenario.
Mathematically, let $F_{t} \in \mathbb{R}^{N}$ be the feature vector consisting of the $N$ features for the drone at time $t$. Let $E_{t} \in \mathbb{R}$ denote the energy consumption of the drone at time $t$. For a given time window $\mathcal{T}: =\left\lbrace 1 , 2, \dots, T \right\rbrace$, our objective is to find a learning function $H(.)$ which is able to address the following problem:
\begin{equation}\label{localopt}
\begin{aligned}
\min_{H} \quad & \sum_{t \in \mathcal{T}} (E_{t} - \hat{E}_{t})^2 \\
\textrm{s.t.} \quad & \hat{E}_{t} = H(F_{t}) \\
\end{aligned}
\end{equation}
where $\hat{E}_{t}$ denotes the predicted energy consumption of the drone at time $t$ with respect to the input feature vector $F_{t}$.
\subsection{Experimental Dataset}
The experimental dataset used in this work is from the paper \cite{ref5}. The dataset presents some very recent energy consumption information for a DJI Matrice 100 drone that consists of a total of 195 test flights with variations in payload, speed, and altitude. A total number of 28 features were recorded onboard which were taken from the battery state, Global Positioning System (GPS), Inertial Measurement Unit (IMU), and the wind measurement unit. A total number of 21 features was included from the dataset in order to create our energy prediction model, the details of which are summarized as follows:
\begin{itemize}
\item Wind Speed: Speed of wind recorded by the anemometer in meters per second (m/s).
\item Wind Angle: Angle of the airspeed recorded by the anemometer with respect to north in (degrees).
\item Position X, Y, Z: Longitude, latitude and altitude recorded by the GPS (degrees).
\item Orientation X, Y, Z, W: Orientation as recorded by the IMU in (quarternions).
\item Velocity X, Y, Z: Ground speed recorded by the GPS and IMU in meters per second (m/s).
\item Angular X, Y, Z: Angular velocity recorded by the IMU in radians per second (rad/s).
\item Linear Acceleration X, Y, Z: Linear acceleration recorded by the IMU in meters per second squared (m/s$^{2}$).
\item Speed: Input ground speed before flight in meters per second (m/s).
\item Payload: Payload mass attached to the drone prior to a test in grams (g).
\item Altitude: Input altitude the drone rises to before following flight route in meters (m).
\end{itemize}
\subsection{System Architecture}
To find out the learning function $H$, we propose the LSTM architecture which is shown in the Fig. \ref{architecture} below. Specifically, the proposed LSTM architecture consists of two bidirectional LSTM layers stacked together with a dropout layer attached to the second LSTM layer before connecting to a dense layer for output. Some details for model and network setup are reported as follows:
\begin{itemize}
\item The activation function used for the output layer was a tangent function.
\item The number of hidden cells for each LSTM layer was defined as 128.
\item The length of the input time window $T$ was set as 10.
\item The Adam optimizer was chosen for model training.
\item The proposed model was assembled using Keras at the backend.
\end{itemize}
In order to achieve the optimal performance for energy prediction using the proposed architecture, we considered dropout, batch size and learning rate as hyperparameters for model tuning through grid search. For each setting of the hyperparameters, a 5-fold cross-validation was carried out on the dataset to evaluate the performance of the resulting model. The best set of parameters which results in the minimum averaged mean square error (MAE) was chosen as the optimal hyperparameters for the proposed model. Table \ref{tab1} presents our results for the hyperparamters tuning in different settings. We also present the calculation results for the root mean square error (RMSE) in the table for reference, and it can be seen that the optimal hyperparameters for the model are presented in the third row of the table, and this finding is consistent with both performance metrics, i.e., averaged RMSE and averaged MAE. Finally, the training and validation loss under the optimal configuration are shown in Fig. \ref{trainingCurve}, where two curves are converging gradually in a few number of epochs.
\begin{figure*}[htbp]
\centering
\includegraphics[width=1\columnwidth, height=5in]{architecture.png}
\caption{The proposed stacked bidirectional LSTM-based system architecture.}\label{architecture}
\end{figure*}
\begin{table}[htbp]
\caption{Hyperparameter tuning for the proposed model}\label{tab1}
\centering
\begin{tabular}{|c|c|c|c|c|}
\hline
\textbf{Dropout} & \textbf{Learning Rate} & \textbf{Batch Size} & \textbf{\begin{tabular}[c]{@{}l@{}}Avg. \\ RMSE\end{tabular}} & \textbf{\begin{tabular}[c]{@{}l@{}}Avg. \\ MAE\end{tabular}} \\\hline
0.2 & 0.001 & 128 & 47.4891 & 5.7213 \\ \hline
0.2 & 0.0001 & 128 & 50.7283 & 6.0008 \\ \hline
0.5 & 0.001 & 128 & 46.9918 & 5.6942 \\\hline
0.5 & 0.0001 & 128 & 48.3828 & 5.8538 \\\hline
0.5 & 0.01 & 128 & 63.1021 & 6.8779 \\\hline
0.5 & 0.001 & 64 & 51.3855 & 5.9844 \\\hline
\end{tabular}
\end{table}
\begin{figure}[htbp]
\centering
\includegraphics[width=\columnwidth, height=2.5in]{TrainingLossCurve}
\caption{Training and validation loss curves using the optimal configuration.}\label{trainingCurve}
\end{figure}
\section{Results and Discussion} \label{result}
\subsection{Performance Evaluation}
In this section, we present our experimental results using the five prominent mathematical models as well as the proposed LSTM model in its optimal configuration. Our objective is to illustrate the differences of model prediction performance based on the realistic dataset \cite{ref5}, and reveal the superiority of the model performance using our proposed LSTM-based architecture. Specifically, we applied all models to a specific flight (flight 276) which had not been used for model training. While the five models originated from different studies, unified notation between parameters was used for fair comparison similar to the approach used in \cite{ref1}. Input parameters from the dataset were airspeed and the weight components of the drone, which were adapted to use in all models. The prediction results for different models under test are illustrated in Fig. \ref{fig15} and Fig. \ref{lstm_result}, where Fig. \ref{fig15} compared the performance for all mathematical models and Fig. \ref{lstm_result} compares performance for the LSTM-based model only. The key performance metrics are also summarised and reported in Table \ref{tab2} for ease of comparison.
\begin{table}[htbp]
\caption{Energy Model Comparison}\label{tab2}
\centering
\begin{tabular}{|c|c|c|}
\hline
\textbf{Author} & \textbf{Avg. RMSE} & \textbf{Avg. MAE} \\\hline
D'Andrea & 745.9512 & 21.7650 \\\hline
D'Andrea (With Headwind) & 919.2040 & 23.7520 \\\hline
Dorling & 365.1678 & 18.3391 \\\hline
Stolaroff & 291.6590 & 16.2421 \\\hline
Kirchstein & 275.8223 & 13.8690 \\\hline
Tseng & 131.3750 & 9.5263 \\\hline
Proposed LSTM model & 36.2770 & 4.9080 \\ \hline
\end{tabular}
\end{table}
\begin{figure}[htbp]
\centering
\includegraphics[width=\columnwidth, height=2.3in]{energy_consumption_math_models}
\caption{Comparison of the five mathematical models for energy consumption.}\label{fig15}
\end{figure}
\begin{figure}[htbp]
\centering
\includegraphics[width=\columnwidth, height=2.3in]{energy_consumption_LSTM_models}
\caption{Comparison of the proposed LSTM model with the ground truth.}\label{lstm_result}
\end{figure}
Among the five fundamental models, the D'Andrea model performs poorest with the highest averaged RMSE found for the model variant with the headwind being factored in. In contrast, the Tseng energy model achieves the best prediction result in that both performance metrics, i.e., averaged RMSE and averaged MAE, are lowest. This conclusion can also be further validated in Fig. \ref{fig15} where the Tseng model maintains a flat prediction throughout the duration of the evaluation which is clearly closest to the ground truth. However, none of these fundamental models achieves a promising result when compared with the proposed LSTM model where the averaged MAE is found as low as 4.908. In practice, this simply implies that on average the predicted energy only incurs 4.9080 watts bias compared with the realistic energy consumption.
\subsection{Sensitivity Analysis}
To further illustrate some interpretability of the trained LSTM model, we now carry out a sensitivity analysis for the learned model. In particular, we are interested in answering the following question, that is how the altitude, payload and speed as input features can contribute to the energy consumption for drones. Our results are shown in Table \ref{tabData} and Fig. \ref{fig1}. More specifically, the divergent bar chart in Fig. \ref{fig1} takes intervals at steps and half steps, where steps are taken as the minimum or maximum value of the input parameter, and half steps are the midpoints from the mean. Table \ref{tabData} shows the steps taken for each feature of interest. Fig. \ref{fig1} shows payload contributing the most towards change in overall power consumption followed by speed and altitude. Interestingly, the figure also demonstrates that the speed factor is negatively correlated to power consumption of the drone while the altitude factor can positively contribute to the power consumption. Such insight on speed is consistent with what we found in the Tseng model where airspeed is also negatively correlated with power consumption.
\begin{table}[htbp]
\caption{Power Consumption Sensitivity Data Table}\label{tabData}
\centering
\begin{tabular}{|l|l|l|l|l|l|}
\hline
& \textbf{Step-1} & \textbf{Step-1/2} & \textbf{Step 0} & \textbf{Step+1/2} & \textbf{Step+1} \\ \hline
Altitude (m) & 25.00 & 43.75 & 62.50 & 81.25 & 100.00 \\ \hline
Payload (g) & 0 & 187.50 & 375.00 & 562.50 & 750.00 \\ \hline
Speed (m/s) & 4.00 & 6.00 & 8.00 & 10.00 & 12.00 \\ \hline
\end{tabular}
\end{table}
\begin{figure}[htbp]
\centering
\includegraphics[width=\columnwidth, height=2.3in]{DivergentBarChart_new}
\caption{Sensitivity of power consumption to key features}\label{fig1}
\end{figure}
\section{Conclusion} \label{conclusion}
In this paper, we propose a learning-based approach using the LSTM-based deep learning architecture for accurately modelling energy consumptions of drones. We have revealed the efficacy of the proposed model by comparing its performance with the five fundamental mathematical based energy models using a realistic dataset that can be publicly accessed in \cite{ref5}. Finally, we have also implemented a sensitivity analysis on the trained model with a view to provide some insights and explainability for the fine-tuned model. To conclude, we believe that the work presented in this paper is an important step towards using a data-driven method to understand energy consumption pattern for drones. However, we note that one obvious limitation in our current work is that the proposed deep learning model has not been validated comprehensively across different energy datasets. This challenge will be addressed as part of our future work. In addition, we shall investigate the effectiveness of using a federated learning based framework \cite{lstmSimulatedRef} to further improve accuracy of the proposed model.
\subsubsection{Acknowledgements}
The author Carlos Muli would like to thank the ide3a team for kindly accommodating a scholarship which has made this research work possible. This work has also emanated from research supported in part by Science Foundation Ireland under Grant Number SFI/12/RC/2289\_P2, and the Entwine Research Centre at Dublin City University.
\bibliographystyle{ieeetran}
| {'timestamp': '2022-06-06T02:15:38', 'yymm': '2206', 'arxiv_id': '2206.01609', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01609'} | arxiv |
\section{Introduction}
\label{sec:introduction}
\looseness=-1
An agent is expected to satisfy three important properties for a reliable deployment in real-world applications: \textbf{(i)} The agent should learn \emph{fast} with as few episode failures as possible. \textbf{(ii)} The agent should \emph{maintain high reward} when facing new environments similar to the training environment after deployment. \textbf{(iii)} The agent should \emph{flag anomalous environment states} when it does not know what action to take in an unknown environment. These three practically desirable properties translate into three technical properties in reinforcement learning agents. Indeed, a reinforcement learning agent should achieve high \emph{sample efficiency} at training time \cite{sample-efficient-ac}, high \emph{generalization} performance on test environments similar to the training environment \cite{epistemic-pomdp}, and high \emph{Out-Of-Distribution (OOD) detection} scores on environment unrelated to the training task \cite{ood-detection-survey, ood-automotive-perception}.
\looseness=-1
In this paper, we argue that \emph{aleatoric} and \emph{epistemic} uncertainty are key concepts to achieve these desired practical and technical properties. The aleatoric uncertainty represents the irreducible and inherent stochasticity of the environment. Thus, an environment region with high aleatoric uncertainty is unlikely to be interesting to explore at training time because it could be uninformative (e.g. a sensor is very noisy) or dangerous (e.g. the environment has an unpredictable behavior). In contrast, the epistemic uncertainty represents the lack of information for accurate prediction. Thus, an environment region with high epistemic uncertainty is potentially promising to explore to build a better understanding of the environment (e.g., a state has unknown transition dynamics because it has never been explored).
\begin{figure*}[t]
\centering
\vspace{-8mm}
\includegraphics[width=.65\linewidth]{resources/diagram-cropped_2.pdf}
\caption{Overview of our proposed desiderata for uncertainty in RL (See sec.~\ref{sec:desiderata}).}
\vspace{-3mm}
\label{fig:diagram}
\vspace{-4mm}
\end{figure*}
\looseness=-1
The core motivation of our work is to disentangle the properties of aleatoric and epistemic uncertainty estimates in RL to build agents with reliable performance in real-world applications. This motivation is similar to supervised learning (SL) where previous works defined \emph{desiderata}, \emph{models}, and \emph{evaluation} methods for aleatoric and epistemic uncertainty \cite{uncertainty-deep-learning, review-uncertainty-dl, dataset-shift, robustness-uncertainty-dirichlet}. Important examples of models using a single or multiple forward passes for uncertainty estimation in SL are MC dropout \cite{dropout}, ensemble \cite{ensembles, hyper-ensembles, batch-ensembles}, deep kernel learning \cite{simple-baseline-uncertainty, due, duq, uceloss}, and evidential networks \cite{postnet, priornet, natpn, evidential-regression}. Further, empirical evaluation of uncertainty estimates in SL focuses \emph{only} on testing time with Out-Of-Distribution (OOD) detection and generalization or detection of shifts \citep{dataset-shift, shifts-dataset}. In contrast to SL, the RL setting is more complex since it cares about the performance of uncertainty estimates at \emph{both} training and testing time.
\looseness=-1
\textbf{Our Contributions.} In this work, we propose a framework for aleatoric and epistemic uncertainty estimation in RL: \textbf{(Desiderata)} We explicitly define four desiderata for uncertainty estimation in RL at both \emph{training} and \emph{testing time} (See fig.~\ref{fig:diagram}). They cover the behavior of \emph{aleatoric} and \emph{epistemic} uncertainty estimates w.r.t. the sample efficiency in the training environment and, w.r.t. the generalization performance in different testing environments. \textbf{(Models)} We carefully combine a diverse set of uncertainty estimation methods in SL (i.e. MC dropout, ensemble, deep kernel learning, and evidential networks) with Deep Q-Networks (DQN) \cite{dqn}, a ubiquitous RL model that is not equipped with uncertainty estimate by default. These combinations require a \emph{minimal} modification to the training procedure of the RL agent. We discuss \emph{theoretical} evidence on the ability of these combinations to fulfill the uncertainty desiderata. \textbf{(Evaluation)} Finally, we also propose a \emph{practical} methodology to evaluate uncertainty in RL based on OOD environments and domain shifts.
\section{Problem Setup}
\label{sec:setup}
\looseness=-1
\textbf{Uncertainty in SL.} The objective of SL is to accurately predict the output \smash{$\y\dataix$} given an input \smash{$\x\dataix$} with index \smash{$\idata$}. It differentiates between two types of uncertainty: the uncertainty on the label prediction \smash{$\y\dataix$} described by the \emph{aleatoric distribution} \smash{$\prob(\y\dataix \mid \expparam\dataix)$} with parameters \smash{$\expparam\dataix$} estimated from the input $\x\dataix$, and the uncertainty on the predicted label distribution parameters $\expparam\dataix$ described by the \emph{epistemic distribution} \smash{$\prior(\expparam\dataix \mid \priorparam\dataix)$} with parameters $\priorparam\dataix$ estimated from the input $\x\dataix$. Intuitively, the variations of the aleatoric distribution will be high when the input \smash{$\x\dataix$} does not provide discriminative information to determine the label \smash{$\y\dataix$}. The variations of the epistemic distribution will be high when the input \smash{$\x\dataix$} does not provide enough information to determine the label distribution \smash{$\prior(\expparam\dataix \mid \priorparam\dataix)$} described by the parameters \smash{$\priorparam\dataix$}. Thus, the aleatoric uncertainty can be measured in practice by computing the entropy, i.e \smash{$u_\text{alea}(\x\dataix)=\entropy(\prob(\y\dataix \ensuremath{\,|\,} \expparam\dataix))$}, or the variance, i.e. \smash{$u_\text{alea}(\x\dataix)= \variance(\prob(\y\dataix \ensuremath{\,|\,} \expparam\dataix))$}, of the aleatoric distribution, while the epistemic uncertainty can be measured by computing the entropy, i.e. \smash{$u_\text{epist}(\x\dataix)=\entropy(\prior(\expparam\dataix \mid \priorparam\dataix)$}, of the epistemic distribution \cite{priornet, postnet, natpn}. Further, SL also distinguishes between sampling-based which often require multiple forward passes for uncertainty estimation, and sampling-free methods which often require a single forward pass for uncertainty estimation. Sampling-based methods like MC drop-out \cite{dropout} and ensemble \cite{ensembles, hyper-ensembles, batch-ensembles} estimate uncertainty by aggregating statistics (e.g. mean and variance) from different samples which \emph{implicitly} describe the epistemic distribution \smash{$\prior(\expparam\dataix \mid \priorparam\dataix)$}. Sampling-free methods like deep kernel learning models \cite{simple-baseline-uncertainty, due, duq, uceloss} and evidential networks \cite{postnet, priornet, natpn, evidential-regression} estimate uncertainty by \emph{explicitly} parametrizing the epistemic distributions \smash{$\prior(\expparam\dataix) \mid \priorparam\dataix)$} with known distributions such as Normal and Normal Inverse-Gamma (NIG) distributions, thus enabling efficient and closed-form computation of the distribution statistics (incl. mean, variance or entropy).
\looseness=-1
\textbf{Uncertainty in RL.} We consider the task of learning RL policies interacting with an environment with fully observed states at every time step $t$. The environment is described by a Markov Decision Process (MDP) $(S, A, r, T, \rho, \gamma)$ where $S$ is the state space, $A$ is the action space, \smash{$r(\s\datatx, a\datatx)$} is the reward associated to the action \smash{$a\datatx$} and state \smash{$\s\datatx$}, \smash{$T(\s^{(t+1)}|\s\datatx, a\datatx)$} is the transition probability, \smash{$\rho(\s^{(0)})$} is the initial state distribution, and $\gamma$ is the discount factor. Given the current state \smash{$\s\datatx$}, our goal is to learn a policy predicting the action \smash{$a\datatx$} leading to the highest reward \smash{$\y\datatx=r(\s\datatx, a\datatx)$} in addition to the aleatoric uncertainty \smash{$u_\text{alea}(\s\datatx, a\datatx)$} and the epistemic uncertainty \smash{$u_\text{epist}(\s\datatx, a\datatx)$} on the predicted reward. Similar to SL, the aleatoric and epistemic distributions can be instantiated with \smash{$\prob(\y\datatx \mid \expparam\datatx)$} and \smash{$\prior(\expparam\datatx) \mid \priorparam\datatx)$} where the predicted value is the future reward i.e. \smash{$\y\datatx=r(\s\datatx, a\datatx)$}. Intuitively, the variation of the aleatoric distribution will be high when the current state $\s\datatx$ and action $a\datatx$ only contains noisy information to determine the future reward \smash{$\y\datatx=r(\s\datatx, a\datatx)$} while the epistemic uncertainty will be high when the current state \smash{$\s\datatx$} and action \smash{$a\datatx$} does not provide enough information according to the model to determine the reward distribution \smash{$\prior(\expparam\datatx \mid \priorparam\datatx)$} described by the parameters \smash{$\priorparam\datatx$}. Finally, we consider three action selection strategies which is a crucial choice for exploration and generalization in RL: the \emph{epsilon-greedy} strategy \cite{epsilon-greedy} which selects the action with the highest predicted reward with probability $1-\epsilon$ and samples a random action otherwise, the \emph{sampling-aleatoric} strategy which takes the action with the highest predicted reward based on one aleatoric distribution sample i.e. \smash{$a\datatx = \max_{a} \y\datatx$} where \smash{$\y\datatx \sim \prob(\y\datatx | \expparam\datatx)$}, or the \emph{sampling-epistemic} strategy which takes the action with the highest predicted reward based on one epistemic distribution sample i.e. \smash{$a\datatx = \max_{a} \expectation_{\prob(\y\datatx | \expparam\datatx)}[\y\datatx]$} where \smash{$\expparam\datatx \sim \prior(\expparam\datatx | \priorparam\datatx)$}. The sampling-epistemic strategy corresponds to the Thompson sampling strategy\cite{thompson-sampling}.
\section{Desiderata for Uncertainty Quantification in RL}
\label{sec:desiderata}
\looseness=-1
In this section, we \emph{explicitly} define four intuitive and general desiderata that capture the desired behavior for uncertainty estimates in our RL setup. The desiderata cover \emph{aleatoric} and \emph{epistemic} uncertainty at both \emph{training} and \emph{testing} time. The first distinction differentiates between aleatoric and epistemic uncertainty which are commonly used concepts in SL \cite{uncertainty-deep-learning, priornet, natpn}. In contrast, RL mostly focuses on measuring aleatoric uncertainty with risk-sensitive policy or distributional RL \cite{distributional-rl-prespective, distributional-rl, iqn}. The second distinction differentiates between training and testing time relevant to sample efficiency and generalization in RL. In contrast, SL mostly focuses on testing time performance.
\looseness=-1
\textbf{Training Time.} We describe the desired behavior of uncertainty estimates at training time. First, we describe the desired uncertainty behavior when observing more samples of the training environment.
\begin{desiderata}
\label{ax:training_state}
An agent training longer on states sampled from one specific environment should become more epistemically confident when predicting actions on states sampled from the same specific environment.
\end{desiderata}
\vspace{-2mm}
Intuitively, an agent observing more samples from the same environment distribution should accumulate more knowledge through time thus being more epistemically certain. In practice, des.~\ref{ax:training_state} expresses that the epistemic uncertainty estimates should reflect the accumulated knowledge, and thus the convergence, of the agent during training. We test des.~\ref{ax:training_state} in the experiments (see sec.~\ref{sec:experiments}) by tracking the epistemic uncertainty at training time. Second, we describe the behavior of the total reward when selecting actions based on uncertainty estimates at training time.
\begin{desiderata}
\label{ax:training_strategy}
All else being equal, an agent selecting actions with the sampling-aleatoric strategy at training time should achieve lower sample efficiency than an agent selecting actions with the sampling-epistemic strategy.
\end{desiderata}
Intuitively, an agent exploring states with more (irreducible) aleatoric uncertainty would gain less knowledge about the environment dynamic than an agent exploring states with high epistemic uncertainty where the agent lacks knowledge. However, there is an important trade-off between over- or under-exploring epistemically uncertain actions which could lead to lower sample efficiency. The sampling-epistemic strategy, which corresponds to Thompson sampling \cite{thompson-sampling}, mitigates this exploration-exploitation problem by sampling action w.r.t. the epistemic distribution. Thompson sampling has already \emph{empirically} demonstrated high sample efficiency in deep RL problems \cite{dropout} and provably achieve low regret in many decision-making problems like multi-arms Bandit \cite{thompson-sampling-mab, thompson-sampling-information}. In practice, des.~\ref{ax:training_strategy} suggests that an agent should use the sampling-epistemic strategy for a better exploration-exploitation trade-off. We test des.~\ref{ax:training_strategy} in the experiments (see sec.~\ref{sec:experiments}) by comparing the sample efficiency of the sampling-aleatoric and the sampling-epistemic strategies during training.
\looseness=-1
\textbf{Testing Time.} We describe the desired behavior of uncertainty estimates at testing time. First, we describe the desired uncertainty behavior when observing samples from an environment different from the training environment.
\begin{desiderata}
\label{ax:testing_state}
At testing time, epistemic uncertainty should be greater in environments that are very different from the original training environments.
\end{desiderata}
\vspace{-2mm}
The environment difference could be measured with different distances depending on the task or application requirements \cite{domain-shifts-rl}. Intuitively, an agent should be less confident when observing new states at test time that were not used to collect knowledge at training time. In practice, des.~\ref{ax:testing_state} suggests that an agent should be able to use epistemic uncertainty estimates to detect states which are abnormal compared to the states observed during training. We test des.~\ref{ax:testing_state} in the experiments (see sec.~\ref{sec:experiments}) by comparing the epistemic uncertainty of the training environment against the uncertainty in noisy environments at testing time. Noisy environments include environments with completely random states and thus irrelevant to the training task, and environments with different strengths of perturbation on the original states, actions, or transition dynamics. Second, we describe the behavior of the total reward when selecting at testing time actions based on uncertainty aleatoric or epistemic uncertainty estimates.
\begin{desiderata}
\label{ax:testing_strategy}
All else being equal, an agent sampling actions from the epistemic uncertainty at training and testing time should generalize better at testing time than an agent sampling actions from the aleatoric uncertainty.
\end{desiderata}
\vspace{-2mm}
Intuitively, an agent exploring more epistemically uncertain states at training time would collect more knowledge about the environment, thus generalizing to more states at testing time. Further, since the environment dynamic is not directly observed, an agent should account for the epistemic certainty on the current state to take actions that generalize better at testing time. In particular, it has been shown that the Bayes-optimal Markovian policy at testing time is stochastic in general due to the partially observed MDP dynamic sometimes called epistemic POMDP \cite{epistemic-pomdp}. In practice, des.~\ref{ax:testing_strategy} suggests that an agent should use the sampling-epistemic strategy for more robust generalization performance. We test des.~\ref{ax:testing_strategy} in the experiments (see sec.~\ref{sec:experiments}) by comparing the reward obtained by the sampling-aleatoric and the sampling-epistemic strategies at testing time. The two latter desiderata \ref{ax:testing_state} and \ref{ax:testing_strategy} express an important trade-off between assigning high uncertainty and generalizing to new test environments. Since an agent cannot generalize to all new environment because of the No Free Lunch Theorem \cite{no-free-lunch-theorem-optimization}, an agent should assign higher uncertainty to environments where it does not generalize. We jointly test des.~\ref{ax:testing_state} and des.~\ref{ax:testing_strategy} in the experiments (see sec.~\ref{sec:experiments}) by tracking the reward and the uncertainty estimates in test environments with different perturbation strengths.
\section{Models for Uncertainty Quantification in RL}
\label{sec:models}
\looseness=-1
Model-free RL agents commonly rely on learning the expected return \smash{$Q^{\policy}(\s^{(t)}, a^{(t)})$} associated with taking action \smash{$a^{(t)}$} in state \smash{$\s^{(t)}$} and then following a policy $\policy$. It is defined by the Bellman equation:
$Q^{\policy}(\s^{(t)}, a^{(t)}) = r(\s^{(t)}, a^{(t)}) + \gamma \expectation_{T, \policy} [Q^{\policy}(\s^{(t+1)}, a^{(t+1)})]$.
Similarly, the optimal policy \smash{$\policy^*$} achieving the highest expected reward satisfies the optimal Bellman equation \cite{dynamic-programming}:
\begin{equation}
\label{eq:optimal_bellman_equation}
Q^{\policy^*}(\s^{(t)}, a^{(t)}) = r(\s^{(t)}, a^{(t)}) + \gamma \expectation_T [\max_{a^{(t+1)}} Q^{\policy^*}(\s^{(t+1)}, a^{(t+1)})]
\end{equation}
However, the exact computation of the optimal $Q$-value is often intractable for large action or state spaces. Therefore, deep RL agents like DQN \cite{dqn}, PPO \cite{ppo} and A2C \cite{a2c}
aim at approximating the optimal $Q$-value \smash{$Q^{\policy^*}(\s^{(t)}, a^{(t)})$} with a neural network \smash{$f_\theta(\s^{(t)}, a^{(t)})$} with parameter \smash{$\bm{\theta}$}. In particular, DQN enforces eq.~\ref{eq:optimal_bellman_equation} by minimizing the squared temporal difference (TD) error \smash{$\|r(\s^{(t)}, a^{(t)}) + \gamma \max_{a^{(t+1)}} f_{\bm{\theta}'}(\s^{(t+1)}, a^{(t+1)}) - f_{\bm{\theta}}(\s^{(t)}, a^{(t)})\|_2$}, where \smash{$f_{\bm{\theta}}$} is the learned prediction network and \smash{$f_{\bm{\theta}'}$} is the frozen target network regularly updated with the prediction network parameters during training. The TD error minimization is similar to SL regression with a MSE loss between the prediction \smash{$\hat{\y}\datatx = f_{\bm{\theta}}(\s^{(t)}, a^{(t)})$} and the target \smash{$\y\datatx = r(\s^{(t)}, a^{(t)}) + \gamma f_{\bm{\theta}'}(\s^{(t+1)}, a^{(t+1)})$} with the key difference that the exploration strategy select the targets that will be used during training.
\looseness=-1
Model-free Deep RL agents often show important limitations for uncertainty estimation because of their neural network architecture choice. For, instance, while DQN only outputs a single scalar representing the mean $Q$-value with no uncertainty estimates, PPO and A2C policies parameterized with standard ReLU networks would provably produce overconfident predictions for extreme input states \cite{overconfident-relu}. In this work, we focus on equipping the widely used DQN RL agent with reliable uncertainty estimates. To this end, we combine DQN with four SL architectures for uncertainty estimation (incl. MC dropout, ensemble, deep kernel learning, and evidential networks) covering a diverse range of sampling-based and sampling-free methods. These four DQN combinations allow to instantiate both aleatoric and epistemic uncertainty with minimal modifications to the training procedure. We provide a summary of the uncertainty properties of these models in Tab.~\ref{tab:summary_models}.
\begin{table*}[ht!]
\vspace{-3mm}
\caption{Summary of the uncertainty properties of the models.}
\label{tab:summary_models}
\vspace{-2mm}
\centering
\resizebox{.89\textwidth}{!}{%
\begin{tabular}{@{}lcccc@{}}
\toprule
& DropOut & Ensemble & Deep Kernel Learning & Evidential Networks \\
\midrule
Uncertainty concentration (Des.~\ref{ax:training_state}) & \xmark & \xmark & \xmark & \cmark\\
\midrule
Alea. vs epist. sampling at training time (Des.~\ref{ax:training_strategy}) & \cmark & \cmark & \xmark & \cmark\\
\midrule
OOD detection (Des.~\ref{ax:testing_state}) & \xmark & \xmark & \cmark & \cmark\\
\midrule
Alea. vs epist. sampling at testing time (Des.~\ref{ax:training_strategy}) & \cmark & \cmark & \xmark & \cmark\\
\bottomrule
\end{tabular}}
\vspace{-3mm}
\end{table*}
\looseness=-1
\textbf{MC Dropout.} DQN is combined with MC Dropout \cite{dropout} in three steps: \textbf{(1)} it samples $K$ independent set of model parameters \smash{$\{\bm{\theta}_k\}_{k=1}^K$} by dropping activations with probability $p$, \textbf{(2)} it performs $K$ forward passes \smash{$\mu_k, \sigma_k = f_{\bm{\theta}_k}(s^{(t)}, a^{(t)})$}, and \textbf{(3)} it aggregates predictions to form the mean prediction \smash{$\mu(s^{(t)}, a^{(t)}) = \frac{1}{K}\sum_{k=1}^K \mu_k$}, the aleatoric uncertainty estimate \smash{$u_\text{alea}(s^{(t)}, a^{(t)}) = \frac{1}{K}\sum_{k=1}^K \sigma_s$}, and the epistemic uncertainty estimate \smash{$u_\text{epist}(s_t, a_t) = \frac{1}{K}\sum_{k=1}^K (\mu_k - \mu(s^{(t)}, a^{(t)}))^2$}. In this case, the aleatoric distribution is Gaussian while the epistemic distribution is implicitly represented by the sampled parameters \smash{$\{\theta_k\}_{k=1}^K$}. Further, the sampling-epistemic strategy is achieved by performing one single forward pass with a single set of sampled model parameters. This is similar to the Thompson sampling strategy used by \citet{dropout}. During training, we train the neural network parameters $\theta$ by using a Gaussian negative log-likelihood loss. The combination of DQN and dropout has been shown to practically improve sample efficiency \cite{dropout}. However, dropout has multiple limitations. First, the dropout uncertainty estimates \emph{provably} do not concentrate with more observed data \cite{randomized-prior-functions}, thus potentially violating des.~\ref{ax:training_state}. Second, there is no guarantee that dropout produce meaningful uncertainty estimates for extreme input states with a finite number of samples $K$, thus potentially violating des.~\ref{ax:testing_state}. Third, dropout might be computationally expensive for large $K$ value since it would require many forward passes for uncertainty estimation.
\looseness=-1
\textbf{Ensemble.} DQN is combined with ensembles \cite{ensembles} in three steps: \textbf{(1)} it trains $K$ independent models with parameters \smash{$\{\theta_k\}_{k=1}^K$}, \textbf{(2)} it performs $K$ forward passes \smash{$\mu_k, \sigma_k = f_{\bm{\theta}_k}(s^{(t)}, a^{(t)})$}, and \textbf{(3)} it aggregates predictions to form the mean prediction \smash{$\mu(\s^{(t)}, a^{(t)}) = \frac{1}{K}\sum_{k=1}^K \mu_k$}, the aleatoric uncertainty estimate \smash{$u_\text{alea}(s^{(t)}, a^{(t)}) = \frac{1}{K}\sum_{k=1}^K \sigma_s$}, and the epistemic uncertainty estimate \smash{$u_\text{epist}(s_t, a_t) = \frac{1}{K}\sum_{k=1}^K (\mu_k - \mu(s^{(t)}, a^{(t)}))^2$}. In this case, the aleatoric distribution is Gaussian while the epistemic distribution is implicitly represented by the parameters of the $K$ networks \smash{$\{\bm{\theta}_k\}_{k=1}^K$}. Further, the sampling-epistemic strategy is achieved by performing one single forward pass with one randomly selected network. This is similar to the Thompson sampling strategy used by \citet{bootstrapped-dqn}. We train the $K$ independent neural network parameters \smash{$\theta_k$} with a Gaussian negative log-likelihood loss. However, ensemble has multiple limitations. First, while the combination of DQN with bootstrapped ensemble and prior functions has been \emph{empirically} shown to improve learning for complex tasks with sparse rewards \cite{bootstrapped-dqn, randomized-prior-functions}, there is no explicit theoretical or empirical evidence that their uncertainty estimates concentrate with more observed data. Second, there is no guarantee that ensembles produce meaningful uncertainty estimates for extreme input states with a finite number of samples $K$, thus potentially violating des.~\ref{ax:testing_state}. Third, ensemble is computationally expensive for large $K$ value since it would require many forward passes and many neural networks.
\looseness=-1
\textbf{Deep Kernel Learning.} DQN is combined with deep kernel learning \cite{due} in three steps: \textbf{(1)} it predicts one latent representation of each input state i.e. \smash{$\z^{(t)} = f_{\bm{\theta}}(\s^{(t)})$}, and \textbf{(2)} one Gaussian Process per action $a$ defined from a fixed set of $K$ learnable inducing points \smash{$\{\bm{\phi}_{a,k}\}_{k=1}^{K}$} and a predefined positive definite kernel \smash{$\kappa(\cdot, \cdot)$} predicts the mean \smash{$\mu(\s^{(t)}, a)$} and the variance \smash{$\sigma(\s^{(t)}, a)$} of a Gaussian distribution. We train the neural network parameters $\bm{\theta}$ and the inducing points \smash{$\{\bm{\phi}_{a,k}\}_{k=1}^{K}$} jointly with a variational ELBO loss similarly to \cite{due}. In this case, the epistemic distribution is Gaussian \cite{simple-baseline-uncertainty}, i.e. \smash{$u_\text{epist}(s_t, a_t) = \entropy(\DNormal(\mu(\s^{(t)}, a^{(t)}), \sigma(\s^{(t)}, a^{(t)})))$}. Indeed, we show \emph{theoretically} that epistemic uncertainty increases far from training data (see app.~\ref{app:proofs}). Thus, the combination of DQN and deep kernel learning does not suffer from arbitrary uncertainty estimates for extreme input states contrary to ReLU networks \cite{overconfident-relu}. However, one of the limitation of deep kernel learning is that it does not disentangle \emph{aleatoric} and \emph{epistemic} uncertainty. This is similar to deep kernel learning methods in SL \cite{simple-baseline-uncertainty, due, duq}.
\looseness=-1
\textbf{Evidential Networks.} The combination of DQN and the posterior networks \cite{natpn, postnet} which belong to the class of evidential networks consists in three steps: \textbf{(1)} an encoder $ f_{\bm{\theta}}$ predicts one latent representation of each input state i.e. \smash{$\z^{(t)} = f_{\bm{\theta}}(\s^{(t)})$}, \textbf{(2)} one normalizing flow density estimator \smash{$\prob(. \ensuremath{\,|\,} \bm{\omega}_{a})$} and one linear decoder \smash{$g_{\bm{\psi}_{a}}$} per action $a$ predict a Normal Inverse-Gamma distribution \smash{$\prior(\priorparam(\s^{(t)}, a), \evidence(\s^{(t)}, a))$} with parameters \smash{$\priorparam(\s^{(t)}, a) = g_{\bm{\psi}_{a}}(\z^{(t)}, a)$} and \smash{$ \evidence(\s^{(t)}, a) \propto \prob(\z\dataix \ensuremath{\,|\,} \bm{\omega}_{a})$}, and \textbf{(3)} it computes the posterior parameters $\priorparam^\text{post}(\s^{(t)}, a) = \frac{\evidence^\text{prior}\priorparam^\text{prior} + \evidence(\s^{(t)}, a)) \priorparam(\s^{(t)}, a)}{\evidence^\text{prior} + \evidence(\s^{(t)}, a))}, \evidence^\text{post}(\s^{(t)}, a)) = \evidence^\text{prior} + \evidence(\s^{(t)}, a)$ where the prior parameters are chosen to enforce high entropy for the prior distribution e.g. \smash{${\priorparam^\text{prior}=(0, 100)^T}, \evidence^\text{prior}=1$} \cite{natpn}. In this case, the epistemic distribution is a Normal Inverse-Gamma distribution and the aleatoric distribution is a Normal distribution \cite{natpn}. We train the neural network parameters $\bm{\theta}$ and $\bm{\psi}$ and the normalizing flow parameters $\bm{\omega}$ jointly with the MSE loss. The entropy of the conjugate prior distribution represents the epistemic uncertainty , i.e. \smash{$u_\text{epist}(s\datatx, a\datatx) = \entropy(\DNIG(\priorparam(\s\datatx, a\datatx), \evidence(\s\datatx, a\datatx)))$}. The entropy of the likelihood distribution represents the aleatoric uncertainty, i.e. \smash{$u_\text{alea}(s\datatx, a\datatx) = \entropy(\DNormal(\mu(\s\datatx, a\datatx), \sigma(\s\datatx, a\datatx)))$}. Indeed, it has been showed \emph{theoretically} that epistemic uncertainty increases far from training data (see app.~\ref{app:proofs}) \cite{natpn}. Thus, the combination of DQN and posterior networks does not suffer from arbitrary uncertainty estimates for extreme input states contrary to ReLU networks \cite{overconfident-relu}.
\section{Evaluation of Uncertainty Quantification in RL}
\label{sec:experiments}
\looseness=-1
In this section, we provide an extensive evaluation of uncertainty estimation for model-free RL. It compares four uncertainty estimation methods for model-free RL in three environments. First, we evaluate the uncertainty predictions at \emph{training time} to assess the uncertainty concentration (des.~\ref{ax:training_state}) and the sample efficiency of the uncertainty-guided exploration-exploitation strategy (des.~\ref{ax:training_strategy}). Second, we evaluate the uncertainty estimates at \emph{testing time} to assess the OOD detection performances (des.~\ref{ax:testing_state}) and the generalization performances of the uncertainty-guided decision strategy (des.~\ref{ax:testing_strategy}). In particular, we evaluate the trade-off between the generalization performance and the detection performance in new perturbed test environments.
\looseness=-1
\textbf{Models.} We consider the four uncertainty models MC Dropout \textbf{(DropOut)}, \textbf{Ensemble}, deep kernel learning \textbf{(DKL)} and the evidential model based on Posterior Networks \textbf{(PostNet)} combined with the DQN RL policy (see sec.~\ref{sec:models}). In this work, we focus on DQN \cite{dqn} since it is a widely used model-free RL agent which does not provide any uncertainty estimates by default. All models use the same encoder architecture and DQN hyper-parameters. We performed a grid search over all hyper-parameters. We compute the mean and standard error of the mean over 5 seeds. Further details are given in app.~\ref{app:models-details}.
\looseness=-1
\textbf{Environments.} We used three training environments \textbf{CartPole} \cite{cartpole}, \textbf{Acrobot} \cite{acrobot1, acrobot2} and \textbf{LunarLander} \cite{lunarlander1, lunarlander2} from the Open AI gym environments \cite{gym}. \citet{assessing-generalization-rl} also used similar environment to assess generalization in RL. We focus on these environments since they turn out to be already challenging settings for the uncertainty methods and the sampling strategies. Some methods and strategies are indeed already unable to achieve high performance for sample efficiency, generalization, and OOD detection. We provide further details on the environments in app.~\ref{app:environments-details}. \textit{\underline{OOD environments:}} The states, actions, and transition dynamics of the OOD environments should not be relevant to the original training environment task, thus being a reasonable failure mode. To this end, the input state is composed of Gaussian noise at every time step independently of the previous actions. \textit{\underline{Perturbed environments:}} These environments are perturbed versions of the original training environment with different perturbation strengths. We separately perturb the \emph{state} space, the \emph{action} space, and the \emph{transition} dynamics with different strengths of Gaussian or uniform noises. These perturbations follow the MDP structure of the environment as proposed by the formal framework for domain shifts presented in \cite{domain-shifts-rl}. We did not consider perturbation on the initial state only, which would be a weaker version of the state perturbations, and perturbations on the reward function which would not affect the model at testing time. Further details are given in app.~\ref{app:environments-details}.
\looseness=-1
\textbf{Training Time.} First, we compare the sample efficiency and the uncertainty predictions of the four uncertainty methods using the epsilon-greedy exploration-exploitation strategy at training time. We normalize the epistemic uncertainty in $[0, 1]$ with min-max normalization to compute the relative epistemic uncertainty. It allows us to easily compare the trend of the epistemic uncertainty of all models. We show the key results for Cartpole in fig.~\ref{fig:model-training-testing-performance-cartpole-main} and the detailed results for CartPole, Acrobot and LunarLander in fig.~\ref{fig:model-training-performance-cartpole}, \ref{fig:model-training-performance-acrobot}, \ref{fig:model-training-performance-lunarlander} in app.~\ref{app:additional-experiments}. We observe that all methods achieve similar sample efficiency. Ensemble with epsilon-greedy strategy struggles to maintain high reward on CartPole. This can be intuitively explained by the under-exploration of the epsilon-greedy strategy as also observed by \citet{randomized-prior-functions, dropout}. Further, we observe that only the epistemic uncertainty estimates of the combination of DQN and PostNet decreases during training. Thus, PostNet \emph{empirically} validates des.~\ref{ax:training_state}. In contrast, the epistemic uncertainty estimates of other methods increase or do not converge. This corroborates with the findings of \cite{randomized-prior-functions} which \emph{theoretically} shows that the uncertainty estimates of dropout and ensemble might not converge even on simple tasks.
\begin{figure}
\centering
\vspace{-5mm}
\begin{subfigure}{.5\textwidth}
\includegraphics[width=\textwidth]{resources/legend.png}
\end{subfigure}
\vspace{-5mm}
\begin{subfigure}{.245\textwidth}
\includegraphics[width=\textwidth]{resources/cartpole-training_total_reward-training-model.png}
\vspace{-5mm}
\caption{}
\label{fig:model-training-reward-cartpole}
\end{subfigure}
\begin{subfigure}{.245\textwidth}
\includegraphics[width=\textwidth]{resources/cartpole-training_epistemic_uncertainty-training-model.png}
\vspace{-5mm}
\caption{}
\label{fig:model-training-uncertainty-cartpole}
\end{subfigure}
\begin{subfigure}{.245\textwidth}
\includegraphics[width=\textwidth]{resources/CartPole-v0-mean_reward_-testing-model.png}
\vspace{-5mm}
\caption{}
\label{fig:model-testing-reward-cartpole}
\end{subfigure}
\begin{subfigure}{.245\textwidth}
\includegraphics[width=\textwidth]{resources/CartPoleOOD-v0-AUC-ROC-epistemic_-testing-model.png}
\vspace{-5mm}
\caption{}
\label{fig:model-testing-ood-cartpole}
\end{subfigure}
\vspace{-3mm}
\caption{Comparison of the training performance (\ref{fig:model-training-reward-cartpole}, \ref{fig:model-training-uncertainty-cartpole}) and testing performance (\ref{fig:model-testing-reward-cartpole}, \ref{fig:model-testing-ood-cartpole}) of the four uncertainty methods using epsilon-greedy strategies on CartPole. Ideally, an uncertainty aware-model in RL should achieve high reward with few training samples at training and testing time, a decreasing epistemic uncertainty at training time and high OOD detection scores at testing time.}
\label{fig:model-training-testing-performance-cartpole-main}
\vspace{-5mm}
\end{figure}
\looseness=-1
Second, we compare the sample and episode efficiency of the \emph{sampling-epistemic} and the \emph{sampling-aleatoric} strategies for each model during training. We show the results for Acrobot in fig.~\ref{fig:strategy-training-performance-acrobot-main}, and additional results for CartPole and LunarLander in fig.~\ref{fig:strategy-training-performance-cartpole}, \ref{fig:strategy-training-performance-lunarlander} in app.~\ref{app:additional-experiments}. We observe that all models achieve high rewards by using the sampling-epistemic strategy. In particular, we observed that Ensemble with epistemic sampling achieves more stable rewards than with epsilon-greedy which aligns with observations in \cite{bootstrapped-dqn}. Further, we observe that all models instantiating both aleatoric and epistemic uncertainty achieve significantly better sample efficiency with sampling-epistemic than sampling-aleatoric. Contrary to the sampling-epistemic strategy, the sampling-aleatoric strategy intuitively fails at visiting new under-explored states/actions, thus achieving low and unstable rewards. Hence, Drop-Out, Ensemble and PostNet \emph{empirically} validate des.~\ref{ax:training_strategy}. Thus, disentangling aleatoric and epistemic uncertainty can speed learning in a training environment. Further, the sampling-epistemic strategy requires fewer finished episodes on CartPole and LunarLander. This represents a more reliable training for these two environments since each finished episode translates into a failure and a restart of the systems (see app.~\ref{app:additional-experiments}).
\input{figures/strategy-training-performance-acrobot-main}
\looseness=-1
\textbf{Testing Time.} In this section, we save $20$ models during training to evaluate their performance at testing time. The testing performance can be viewed as the model performance after deployment. First, we evaluate the testing in-distribution (ID) reward in the training environment and the out-of-distribution (OOD) detection performance against the OOD environment composed of fully noisy states. All the methods used the same epsilon-greedy strategy at training time and the action lead to the highest predicted expected return at testing time. The OOD detection performance is measured by comparing the predicted epistemic uncertainty of the states/actions of $10$ episodes with the area under the receiver operating characteristic curve (AUC-ROC). We show the results for CartPole in fig.~\ref{fig:model-training-testing-performance-cartpole-main}, and additional results for Acrobot and LunarLander in fig.~\ref{fig:model-testing-performance-acrobot} and fig.~\ref{fig:model-testing-performance-lunarlander} in app.~\ref{app:additional-experiments}. We observe that DKL and PostNet achieve very high OOD detection scores compared to DropOut and Ensemble. These \emph{empirical} results align with the \emph{theoretical} results stating that DKL and PostNet should assign high uncertainty to states very different from states observed during training. Thus, DKL and PostNet validate des.~\ref{ax:testing_state}. In particular, DKL and PostNet can reliably equip DQN with epistemic uncertainty estimates which can be used to flag anomalous OOD states. In contrast, DropOut and Ensemble achieve poor OOD detection scores. This aligns with \citet{randomized-prior-functions, natpn} which shows on multiple experiments that the uncertainty estimates assigned to OOD inputs by DropOut and Ensemble are not significantly smaller than the uncertainty estimates assigned to inputs close to training data.
\looseness=-1
Second, we compare the testing in-distribution (ID) reward and the out-of-distribution (OOD) detection performance when models use the \emph{sampling-aleatoric} and \emph{sampling-epistemic} strategies at \emph{both} training and testing time. We show the results for the testing reward and the OOD detection scores on the LunarLander in fig.~\ref{fig:strategy-testing-performance-lunarlander}, and additional results on the CartPole and the Acrobot environments in fig.~\ref{fig:strategy-testing-performance-cartpole} and fig.~\ref{fig:strategy-testing-performance-acrobot} in app.~\ref{app:additional-experiments}. We observe that the sampling-epistemic strategy achieves significantly better rewards than the sampling-aleatoric for almost any checkpointed models during training. Thus, all models \emph{empirically} satisfy des.~\ref{ax:testing_state}. These empirical results underline the need to disentangle both aleatoric and epistemic uncertainty for high reward performance at testing time.
\input{figures/strategy-testing-performance-lunarlander}
\looseness=-1
Third, we compare the \emph{sampling-epistemic} and the \emph{sampling-aleatoric} strategies for each model at testing time. All models use the same epsilon-greedy strategy at training time. We show the key results for the testing reward and the testing epistemic uncertainty on Cartpole with perturbed states in fig.~\ref{fig:strategy-state-shift-testing-performance-cartpole}, and detailed results with other perturbations and environments in app.~\ref{app:additional-experiments}. We observe that stronger state and action perturbations deteriorate the reward performance of all models. This is reasonable since the input state or the output actions become more different from the training environment with stronger perturbations. Further, while the models were trained using the same epsilon-greedy strategy, we observe that the sampling-epistemic strategy generalizes significantly better to all types of perturbed environments than the sampling-aleatoric strategy. In particular, all models achieve high rewards with epistemic sampling on environments with perturbed transitions. Intuitively, sampling-aleatoric select actions with more inherent risk, while the sampling-epistemic select actions accounting for the knowledge accumulated by the agent in the training environment. The generalization capacity of the sampling-epistemic strategy aligns with \cite{epistemic-pomdp} which recast the problem of generalization in RL as solving an epistemic POMDP. Thus, differentiating between aleatoric and epistemic uncertainty can improve generalization. Finally, we observed that DKL and PostNet consistently assign higher epistemic uncertainty to environments with perturbed states which aligns with their theoretical guarantees on extreme input states. The most challenging perturbations are perturbed actions since none of the models provide guarantees for this perturbation type. Overall, DKL and PostNet reliably assign higher epistemic uncertainty to most of the perturbation types. Therefore, DKL and PostNet performs a good trade-off between generalization and detection of new perturbed environments.
\input{figures/strategy-state-shift-testing-perfomance-cartpole}
\section{Related Work}
In this section, we cover the related work for aleatoric and epistemic uncertainty estimation for RL. To this end, we review implicit \emph{desiderata} for aleatoric and epistemic uncertainty, RL \emph{methods} using uncertainty estimates and the existing \emph{evaluation} methodology to validate the quality of the uncertainty estimates in practice. We refer the reader to the survey \cite{review-uncertainty-dl} for an exhaustive overview on uncertainty estimation.
\underline{\textit{Desiderata:}} The notion of \emph{risk} is well studied in RL and closely connected to the notion of uncertainty. Risk-sensitive RL usually aims at reducing the number of failures at training time for safer RL \cite{risk-sensitive-rl, risk-constrained-rl-percentile, risk-sensitive-mdp, safe-rl-survey}. In particular, \cite{risk-uncertainty-deep-rl, rl-risk-sample-trade-off, epistemic-risk} discuss the trade-off between risk-sensitivity and sample efficiency at training time. Further, \cite{epistemic-pomdp} aim at improving generalization at testing time within the Bayesian RL framework. In SL, the predicted uncertainty is expected to increase further from training data \citep{provable-uncertainty, natpn, bayesian-a-bit, graph-postnet}. None of these previous works give \emph{explicit} desiderata for both \emph{aleatoric} and \emph{epistemic} \emph{uncertainty} in RL at both \emph{training} and \emph{testing} \emph{time}.
\underline{\textit{Models:}} The related work for uncertainty-aware model in RL is rich as shown in surveys on distributional and Bayesian RL \cite{bayesian-rl, distributional-rl}. Distributional RL \cite{distributional-rl, nonparametric-return-distribution, distributional-rl-prespective, iqn} aims at learning the distribution of return which generally captures the aleatoric uncertainty \cite{information-directed-exploration-deep-rl}. Bayesian RL methods includes sampling-based methods models such as on dropout \cite{dropout, uncertainty-rl-collision-avoidance} and ensembles \cite{bootstrapped-dqn, randomized-prior-functions, safe-rl-model-uncertainty, rl-active-learning, epistemic-pomdp}. These methods are often combined with bootstrapping during training. In particular, \cite{risk-uncertainty-deep-rl} proposed to decompose aleatoric and epistemic uncertainty to the cost of multiple trained networks and \cite{decomposition-uncertatinty-bayesian-dl} decompose aleatoric and epistemic uncertainty with latent variables for model-based RL. Bayesian RL also includes Gaussian processes \citep{gp-rl, rl-gp} and more specifically the deep kernel learning method \citep{deep-rl-deep-kernel-leanring} which requires storing uncertainty estimates in the experience replay buffer during training. Unlike RL, SL includes many uncertainty methods using deep kernel learning \citep{due, duq, simple-baseline-uncertainty} and evidential network \cite{postnet, natpn, graph-postnet, priornet, regression-priornet, evidential-regression, robustness-uncertainty-dirichlet}. In contrast, we look at \emph{both} sampled-based and sampled-free uncertainty methods for \emph{aleatoric} and \emph{epistemic} uncertainty estimation with \emph{minimal} modification to the training procedure of the RL agent, thus ensuring easy adaptation of new uncertainty quantification techniques from SL to RL.
\underline{\textit{Evaluation:}} \cite{bsuite-rl, testbed-rl} proposed to evaluate uncertainty in RL by focusing on joint predictive distributions instead of marginal distributions. Many works \cite{sample-efficient-ac, sample-efficient-rl-stochastic-ensemble, q-prop-sample-efficient, rl-fast-slow} used sample efficiency as evaluation method. Further, previous works proposed generalization benchmarks for RL \cite{generalization-rl-survey, assessing-generalization-rl, qyantifying-generalization-rl, procgen}. Finally, \cite{ood-dynamic-benchmark, benchmark-ood-detection-rl} have recently proposed benchmarks for OOD detection relevant to RL. In contrast, we propose a simple evaluation method which \emph{jointly} look at \emph{multiple} tasks relevant to real-world applications of uncertainty in RL. It covers epistemic uncertainty tracking and sample efficiency at training time, and generalization and OOD detection at testing time. In particular, we evaluate the trade-off between OOD generalization \cite{ood-generalization-survey} and OOD detection \cite{ood-detection-survey}.
\section{Limitations and Broader Impact}
\label{sec:limitations}
\looseness=-1
\underline{\textit{Desiderata:}.} Our desiderata, similar to \cite{graph-postnet, desiderata-ml-lifecycle, overview-interpretable-ml}, are designed to be application and model agnostic. In practice, the desiderata should be instantiated with formal definitions and could be customized depending on the application. \underline{\textit{Models:}} To validate the key contributions, similar to \cite{distributional-rl-prespective, iqn, bootstrapped-dqn}, we restrict our experiments to DQNs. However, the four uncertainty methods essentially modify the encoder architecture, it is possible to adapt them to other model-free RL methods such as PPO \cite{ppo} and A2C \cite{a2c}. \underline{\textit{Evaluation:}} Our approach focuses on a simple and task-diverse evaluation methodology for uncertainty estimation. Contrary to \cite{procgen}, we do not focus on scaling RL methods to more complex tasks in this paper. \underline{\textit{Broader impact:}} Our framework discusses the benefit of using uncertainty estimation to create robust and safe RL methods which corroborate with the Assessment List for Trustworthy AI \cite{trustworthy-ai}. Although, there is always a risk that this framework does not fully capture the real-world complexity, thus encouraging practitioners to proactively validate their models in the real-world.
\section{Conclusion}
\label{sec:conclusion}
\looseness=-1
We introduce a new framework to characterize aleatoric and epistemic uncertainty estimation in RL. It includes four explicit desiderata, four RL models inspired from SL and a practical evaluation methodology. The desiderata characterize the behavior of uncertainty estimates at both training and testing time. The models combine DQN with sampling-based and sampling-free uncertainty methods in SL without modifications of the RL agents training. We give theoretical and empirical evidence that these methods can fulfil the uncertainty desiderata. The evaluation method assesses the quality of uncertainty estimates on sample efficiency, generalization and OOD detection tasks.
\section*{Acknowledgments}
The authors would like to thank Daniel Z\"ugner for the helpful discussion and comments. The authors of this work take the full responsibilities for its content.
\section*{Appendix}
\section{Proofs}
\label{app:proofs}
In this section, we show that deep kernel learning \cite{due} and evidential models based on Posterior Networks \cite{postnet, natpn} are guaranteed to assign high epistemic uncertainty for inputs far from inputs observed during training under technical assumptions. In particular, the combination of DQN with deep kernel learning or evidential networks presented in sec.~\ref{sec:models} are guaranteed to assign high epistemic uncertainty for extreme input states. We assume that the encoder should use ReLU activations, which is common in deep learning, and that the rows of the linear transformations are independent, which is realistic for trained networks with no constant output \citep{overconfident-relu}.
\begin{lemma}
\label{lem:relu-regions}
\cite{understanding-nn-relu} Let $\{Q_l\}_l^{R}$ be the set of linear regions associated to the piecewise ReLU network $f_{\phi}(\x)$. For any $\x \in \real^D$, there exists $\delta^* \in \real^{+}$ and $l^*\in {1,..., R}$ such that $\delta \cdot \x \in Q_{l^*}$ for all $\delta > \delta^*$.
\end{lemma}
\begin{lemma}
\label{lem:asymptotic-latent-norm}
Let a (deep) encoder $f_{\phi}$ with piecewise ReLU activations. Let $f_{\phi}(\x)= V^{(l)}\x + a^{(l)}$ be the piecewise affine representation of the ReLU network $f_{\phi}$ on the finite number of affine regions $Q^{(l)}$ \citep{understanding-nn-relu}. Suppose that $V^{(l)}$ have independent rows, then for almost any $\x$ we have $|| f_{\phi}(\delta \cdot \x) || \underset{\delta \rightarrow \infty}{\rightarrow} \infty$. i.e the norm of the latent representations $\z_\delta=f_{\phi}(\delta \cdot \x)$ associated to the input $\delta \cdot \x$ goes to infinity.
\end{lemma}
\begin{proof}
We prove now lem.~\ref{lem:asymptotic-latent-norm}. Let $\x \in \real^D $ be a non-zero input and $f_{\phi}$ be a ReLU network. Lem.~\ref{lem:relu-regions} implies that there exists $\delta^* \in \real^{+}$ and $l \in \{1,..., R\}$ such that $\delta \cdot \x \in Q^{(l)}$ for all $\delta > \delta^*$. Thus, $\z_{\delta} = f_{\phi}(\delta \cdot \x) = \delta \cdot (V^{(l)} \x) + a^{(l)}$ for all $\delta > \delta^*$. Note that for $\delta\in [\delta^*, +\infty]$, $\z_{\delta}$ follows an affine half line $S_{\x} = \{\z \ensuremath{\,|\,} \z = \delta \cdot (V^{(l)} \x) + a^{(l)}, \delta > \delta^* \}$ in the latent space. Further, note that $V^{(l)}\x \neq 0$ since $\x \neq 0$ and $V^{(l)}$ has independent rows. Therefore, we have $|| \z_\delta|| \underset{\delta \rightarrow \infty}{\rightarrow} + \infty$
\end{proof}
\begin{theorem}
\label{thm:dkl}
Let a Deep Kernel Learning model parametrized with a (deep) encoder $f_{\phi}$ with piecewise ReLU activations, a set of $K$ inducing points $\{\phi_{k}\}_{k=1}^{K}$ and a RBF, Matern or Rational Quadratic kernel $\kappa(\cdot, \cdot)$ \cite{expressing-structure-kernels, gp-for-ml}. Let $f_{\phi}(\x)= V^{(l)}\x + a^{(l)}$ be the piecewise affine representation of the ReLU network $f_{\phi}$ on the finite number of affine regions $Q^{(l)}$ \citep{understanding-nn-relu}. Suppose that $V^{(l)}$ have independent rows, then for almost any $\x$ we have \smash{$\sigma(f_{\phi}(\delta \cdot \x)) \underset{\delta \rightarrow \infty}{\rightarrow} c$ where $ c = \kappa(0, 0)$}.
\end{theorem}
\begin{proof}
We prove now thm.~\ref{thm:dkl}. Lem.~\ref{lem:relu-regions} says that $||\z_\delta|| \underset{\delta \rightarrow \infty}{\rightarrow} + \infty$ where $\z_\delta=f_{\phi}(\delta \cdot \x)$. It implies that $||\z_\delta - \bm{\phi}_k|| \underset{\delta \rightarrow \infty}{\rightarrow} \infty$ for all inducing point $\bm{\phi}_k$. Thus, we obtain $\kappa(\z_\delta, \bm{\phi}_k) \underset{\delta \rightarrow \infty}{\rightarrow} 0$ where $\kappa(\cdot, \cdot)$ is the RBF, Matern or Rational Quadratic kernel \cite{expressing-structure-kernels, gp-for-ml}. Since the variance of the predictive Gaussian distribution associated with the Gaussian process is $\sigma(f_{\phi}(\delta \cdot \x)) = c - \bm{\kappa} \bm{C} \bm{\kappa}$ where $c = \kappa(f_{\phi}(\delta \cdot \x), f_{\phi}(\delta \cdot \x)) = \kappa(0, 0)$, $\bm{\kappa}_k = \kappa(\z_\delta, \bm{\phi}_{k})$ and $\bm{\kappa}_{k, k'} = \kappa(\bm{\phi}_{k}, \bm{\phi}_{k'})$. This gives the final result $\sigma(f_{\phi}(\delta \cdot \x)) \underset{\delta \rightarrow \infty}{\rightarrow} c$ where $ c = \kappa(0, 0)$.
\end{proof}
Thm.~\ref{thm:dkl} implies that deep kernel learning on a latent space parametrized with a neural network is guaranteed to predict high uncertainty corresponding to the prior uncertainty far from training data. This includes the uncertainty predicted by the GP associated to each action $a$ in the combination of DQN and deep kernel learning presented in sec.~\ref{sec:models}. The uncertainty prediction $u_\text{epist}(s_t, a_t) = \entropy(\DNormal(\mu(\s^{(t)}, a^{(t)}), \sigma(\s^{(t)}, a^{(t)})))$ becomes high for input states $s\datatx$ extremely different from the training environment i.e. $||s\datatx|| \rightarrow \infty$.
\begin{theorem}
\label{thm:natpn}
\cite{natpn} Let a Natural Posterior Network model parametrized with a (deep) encoder $f_{\phi}$ with piecewise ReLU activations, a decoder $g_{\psi}$ and the density $\prob(\z \ensuremath{\,|\,} \bm{\omega})$. Let $f_{\phi}(\x)= V^{(l)}\x + a^{(l)}$ be the piecewise affine representation of the ReLU network $f_{\phi}$ on the finite number of affine regions $Q^{(l)}$ \citep{understanding-nn-relu}. Suppose that $V^{(l)}$ have independent rows and the density function $\prob(\z \ensuremath{\,|\,} \bm{\omega})$ has bounded derivatives, then for almost any $\x$ we have \smash{$\prob(f_{\phi}(\delta \cdot \x) \ensuremath{\,|\,} \bm{\omega}) \underset{\delta \rightarrow \infty}{\rightarrow} 0$}. i.e the evidence becomes small far from training data.
\end{theorem}
The proof of thm.~\ref{thm:natpn} is given in \cite{natpn}, and relies also on lem.~\ref{lem:asymptotic-latent-norm} and the fact that a smooth density estimator should converge to $0$ far from training data. Intuitively, it implies that the epistemic associated to each possible action $a$ by the combination of DQN and posterior network becomes high for input states $s\datatx$ extremely different from the training environment i.e. $||s\datatx|| \rightarrow \infty$. In particular, prior parameter takes over in the posterior update (i.e. $\evidence^\text{post}(\s^{(t)}, a)) \rightarrow \evidence^\text{prior}$, $\priorparam^\text{post}(\s^{(t)}, a) \rightarrow \priorparam^\text{prior}$)
\section{Model Details}
\label{app:models-details}
\looseness=-1
We train all models on a single GPU (NVIDIA GTX 1080 Ti or NVIDIA GTX 2080 Ti, 11 GB memory). All models use the same core architecture. They use a $2$ layers MLP with 128 hidden units for the CartPole environment, a $2$ layers MLP with 64 hidden units for the Acrobot environment and a $3$ layers MLP with 128 hidden units for the LunarLander environment. All models are trained using $5$ random seeds with the Adam optimizer \cite{adam-optimizer}. For fair comparison, we use the same hyperparameters for the DQN architecture in all uncertainty models: the target network parameters are completely updated (i.e. $\tau=1.$) every $10$ training iterations. The epsilon-greedy strategy start with $\epsilon=1.$ and decay till $\epsilon=0.01$ after $1000$ iteration steps. The discount factor is set to $0.99$. Further, we use a batch size of $16$, a replay size of $1000$ and a maximum number of training iterations of $13000$ for Cartpole, a batch size of $64$, a replay size of $10000$ and a maximum number of training iterations of $120000$ for Acrobot, and a batch size of $128$, a replay size of $10000$ and a maximum number of training iterations of $300000$ for LunarLander. For each type of uncertainty model, we performed a grid search for the learning rate in the range $[10^{-1}, 10^{-4}]$.
\looseness=-1
Each uncertainty method has also its own hyperparameters. We show an hyperparameter study in app.~\ref{app:hyper-parameter-study} for the main hyper-parameters of each uncertainty method. For the MC dropout model, we make a grid-search over the number of samples $n \in [10, 20, 40, 80]$ and the drop probability $p \in [.1, .2, .3, .4, .5]$. In the main experiments, we use $n=80$ and $p=.2$. For the ensemble model, we make a grid-search over the number of networks $n \in [10, 20, 40, 80]$. In the main experiments, we use $n=80$. For the deep kernel learning model, we make a grid-search over the number of inducing points $n \in [10, 20, 40, 80]$, the latent dimension $H \in [16, 32, 64]$, the kernel type in RBF, RQ and Matern-$\frac{3}{2}$ Kernel, and an ELBO regularization factor in $\lambda \in [., 1.]$ . In the main experiments, we use $n=80$ inducing points, a latent dimension of $H=64$, the RQ kernel, and a regularization factor of $\lambda=.1$. Further, we observed that adding a batch normalization layer right after the encoder $f_{\bm{\theta}}$ was stabilizing the training similarly to \citet{postnet}. For the evidential network model based on posterior networks, we make a grid-search over the flow depth $d \in [8, 16, 32]$, the latent dimension $H \in [8, 16, 32]$. In the main experiments, we use a radial flow with depth $d=8$ and a latent dimension of $H=16$. Further, we observed that adding a batch normalization layer right after the encoder $f_{\bm{\theta}}$ was stabilizing the training similarly to \citet{postnet}.
\looseness=-1
We will provide the github repository with the code on the project page
\url{https://www.cs.cit.tum.de/daml/aleatoric-epistemic-uncertainty-rl/}.
To conduct the experiments, we used Pytorch \cite{pytorch} with BSD license, Pytorch Lightning \citep{pytorch-lightning} with Apache 2.0 license and Weight\&Biases \cite{wandb}. Further, we also use GPytorch for to implement the deep kernel model \cite{gpytorch}.
\section{Environment Details}
\label{app:environments-details}
\looseness=-1
We use OpenAI gym environments \cite{gym} with MIT license. We design the OOD environments such that they should not be relevant to the original training environment task, and thus being a reasonable failure mode. Further, we design a continuum of perturbed environments going from tasks very similar to the training environment to the tasks very different from the original environment. We distinguish between perturbations on the \emph{state} space, the \emph{action} space, and the \emph{transition} dynamics to follow the MDP structure of the original environment. In contrast, \cite{assessing-generalization-rl, benchmark-ood-detection-rl} mostly focus on perturbations on the environment parameters. We will provide the github repository with the code for the OOD and perturbed environment on the project page
\url{https://www.cs.cit.tum.de/daml/aleatoric-epistemic-uncertainty-rl/}.
\looseness=-1
\textbf{Cartpole \citep{cartpole}} In this environment, the goal of the agent is to maintain a pole on a cart straight up. This environment has a discrete action space with $2$ possible actions corresponding to apply the a force to the left or the right of the cart. This environment has a continuous state space with dimension $4$ corresponds to. The episode ends when the pole is more than 15 degrees from vertical, or the cart moves more than 2.4 units from the center. The reward is $+1$ at every time step that the pole stays up. The maximum length of an episode is 200 steps. For the OOD environment, the input states are drawn from a Gaussian distribution with unit variance i.e. $\s^{(\tdata), \text{pert}} \sim \DNormal(0, 1)$. For the perturbed environments with perturbation strength $\epsilon$, the action space is perturbed by randomly adding Gaussian noise to the scale of the force applied to the cart (i.e. $f^{\text{pert}} = (1. + x)f$ where $f \in \{-10, 10\}$ is default action force and $x \sim \DNormal(0, \epsilon)$ is the perturbation), the state space is perturbed by adding Gaussian noise to the observation scale (i.e. $\s^{(\tdata), \text{pert}} = (1. + x)\s\datatx$ where $x \sim \DNormal(0, \epsilon)$ is the perturbation), and the transition dynamic is perturbed by adding a uniform noise centered around the true dynamic parameters (i.e. $\nu^{\text{pert}} = (1 + x) \nu$ where $x \sim U(-\epsilon, \epsilon)$ where $\nu$ is the original environment parameters) such as the gravity, pole length ...etc.
\looseness=-1
\textbf{Acrobot \citep{acrobot1, acrobot2}} In this environment, the agent control a robot arm with two links and its goal is to move the end of the lower link up to a given height. This environment has a discrete action space with $3$ possible actions corresponding to apply a positive torque, a negative torque or nothing. This environment has a continuous state space with dimension $6$ corresponding to the $4$ joint angles and the $2$ angular velocities. The episode ends when the lower link of the robot arm is above a given height. The reward is $-1$ at every time step that the pole does not reach the expected height. The maximum length of an episode is 500 steps at most. For the OOD environment, the input states are drawn from a Gaussian distribution with unit variance (i.e. $\s^{(\tdata), \text{pert}} \sim \DNormal(0, 1)$). For the perturbed environments with perturbation strength $\epsilon$, the action space is perturbed by randomly sampling actions with probability $p=\frac{\epsilon}{2}$, the state space is perturbed by adding Gaussian noise to the observation scale (i.e. $\s^{(\tdata), \text{pert}} = (1. + x)\s\datatx$ where $x \sim \DNormal(0, \epsilon)$), and the transition dynamic is perturbed by adding a uniform noise centered around the true dynamic parameters (i.e. $\nu^{\text{pert}} = (1 + x) \nu$ where $x \sim U(-\epsilon, \epsilon)$ where $\nu$ is the original environment parameters) such as the lengths of the links, the masses of the links.
\looseness=-1
\textbf{LunarLander \citep{lunarlander1, lunarlander2}} In this environment, the agent control a space ship and its goal is to land it on the surface of the moon. This environment has a discrete action space with $4$ possible actions corresponding to apply a torque to the left, to the right, downward or nothing. This environment has a continuous state space with dimension $8$ corresponding to the space ship coordinates. The reward is correlated with fast landing in the correct area without crashes. The episode ends when the spaceship is landed or crashed. For the OOD environment, the input states are drawn from a Gaussian distribution with unit variance (i.e. $\s^{(\tdata), \text{pert}} \sim \DNormal(0, 1)$). For the perturbed environments with perturbation strength $\epsilon$, the action space is perturbed by randomly sampling actions with probability $p=\frac{\epsilon}{2}$, the state space is perturbed by adding Gaussian noise to the observation scale (i.e. $\s^{(\tdata), \text{pert}} = (1. + x)\s\datatx$ where $x \sim \DNormal(0, \epsilon)$), and the transition dynamic is perturbed by adding a uniform noise centered around the true dynamic parameters (i.e. $\nu^{\text{pert}} = (1 + x) \nu$ where $x \sim U(-\epsilon, \epsilon)$ where $\nu$ is the original environment parameters) such as the lengths of the links, the masses of the links.
\section{Metric Details - Training Time}
\label{app:training-time-metric-details}
\looseness=-1
We track the current reward, the epistemic uncertainty and the aleatoric uncertainty at every training step. The epistemic and aleatoric uncertainty are defined by the variance or the entropy of the epistemic and the aleatoric distributions (see sec.~\ref{sec:models}). The two uncertainty types are then normalized between $[0, 1]$ with min-max normalization to compute the relative epistemic and aleatoric uncertainty on the plots. The normalization enable an easier comparison of the trend of the uncertainty estimates across methods. For all these experiments, we compute the mean and the standard error of the mean across $5$ seeds for all results.
\section{Metric Details - Testing Time}
\label{app:testing-time-metric-details}
\looseness=-1
We save $20$ model checkpoints at regular interval during the whole training. We evaluate then the $20$ checkpointed models at testing time. First, we compute the in-distribution (ID) reward average over $10$ episodes on the original training environment. Second, we compute the OOD detection scores by comparing the epistemic uncertainty of the ID and the OOD environment over $10$ episodes each with the area under the receiver operating characteristic curve (AUC-ROC) and the area under the precision-recall curve (AUC-PR). Higher scores indicate better OOD detection performances. Third, we compute the averaged reward and epistemic uncertainty on the perturbed environment over $10$ episodes. For all these experiments, we compute the mean and the standard error of the mean across $5$ seeds for all results. Further, we also sampled $5$ random perturbations for each perturbation strength.
\section{Additional Experiments}
\label{app:additional-experiments}
\subsection{Training Time}
We show additional results on CartPole, Acrobot and LunarLander in fig.~\ref{fig:model-training-performance-cartpole}, fig.~\ref{fig:model-training-performance-acrobot} and fig.~\ref{fig:model-training-performance-lunarlander} to compare the performance of the uncertainty estimates of the four uncertainty methods at training time. The epistemic uncertainty estimates of PostNet decrease during training. Thus, PostNet empirically validate des.~\ref{ax:training_state}. Further, Ensemble and PostNet require a low number of finished episodes on CartPole and LuncarLander. This translates for these two envionments into a safer learning with a lower number of restart of the systems.
\input{figures/model-training-performance-cartpole}
\input{figures/model-training-performance-acrobot}
\input{figures/model-training-performance-lunarlander}
We show additional results in fig.~\ref{fig:strategy-training-performance-cartpole}, fig.~\ref{fig:strategy-training-performance-acrobot} and fig.~\ref{fig:strategy-training-performance-lunarlander} to compare the performance of the sampling-epistemic and the sampling-aleatoric strategies at training time. The sampling-epistemic strategy consistently achieve a better sample efficiency. Thus, Ensemble, DropOut and PostNet empirically satisfy des.~\ref{ax:training_strategy}. Hence, disentangling aleatoric and epistemic uncertainty can speed learning in a training environment.
\input{figures/strategy-training-performance-cartpole}
\input{figures/strategy-training-performance-acrobot}
\input{figures/strategy-training-performance-lunarlander}
\subsection{Testing Time}
We show additional results in fig.~\ref{fig:model-testing-performance-cartpole}, fig.~\ref{fig:model-testing-performance-acrobot} and fig.~\ref{fig:model-testing-performance-lunarlander} to compare the generalization and OOD detection performance of the uncertainty estimates of the four uncertainty methods at testing time. The models use the sampling-epistemic or the sampling-aleatoric strategy at both training and testing time. Further, we show other additional results for OOD detection by using the area under the precision-recall (AUC-PR) scores instead of the area under the receiver operating characteristic curve (AUC-ROC) in fig.~\ref{fig:strategy-testing-ood-auc-pr-performance-cartpole}, fig.~\ref{fig:strategy-testing-ood-auc-pr-performance-acrobot}, fig.~\ref{fig:strategy-testing-ood-auc-pr-performance-lunarlander}. We observe that DKL and PostNet achieve very high OOD detection scores in most settings compared to DropOut and Ensemble. These \emph{empirical} results align with the \emph{theoretical} results stating that DKL and PostNet should assign high uncertainty to states very different from states observed during training. Thus, DKL and PostNet validate des.~\ref{ax:testing_state}. In particular, DKL and PostNet can reliably equip DQN with epistemic uncertainty estimates which can be used to flag anomalous OOD states.
\input{figures/model-testing-performance-cartpole}
\input{figures/model-testing-performance-acrobot}
\input{figures/model-testing-performance-lunarlander}
We show additional results in fig.~\ref{fig:strategy-testing-performance-cartpole}, fig.~\ref{fig:strategy-testing-performance-acrobot} and fig.~\ref{fig:strategy-testing-performance-lunarlander} to compare the performance of the sampling-epistemic and sampling-aleatoric strategies for each uncertainty model. All models use the same epsilon-greedy strategy at training time. We observe that the sampling-epistemic strategy is consistently better than sampling-aleatoric at testing time. The higher generalization capacity of the sampling-epistemic strategy aligns with \cite{epistemic-pomdp} which recasts the problem of generalization in RL as solving an epistemic POMDP. These empirical results underline the need to disentangle both aleatoric and epistemic uncertainty for high reward performance at testing time.
\input{figures/strategy-testing-performance-cartpole}
\input{figures/strategy-testing-performance-acrobot}
We show additional results in fig.~\ref{fig:strategy-state-shift-testing-performance-cartpole}, fig.~\ref{fig:strategy-state-shift-testing-performance-acrobot}, fig.~\ref{fig:strategy-state-shift-testing-performance-lunarlander}, fig.~\ref{fig:strategy-action-shift-testing-performance-cartpole}, fig.~\ref{fig:strategy-action-shift-testing-performance-acrobot}, fig.~\ref{fig:strategy-action-shift-testing-performance-lunarlander}, fig.~\ref{fig:strategy-transition-shift-testing-performance-cartpole}, fig.~\ref{fig:strategy-transition-shift-testing-performance-acrobot}, fig.~\ref{fig:strategy-transition-shift-testing-performance-lunarlander} to compare the generalization and uncertainty performances of the sampling-epistemic and sampling-aleatoric strategies of each method on perturbed environments with state, action and transition dynamic perturbations. All methods achieve lower reward on environment with stronger perturbations. This is expected since a model cannot generalize to all new environments. The sampling-epistemic strategy achieves significantly better that the sampling-aleatoric strategy. The generalization capacity of the sampling-epistemic strategy aligns again with \cite{epistemic-pomdp}. Thus, differentiating between aleatoric and epistemic uncertainty can improve generalization. Finally, only DKL and PostNet reliably assign higher epistemic uncertainty to most of the perturbation types. Therefore, DKL and PostNet have a good trade-off between generalization and detection of new perturbed environments.
\textbf{Video:} For a better visualization, we provide supplementary videos on the project page \url{https://www.cs.cit.tum.de/daml/aleatoric-epistemic-uncertainty-rl/}. The videos show the landing performance, the reward performance, and the relative epistemic uncertainty prediction of the PostNet model in the original LunarLander environments and two environments with perturbed states with perturbation strengths equal to $0.5$ and $2.0$. On the original environment, we observe that the space ship lands correctly with lower epistemic uncertainty after landing. On the perturbed environment with strength $0.5$, we observe that the space ship avoids crashing but assigns higher epistemic uncertainty when moving further from the landing zone. Finally, on the perturbed environment with strength $2.0$, we observe that the space ship assigns significantly higher epistemic uncertainty especially when approaching the floor before the crash.
\input{figures/strategy-action-shift-testing-perfomance-cartpole}
\input{figures/strategy-transition-shift-testing-perfomance-cartpole}
\input{figures/strategy-state-shift-testing-perfomance-acrobot}
\input{figures/strategy-action-shift-testing-perfomance-acrobot}
\input{figures/strategy-transition-shift-testing-perfomance-acrobot}
\input{figures/strategy-state-shift-testing-perfomance-lunarlander}
\input{figures/strategy-action-shift-testing-perfomance-lunarlander}
\input{figures/strategy-transition-shift-testing-perfomance-lunarlander}
\input{figures/strategy-testing-ood-auc-pr-performance-cartpole}
\input{figures/strategy-testing-ood-auc-pr-performance-acrobot}
\input{figures/strategy-testing-ood-auc-pr-performance-lunarlander}
\subsection{Comparison with Vanilla DQN}
We show additional results in fig.~\ref{fig:camprison-vanilla-cartpole}, fig.~\ref{fig:camprison-vanilla-acrobot}, fig.~\ref{fig:camprison-vanilla-lunarlander} to compare the sample efficiency and the generalization capacity of the uncertainty models with the vanilla DQN. The vanilla DQN is not eqquiped by default with uncertainty estimates. Therefore, it cannot be used for uncertainty tasks like OOD detection. For the sake of comparison, all models use the epsilon-greedy strategy. We observe that the vanilla DQN achieve significantly lower sample efficiency on CartPole. Further, it achieves less stable generalization performance on LunarLander. In contrast, the four uncertainty methods achieve higher generalization performance especially when using the sampling epistemic strategy (see fig.~\ref{fig:strategy-testing-performance-cartpole}, fig.~\ref{fig:strategy-testing-performance-acrobot} and fig.~\ref{fig:strategy-testing-performance-lunarlander}). These results underline the benefit of predicting and disentangling the aleatoric and the epistemic uncertainty for better sample efficiency and generalization performance.
\input{figures/comparison-vanilla-cartpole}
\input{figures/comparison-vanilla-acrobot}
\input{figures/comparison-vanilla-lunarlander}
\subsection{Hyperparameter Selection}
\label{app:hyper-parameter-study}
In this section, we present a hyperparameter study for each uncertainty method on the CartPole environment To this end, plot the testing reward and the OOD scores when varying the most important hyper-parameters. we at testing time. We show the hyper-parameter study for dropout when varying the number of samples $n$ and the dropout probability $p$ in fig.~\ref{fig:hyperparameter-dropout-cartpole}. We observe that a higher number of samples achieves a slightly better OOD detection score. Dropout is pretty insensitive to the dropout probability. We show the hyper-parameter study for ensemble when varying the number of networks $n$ in fig.~\ref{fig:hyperparameter-ensemble-cartpole}. While a higher number of networks is supposed to give higher prediction quality \cite{ensembles}, Ensemble looks to give similar results for all number of networks. We show the hyper-parameter study for DKL when varying the number of inducing points $n$, the latent dimension $H$, the kernel type and the batch norm layer in fig.~\ref{fig:hyperparameter-dkl-cartpole}. The batch norm layer appears to improve the results similarly to \cite{postnet}. It facilitates the match between the latent positions output by the encoder and the inducing points. The other hyperparameters consistently show good performances. We show the hyperparameter study for PostNet in fig.~\ref{fig:hyperparameter-postnet-cartpole}. Again, the batch norm layer appears to improve the result stability as observed in \cite{postnet}. It facilitates the match between the latent positions output by the encoder and non-zero density regions learned by the normalizing flows. The other hyperparameters consistently show good performances.
\input{figures/hyperparameter-dropout-cartpole}
\input{figures/hyperparameter-ensemble-cartpole}
\input{figures/hyperparameter-dkl-cartpole}
\input{figures/hyperparameter-postnet-cartpole}
\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{See sec.~\ref{sec:desiderata}, sec.~\ref{sec:models} and sec.~\ref{sec:experiments}}
\item Did you describe the limitations of your work?
\answerYes{See sec.~\ref{sec:limitations}}
\item Did you discuss any potential negative societal impacts of your work?
\answerYes{See sec.~\ref{sec:limitations}}
\item Have you read the ethics review guidelines and ensured that your paper conforms to them?
\answerYes{}
\end{enumerate}
\item If you are including theoretical results...
\begin{enumerate}
\item Did you state the full set of assumptions of all theoretical results?
\answerYes{See app.~\ref{app:proofs}}
\item Did you include complete proofs of all theoretical results?
\answerYes{See app.~\ref{app:proofs}}
\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 app.~\ref{app:models-details} and app.~\ref{app:environments-details}}.
\item Did you specify all the training details (e.g., data splits, hyperparameters, how they were chosen)?
\answerYes{See app.~\ref{app:models-details} and app.~\ref{app:environments-details}}
\item Did you report error bars (e.g., with respect to the random seed after running experiments multiple times)?
\answerYes{See sec.~\ref{sec:experiments}, app.~\ref{app:metric-details} and app.~\ref{app:additional-experiments}}
\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 app.~\ref{app:models-details}.}
\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{See app.~\ref{app:models-details} and app.~\ref{app:environments-details}}
\item Did you mention the license of the assets?
\answerYes{See app.~\ref{app:models-details} and app.~\ref{app:environments-details}}
\item Did you include any new assets either in the supplemental material or as a URL?
\answerNA{}
\item Did you discuss whether and how consent was obtained from people whose data you're using/curating?
\answerNA{}
\item Did you discuss whether the data you are using/curating contains personally identifiable information or offensive content?
\answerNA{}
\end{enumerate}
\item If you used crowdsourcing or conducted research with human subjects...
\begin{enumerate}
\item Did you include the full text of instructions given to participants and screenshots, if applicable?
\answerNA{}
\item Did you describe any potential participant risks, with links to Institutional Review Board (IRB) approvals, if applicable?
\answerNA{}
\item Did you include the estimated hourly wage paid to participants and the total amount spent on participant compensation?
\answerNA{}
\end{enumerate}
\end{enumerate}
| {'timestamp': '2022-06-06T02:14:05', 'yymm': '2206', 'arxiv_id': '2206.01558', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01558'} | arxiv |
\section{Introduction}
Due to the ever-increasing amount of data available, memory has grown to become a major bottleneck, which makes many traditional graph algorithms inefficient or even inapplicable. To overcome this obstacle, inspired by the MapReduce paradigm \cite{MapReduce}, several computation frameworks for large-scale graph processing across multiple machines have been proposed.
The Massively Parallel Computation (\textsf{MPC}) model is a clean, theoretical abstraction of these frameworks and thus serves as a basis for the systematic study of memory-restricted distributed algorithms. Introduced by Karloff et al.~\cite{KSV10} and Feldman et al.~\cite{FMS+10} in 2010, it was later refined in a sequence of works and has become tremendously popular over the past decade.
\customparagraph{\textsf{MPC}\ Model}
In the \textsf{MPC}\ model, the distributed network consists of $\machines$ machines, having local memory $\memory$ each. The input is distributed across the machines and the computation proceeds in synchronous rounds. In each round, each machine performs an arbitrary \textit{local computation} and then communicates up to $\memory$ data. All messages sent and received by each machine in each round have to fit into the machine’s local space.
The main complexity measure of an algorithm is its \textit{round complexity}, that is, the number of rounds needed by the algorithm to solve the problem. Secondary complexity measures of an algorithm are its \textit{global memory} usage---i.e., the number of machines times the memory per machine required---as well as the \textit{total computation} performed by machines to run the algorithm, i.e., the (asymptotic) sum of the local computation performed by each machine.
We focus on the design of fully scalable graph algorithms in the \textit{low-memory} \textsf{MPC}\ model, where each machine has strongly sublinear memory. More precisely, an input graph $G = (V,E)$, with $n$ vertices and $m$ edges, is distributed arbitrarily across machines with local memory $\memory = O(n^\delta)$ each, for some constant $0 < \delta \le 1$, so that the global space is $\memory_{Global} = \Omega(n + m)$.
\customparagraph{Graph Algorithms and Connectivity} In this model, fundamental graph and optimization problems have recently gained a lot of attention. There is a plethora of work on the problems of connectivity, matching, maximal independent set, vertex cover, coloring, and many more (see, e.g., \cite{MPC-MIS-log2logn, MPC-MIS-loglogn, coyconnectivity2021, MPC-MIS-det-general, 8948671, doi:10.1137/1.9781611975482.99, CDP20ccb}).
One particularly important (and arguably the most central) graph problem that has received increasing attention over the past few years is the one of connectivity. This is not only a problem of independent interest, but it serves as a subroutine for many algorithms.
\begin{definition}[Connectivity Problem]
Let $G = (V, E)$ be an undirected graph. The goal is to compute a function $cc \colon V \rightarrow \mathbb{N}$ such that every vertex $u \in V$ knows $cc(u)$ and for any pair of vertices $u, v \in V$, $u$ and $v$ are connected in $G$ if and only if $cc(u) = cc(v)$.
\end{definition}
A sequence of works \cite{andoni2018parallel, 10.1145/3293611.3331596, DBLP:journals/corr/abs-1807-10727, 8948671, 10.1145/3350755.3400249, 10.1145/3465084.3467951, 8948671} on this problem culminated in a randomized algorithm by Behnezhad et al.~\cite{8948671} that finds all connected components of a graph with diameter $D$ in $O(\log D + \log \log_{\frac m n} n)$ rounds.
In a very recent breakthrough, Coy and Czumaj~\cite{coyconnectivity2021} obtained the same round complexity with a deterministic algorithm.
Their derandomization approach, however, comes at a cost of heavy local computation, which makes it impractical for large-scale applications.
\customparagraph{Deterministic Algorithms and Derandomization} While the problem of connectivity is of independent interest, it is instructive to view the above results in a broader context of deterministic algorithms and derandomization.
Notably, for almost a decade, (almost) all the research in the domain of Massively Parallel Computation has focused on the study of randomized algorithms. Only recently, a sequence of works has aimed at exploring the power of the (low-memory) \textsf{MPC}\ model restricted to deterministic algorithms \cite{BKM20, CDP20ccb, CDP20cc1, MPC-MIS-det-general, coyconnectivity2021}. They demonstrate that several graph problems can be solved deterministically with (asymptotic) complexity bounds that are comparable to those of the randomized algorithms. The main ingredients of these results are derandomization methods specifically tailored to the low-memory \textsf{MPC}\ model: they are designed to cope with the limited memory per machine while exploiting the power of \textit{local computation} and \textit{all-to-all communication} in this setting.
This quest for efficient derandomization techniques has become one of the main problems of the area. Unfortunately, current derandomization frameworks suffer from long local running time (e.g., large polynomial or even exponential in $n^\delta$). In fact, as noted in \cite{CDP20ccb}, allowing heavy local computation might provide an advantage in the context of distributed and parallel derandomization. However, especially in performance-oriented scenarios, local computation may quickly become a critical parameter. It thus emerges as a natural direction to study deterministic algorithms whose total computation matches that of their randomized counterparts.
\subsection{Our Contribution}
We address this issue by presenting the first computation-efficient deterministic algorithm for the problem of graph connectivity in the strongly sublinear memory regime of \textsf{MPC}.
\begin{theorem}[Deterministic Connectivity]\label{thm:main}
There is a strongly sublinear \textsf{MPC}\ algorithm that given a graph with diameter $D$, identifies its connected components in $O(\log D + \log \log_{\frac m n} n)$ rounds deterministically using $O(n + m)$ global space and $\tilde{O}(m)$ total computation.
\end{theorem}
The total computation of our algorithm significantly improves over the $\operatorname{\text{{\rm poly}}}(n)$-bound of Coy and Czumaj~\cite{coyconnectivity2021}, with no loss in the round complexity. In fact, our algorithm matches even the state-of-the-art randomized algorithm~\cite{8948671} in all parameters up to a polylogarithmic factor in the local running time.
While the connectivity algorithm is of independent interest, our result provides a number of other qualitative advantages. For instance, our analysis relies only on pairwise independence as opposed to the almost $O(\log n)$-wise independence of \cite{coyconnectivity2021}. Moreover, to the best of our knowledge, our result is the first that uses the framework of limited independence for derandomization without incurring a significant loss in one of the parameters (e.g., in the total computation time), and hence may be of practical interest. Furthermore, due to its simplicity, our analyses may serve as a friendly introduction to deterministic algorithms via the framework of bounded independence and, hopefully, as a stepping stone to the more systematic development of computation-efficient derandomization.
\subsection{Randomized Connectivity Algorithms in a Nutshell}\label{randomizedConnReview}
We present the intuition of the randomized connectivity algorithms by Andoni et al.~\cite{andoni2018parallel} and Behnezhad et al.~\cite{8948671}. For a broader overview of connectivity algorithms, see \Cref{history}.
\customparagraph{Vertex Contraction}
The main idea behind connectivity algorithms working in $\tilde{O}(\log D)$ rounds is to repeatedly perform \textit{vertex contractions}~\cite{andoni2018parallel}. Contracting (often also called \textit{relabeling}) a vertex $u$ to an adjacent vertex $v$ means deleting the edge $\{u,v\}$ and connecting $v$ to all the vertices adjacent to $u$.
The simplest way to implement this contraction-based approach is to first appoint a random subset of the vertices as \textit{leaders} (by letting each vertex independently with probability $\frac 1 2$ become a leader), and then to contract non-leader vertices to one of their leader neighbors (if any). This approach requires $O(\log n)$ rounds with high probability.
\customparagraph{Vertex Contraction with Levels and Budgets (Andondi et al.~\cite{andoni2018parallel})}
A crucial observation to speed up the vertex contractions---going back to the graph exponentiation approach by Lenzen and Wattenhofer~\cite{LW10}---is to let each vertex expand its neighborhood to neighbors of neighbors by adding new edges (without changing the connectivity). In fact, if every vertex reaches degree $\Omega(d)$ by expanding its neighborhood in $O(\log D)$ rounds, we can mark vertices to be a leader with probability $\approx \frac{\log n}{d}$. As a result, each non-leader vertex has a leader in its neighborhood and the number of remaining vertices is $\tilde{O}(\frac{n}{d})$.
In their algorithm, Andoni et al.~\cite{andoni2018parallel} assign a level to every vertex which has not been contracted yet.
Vertices at level $i$ have a budget of $b_i$ for expanding their neighborhood, i.e., each vertex at level $i$ can add at most $b_i$ neighbors. The initial budget $b_0$ is set to $\min(n^{\delta/2}, \sqrt{\frac{m}{n}})$ to maintain global space $O(m)$. At iteration $i$, every vertex either increases its degree to $b_i$ or finds its connected component.
As explained above, we thus can mark leader vertices with probability $\frac{\log n}{b_i}$ and perform contractions to reduce the problem size to $\tilde{O}(n/b_i)$. Hence, the budgets of remaining vertices can be updated to $b_{i+1} = b_i^{1+c}$, for a small constant $c$, while using the same global space. Overall, after $O(\log \log_{\frac m n} n)$ iterations, there will be a unique vertex left in each connected component.
\customparagraph{Random Leader Contraction (Behnezhad et al.~\cite{8948671})}
To further improve the round complexity, Behnezhad et al.~\cite{8948671} design an algorithm that applies vertex contractions and increases the budgets of vertices in an asynchronous manner, e.g., at a given time two active vertices can have different budgets. In each round, their algorithm (informally) ensures that each vertex either learns its $2$-hop neighborhood or increases its budget. We here focus on the routine that defines the budgets' increase, as this is the only step involving randomness.
Consider the subgraph induced by vertices with budget level $i$. The crucial observation is that if a vertex has $\Omega(b_i)$ many neighbors of the same level, then contracting all of them allows us to recuperate $\Omega(b_i^2)$ budget. If each vertex is elected as a leader with probability $\approx \frac{\log n}{b_i}$, and non-leader vertices contracted to an arbitrary neighboring leader, then leaders can increase their level without exceeding the total memory.
\customparagraph{Increasing Initial Budget using Matching (Behnezhad et al.~\cite{8948671})}
To allow each vertex to start with a $\operatorname{\text{{\rm poly}}} \log n$ budget, a randomized constant-round algorithm (see \cite[Algorithm 3]{8948671}) reduces the number of vertices of $G$ by a constant factor. By running it for $O(\log \log n)$ \textsf{MPC}\ rounds, the problem size decreases from $n$ to $n/\operatorname{\text{{\rm poly}}} \log n$. Intuitively, this algorithm works by contracting a constant fraction of the vertices to their lowest-ID neighbors as follows. Each vertex proposes to be contracted to its neighbor with smallest ID. A deterministic conflict resolving phase results in a graph of size $\Omega(n)$ consisting of \textit{vertex-disjoint paths}. Contracting along the edges of a constant-approximate \textit{maximum matching} in this graph with maximum degree $2$ thus allows to contract $\Omega(n)$ vertices as desired.
\subsection{Deterministic Connectivity: Comparison with the State-of-the-Art}\label{review}
We next present the main ideas behind the recent deterministic connectivity algorithm of Coy and Czumaj~\cite{coyconnectivity2021}.
Coy and Czumaj~\cite{coyconnectivity2021} identify and extract the only two sources of randomization from the algorithms of \cite{andoni2018parallel, 8948671}, namely matching and hitting set. On the one hand, as outlined in \Cref{randomizedConnReview}, a constant approximation of matching in graphs with maximum degree $2$ can be used for the initial budget increase. On the other hand, the random leader contraction can be formulated as a variant of set cover, which we refer to as hitting set with all sets of the same size (see \Cref{def:HS} for a precise definition).
As these are the only steps involving randomness (as outlined in \Cref{randomizedConnReview}), the (efficient) derandomization of these two constant-round key algorithmic primitives immediately leads to an (efficient) deterministic connectivity algorithm. In fact, their derandomization together with the $O(\log D + \log \log n)$ randomized algorithm due to Behnezhad et al.~\cite{8948671} results in the state-of-the-art deterministic connectivity algorithm in low-memory \textsf{MPC}\ \cite{coyconnectivity2021}.
Interestingly, because of the conditional lower bound framework (conditioned on the widely believed 1-vs-2-cycles conjecture for low-space \textsf{MPC}\ algorithms) due to Ghaffari et al.~\cite{GKU19} and its extension to the deterministic setting due to Czumaj et al.~\cite{CDP21lb}, the two underlying problems of matching and hitting set do not admit any \textit{component-stable}\footnote{The notion of component-stability intuitively refers to the property that the choices of any vertex over the course of the algorithm are affected only by vertices in its same connected component.} constant-round deterministic algorithm.
Hence, the authors in \cite{coyconnectivity2021} incorporate in their work derandomization techniques that are highly non-component-stable.
While their adopted derandomization framework is well-established, its efficient implementation for obtaining a deterministic connectivity algorithm on an \textsf{MPC}\ with low local space and optimal global space requires to overcome several challenges. Although the algorithm from \cite{coyconnectivity2021} achieves optimal space guarantees, the computation is suboptimal for both derandomization steps. We refine these to obtain a more efficient deterministic connectivity algorithm, as explained next.
\customparagraph{Maximum Matching}
In \cite{coyconnectivity2021}, the problem of approximating maximum matching in graphs of maximum degree at most two is solved by searching the space of a randomized process based on pairwise independent hash functions, which are specified by $(2\log n + O(1))$ random bits. As each of the $O(n^2)$ hash functions is evaluated $O(n)$ times, with each evaluation taking $\operatorname{\text{{\rm poly}}} \log n$ time, the resulting total computation is $\tilde{O}(n^3)$. We reduce the \textit{seed length}, i.e., the total number of random bits needed, to $O(\log \log n)$ and, as a result, obtain $\tilde{O}(n)$ total computation.
\customparagraph{Hitting Set}
For a hitting set instance with $n$ elements and a collection of $n$ subsets of size $b$, the algorithm from \cite{coyconnectivity2021} finds a hitting set of size $O(nb^{-1/5})$ by derandomizing a simple random sampling approach based on a $O(\log_b(n))$-wise $1/\operatorname{\text{{\rm poly}}}(n)$-approximately independent family of hash functions of size $\operatorname{\text{{\rm poly}}}(n)$. The distributed implementation of the method of conditional expectation for this process takes global space $O(nb)$ and $\operatorname{\text{{\rm poly}}}(n)$ total computation.
We provide a low-memory \textsf{MPC}\ algorithm that solves the same hitting set instance using only pairwise independent random choices with $n \cdot \operatorname{\text{{\rm poly}}}(b)$ global space and $n \cdot \operatorname{\text{{\rm poly}}}(b)$ total computation. Thus, the dependency on $n$ improves polynomially when $b \ll n$. It turns out that using this hitting set algorithm as a subroutine in our connectivity algorithm allows us to obtain an algorithm with total computation $\tilde{O}(m)$.
We also note that several other works \cite{CPS17, GK18, PY18} solve the hitting set problem deterministically in the context of graph spanners in $\mathsf{CONGEST}$\xspace\ and \textsf{CONGESTED-CLIQUE}\ using similar derandomization techniques. However, these are not straightforward to implement in the low-memory \textsf{MPC}\ model.
Finally, it is worth observing that because of the shorter seeds, the \textsf{MPC}\ implementation of both matching and hitting set algorithms is significantly simplified as we can perform a simple brute force search instead of using the method of conditional expectation.
\pagebreak[3]
\subsection{Further Related Work}\label{history}
The study of connectivity algorithms in low-memory \textsf{MPC}\ was initiated by Andoni et al.~\cite{andoni2018parallel} presenting an $O(\log D \cdot \log \log_{\frac m n} n)$ randomized algorithm, which improves upon the classic $O(\log n)$ bound derived from earlier works in the \textsf{PRAM}\ model. Concurrently, for graphs with large spectral gap $\lambda$, i.e., $\Omega(1/\operatorname{\text{{\rm poly}}} \log (n))$, the bound was improved in \cite{10.1145/3293611.3331596} developing a randomized $O(\log \log n + \log (1/\lambda))$ algorithm.
Then, a near-optimal parallel randomized algorithm that in $O(\log D + \log \log_{\frac m n} n)$ rounds determines all connected components was developed by Behnezhad et al.~\cite{8948671}.
Subsequently, Liu et al.~\cite{10.1145/3350755.3400249} extended the same result to the arbitrary \textsf{CRCW \textsf{PRAM}} model, which is less computationally powerful than \textsf{MPC}, achieving such result with good probability\footnote{with success probability at least $1 - 1/ \operatorname{\text{{\rm poly}}}((m \log n)/n)$}. Moreover, by developing a method that converts randomized \textsf{PRAM}\ algorithms to highly randomness-efficient \textsf{MPC}\ algorithms, Charikar et al.~\cite{10.1145/3465084.3467951} achieved a super-polynomial saving in the randomness used in \cite{8948671}, showing that $(\log n)^{O(\log D + \log \log_{m/n} n)}$ random bits suffice (with good probability), provided that the global space is $\Omega((n + m) \cdot n^\delta)$. The current deterministic state-of-the-art algorithm for connectivity is due to Coy and Czumaj \cite{coyconnectivity2021} who obtained a deterministic $O(\log D + \log \log_{\frac m n} n)$ algorithm with asymptotically optimal space.
Finally, let us note that the connectivity problem has been studied in other regimes as well. Lattanzi et al.~\cite{LMSV11} gave a constant-round \textsf{MPC}\ connectivity algorithm in the superlinear regime, i.e., each machine has local space $\Omega(n^{1+\delta})$.
By well-known connections between linear memory \textsf{MPC}\ and the \textsf{CONGESTED-CLIQUE}\ model, \cite{JN18} yields a $O(1)$-rounds randomized connectivity \textsf{MPC}\ algorithm with optimal global space.
Then, Nowicki \cite{Now21} showed that the same problem can be solved deterministically in $O(1)$ \textsf{MPC}\ rounds with the same memory guarantees.
On the hardness side, based on the conjectured $\Omega(\log n)$ low-memory \textsf{MPC}\ lower bound for the 1-vs-2-cycles problem, Behnezhad et al.~\cite{8948671} show an $\Omega(\log D)$ lower bound for computing connected components in general graphs with diameter $D \ge \log^{1+\Omega(1)}n$. Coy and Czumaj in \cite{coyconnectivity2021} extend the same conditional lower bound to the entire spectrum of $D$ proving that no connectivity algorithm can achieve $o(\log D)$ \textsf{MPC}\ round complexity. We note that this lower bound holds for both component-stable and non-component-stable algorithms.
\section{Preliminaries}
\subsection{Primitives in Low-Space \textsf{MPC}}
There are a number of well-known \textsf{MPC}\ primitives that will be used as black-box tools. These have been studied in the MapReduce framework and can be implemented in the \textsf{MPC}\ model with stricly sublinear space per machine and linear global space. We will use the following lemma to refer to them:
\begin{lemma}[\cite{GSZ11, G99}]\label{lem:primitives}
For any positive constant $\delta$, sorting, filtering, prefix sum, predecessor, duplicate removal, and colored summation task
\footnote{Given a sequence of $n$ pairs of numbers $\langle color_i,\, x_i \rangle, i \in [n]$, with $C = \{color_i \, | \, i\in [n]\}$, compute $S_c = \sum_{i : color_i = c} x_i$ for all $c \in C$. Note that this problem can be easily solved by a constant sequence of map, shuffle, and reduce steps with $\langle color_i,\, x_i \rangle$ as key-value pairs.}
on a sequence of $n$ tuples can be performed deterministically in MapReduce (and therefore in the \textsf{MPC}\ model) in a constant number of rounds using $\memory = n^\delta$ space per machine, $O(n)$ global space, and $\tilde{O}(n)$ total computation.
\end{lemma}
Finally, observe that these basic primitives allow us to perform all of the basic computations on graphs deterministically that we will need in a constant number of \textsf{MPC}\ rounds. This includes the tasks of computing the degree of every vertex, ensuring neighborhoods of all vertices are stored on contiguous blocks of machines, sums of values among a vertex’ neighborhood, and collecting the 2-hop neighborhoods provided that they fit in the memory of a single machine.
\subsection{Derandomization Framework}\label{sec:derandomization_framework}
In this section, we give an overview of the common derandomization techniques used in all-to-all communication models \cite{CPS17, Lub93} with a focus on deterministic algorithms in the strongly sublinear memory regime of \textsf{MPC}. A systematic introduction to the framework of limited independence can be found for example in \cite{Rag88, MR95, alon2016probabilistic, LW06, CW79, WC79}.
The first step is to obtain a \textit{randomized process} that produces good results in expectation based on a small search space (i.e., short random seed) by using random variables with some limited independence.
We will use a $k$-wise independent family of hash functions, which is defined as follows:
\begin{definition}[$k$-wise independence]
Let $N, k, \ell \in \mathbb{N}$ with $k \le N$. A family of hash functions $\mathcal{H} = \{h : [N] \rightarrow \{0, 1\}^{\ell}\}$ is $k$-wise independent if for all $I \subseteq \{1,\ldots,n\}$ with $|I| \leq k$, the random variables $X_i := h(i)$ with $i \in I$ are independent and uniformly distributed in $\{0, 1\}^\ell$ when $h$ is chosen uniformly at random from $\mathcal{H}$. If $k = 2$ then $\mathcal{H}$ is called pairwise independent. Random variables sampled from a pairwise independent family of hash functions are called pairwise independent random variables.
\end{definition}
\iffalse
Similarly to \cite{coyconnectivity2021} (Section 2 and Appendix A), we will consider a product distribution $D_{n,p}$ of $n$ identically distributed independent random variables on $\{0, 1\}$ with an arbitrary $p \in [0,1]$. Without affecting asymptotic results, we will assume $1/p = 2^\ell$ for integer $\ell$. We model $D_{n,p}$ by a family of hash functions, so that a sequence of random 0-1 variables $X_1,\ldots,X_n$ can be chosen according to $D_{n,p}$ by selecting a random hash function $h \in \mathcal{H}_\ell$ and then generating each variable $X_1,\ldots,X_n$ as $X_i = 1$ iff $h(i) = 0$, where $h(i)$ evaluates to the integer representation of its $\ell$-bit sequence. \fi The following is a well-known result about the existence and construction of such hash families:
\begin{lemma}[\cite{ABI86, CG89, EGL+98}]\label{lemma-hash}
For every $N, \ell,k \in \mathbb{N}$, there is a family of $k$-wise independent hash functions $\mathcal{H} = \{h : [N] \rightarrow \{0, 1\}^{\ell}\}$ such that choosing a uniformly random function $h$ from $\mathcal{H}$ takes at most $k(\ell + \log N) + O(1)$ random bits, and evaluating a function from $\mathcal{H}$ takes time $\operatorname{\text{{\rm poly}}}(\ell, \log N)$ time.
\end{lemma}
If there is a randomized algorithm, over the choice of a random hash function, that gives good results in expectation, one can derandomize it by finding the right choice of (random) bits. To achieve that, if the seed length is small, one can brute force it without incurring an overhead in the global space.
In previous works this was usually not possible due to a seed length depending on $n$ of $\Omega(\log n)$ bits, which results in hash families of size larger than the space $\memory$ of a single machine. Instead, they used the method of conditional expectation or probabilities. There, one divides the seed into several parts and fixes one part at a time in a way that does not decrease the conditional expectation (or probability). This can be done with global coordination. We refer the interested reader for more details of the method of conditional expectation to \cite[Section 2.5, Appendix A]{coyconnectivity2021}.
\subsection{Reducing The Seed Length via Coloring}\label{sec:coloring}
The following technique plays a central role for reducing the seed length of randomized processes solving \textit{local} graph problems. As showed in \cite{BKM20, CDP20ccb, MPC-MIS-det-general}, if the outcome of a vertex depends only on the random choices of its neighbors, then $k$-wise independence among random variables of \textit{adjacent} vertices is sufficient. Whenever this is the case, we can find a mapping from vertex IDs to shorter names (colors) such that adjacent vertices are assigned different names. Linial gave a $1$-round distributed coloring algorithm with $O(\Delta^2 \log(n))$ colors \cite{doi:10.1137/0221015}.
We here adapt a more explicit $1$-round distributed coloring algorithm with $O(\Delta^2 \log_\Delta^2(n))$ colors by Kuhn \cite{10.1145/1583991.1584032} to the \textsf{MPC}\ model, which leads to the following lemma:
\begin{lemma}\label{lm:coloring}
Let $G = (V,E)$ be a graph of maximum degree $\Delta \leq n^{\delta}$. There exists a deterministic algorithm which computes an $O(\Delta^2 \log_{\Delta}^2 n)$ coloring of $G$ in $O(1)$ \textsf{MPC}\ rounds using $O(n^\delta)$ local space, $O(n \cdot \operatorname{\text{{\rm poly}}}(\Delta))$ global space, and $\tilde{O}(n \cdot \operatorname{\text{{\rm poly}}}(\Delta))$ total computation.
\end{lemma}
\begin{proof}
We start by recalling the high-level idea and then we give an efficient \textsf{MPC}\ implementation.
We assume that each vertex in $G$ is given a unique ID between $1$ and $n$.
Let $p$ be a prime with $10\Delta \log_\Delta (n) \leq p \leq 20 \Delta \log_\Delta (n)$. It is well known that such a prime always exist.
Moreover, let $d = \lceil \log_\Delta (n) \rceil$.
There exists $p^{d+1} \geq n$ distinct polynomials of degree at most $d$ over $\mathbb{F}_p$. We denote by $f_i$ the $i$-th such polynomial.
Each color corresponds to a tuple over $\mathbb{F}_p$. Note that there are $p^2 = O(\Delta^2 \log_{\Delta}^2 n)$ such tuples.
Let $C_i = \{(x,f_i(x)) \colon x \in \mathbb{F}_p\}$.
Using $\Delta d < p$ together with the fact that a non-zero polynomial of degree $d$ can have at most $d$ zeros implies that each vertex can choose a color $c(i) \in C_i$ such that $c(i) \notin C_j$ for every neighbor $j$. Now, assigning each vertex $i$ the color $c(i)$ results in a valid coloring.
It remains to discuss the MPC implementation.
By using the basic primitives of \cref{lem:primitives} and the assumption that $\Delta \leq n^\delta$, we can assume that the machine responsible to compute the coloring of the $i$-th vertex also stores the IDs of all the neighbors of $i$. Note that a given polynomial can be evaluated in time $\operatorname{\text{{\rm poly}}}(\log n,\Delta)$.
Computing the color $c(i)$ boils down to $O(\Delta \cdot p^2) = \operatorname{\text{{\rm poly}}}(\log n,\Delta)$ polynomial evaluations. Hence, the total computation time is $\tilde{O}(n \cdot \operatorname{\text{{\rm poly}}}(\Delta))$, as desired.
\end{proof}
\section{Constant Approximation of Maximum Matching}\label{sec:matching}
The first algorithmic step for the derandomization of the connectivity algorithm from~\cite{8948671} consists of solving approximate maximum matching in graphs of maximum degree two. Coy and Czumaj proved the following theorem:
\begin{theorem}[Theorem 4.2 of \cite{coyconnectivity2021}]\label{coy-amm}
Let $G = (V, E)$ be an undirected simple graph with maximum degree $\Delta \leq 2$. One can deterministically find a matching $\matching$ of $G$ of size at least $m/8 = \Omega(m)$ in $O(1)$ \textsf{MPC}\ rounds with local space $\memory = O(n^\delta)$, and global space $\memory_{Global} = O(n)$.
\end{theorem}
By extending their algorithm with the seed reduction technique mentioned earlier, we prove the following result:
\begin{theorem}\label{thm:matching}
There exists an algorithm with the same properties as those in Theorem \ref{coy-amm} using $\tilde{O}(n)$ total computation.
\end{theorem}
We start by reviewing the main idea used in the algorithm proving Theorem \ref{coy-amm}.
\customsubparagraph{Randomized Algorithm}
The algorithm of Theorem \ref{coy-amm} is based on derandomizing the following simple random process.
Let $\{X_e \colon e \in E\}$ be a family of pairwise independent random variables with $X_e = 1$ with probability $p = 1/4$ and $X_e = 0$ otherwise.
Now, let $\matching$ be the matching that includes each edge $e$ with $X_e = 1$ and $X_{e'} = 0$ for every neighboring edge $e'$.
The expected size of this matching is:
\begin{align*}
\E[|\matching|] &= \sum_{e \in E} \Pr[e \in \matching] \ge \sum_{e \in E} \Pr[X_e = 1] - \sum_{\substack{e' \in E \setminus \{e\}\::\:\\ e' \cap e \neq \emptyset}} \Pr[X_e = 1 \cap X_{e'} = 1]\\
&\ge m \cdot (p - 2p^2) \ge \frac m 8,
\end{align*}
where the second inequality follows from pairwise independence of the random variable. Hence, they can be specified by a seed of length $2\log n + O(1)$ by Lemma~\ref{lemma-hash}. As explained in \cite{coyconnectivity2021}, this allows to use the method of conditional expectation to deterministically find a matching of size at least $m/8$ in $O(1)$ \textsf{MPC}\ rounds.
\customsubparagraph{Reducing the Seed Length}
We next show how one can further reduce the seed length to $O(\log \log n)$. The main observation is that the above analysis holds as long as for any two neighboring edges the two corresponding variables are independent. This motivates the following approach.
First, we assign to each edge $e$ a color $c(e)$ from the set $\{1,2,\ldots,C\}$ for $C = O(\log^2 n)$ by applying Lemma~\ref{lm:coloring} such that two neighboring edges get assigned a different color.
Let $\{X_c \colon c \in [C]\}$ be a family of pairwise independent random variables with $X_c = 1$ with probability $p = 1/4$ and $X_c = 0$ otherwise.
We now include each edge $e$ in $\matching$ if $X_{c(e)} = 1$ and $X_{c(e')} = 0$ for every neighboring edge $e'$. The same calculations as above shows that $\mathbb{E}[\matching] \geq \frac{m}{8}$.
\customsubparagraph{\textsf{MPC}\ Algorithm}
Now we are ready to present our deterministic \textsf{MPC}\ algorithm that proves Theorem~\ref{thm:matching}. In the following, we say that something can be efficiently computed if there exists a deterministic \textsf{MPC}\ algorithm running in $O(1)$ rounds with local space $\memory = O(n^\delta)$, global space $\memory_{Global} = O(n)$ and using $\tilde{O}(n)$ total computation.
Let $\mathcal{H} = \{h \colon [C] \mapsto \{0,1\}^2\}$ be a family of $2$-wise independent hash functions of size at most $2^{2\cdot\log C + O(1)} = \operatorname{\text{{\rm poly}}}(\log n)$ obtained using \cref{lemma-hash}. Observe that each hash function $h \in \mathcal{H}$ defines a matching $\matching(h)$ that includes each edge $e$ with $h(c(e)) = 0$ and $h(c(e')) \neq 0$ for every neighboring edge $e'$.
The analysis of the randomized algorithm above implies that choosing a hash function $h$ uniformly at random from $\mathcal{H}$ results in a matching of expected size at least $m/8$. In particular, this guarantees the existence of a hash function $h^*$ with $\matching(h^*) \geq m/8$. We efficiently compute $|\matching(h)|$ for every $h \in \mathcal{H}$ and choose one \textit{good} hash function that yields a matching of size at least $m/8$.
First, we efficiently compute the coloring $c$ using \cref{lm:coloring}. Next, we compute the approximate maximum matching in $G$ by derandomizing the sampling approach analyzed above. Since the size of our family of pairwise independent hash functions is $\operatorname{\text{{\rm poly}}} \log n$, we can store one number per hash function on every machine. Each machine $M_j$, which is responsible for some edges $\mathcal{E}_j \subseteq [E]$, can compute locally the number of edges $\matching^j(h) \subseteq E_j$ in the matching generated by $h \in \mathcal{H}$ within a single round. Then, we efficiently aggregate these numbers across all machines to compute the size of the matching $\matching(h) = \sum_j \matching^j(h)$ for every hash function $h$. The best $h^* \in \mathcal{H}$ for which $\matching(h^*) \ge \frac m 8$, breaking ties arbitrarily, yields our approximate maximum matching. Finally, let us note that the global memory occupied by the hash functions across all machines $\machines$ is $\machines \cdot |\mathcal{H}| \ll \machines \cdot O(n^\delta) = O(n)$ and the overall computation performed to evaluate each hash function for every edge is $|\mathcal{H}| \cdot \operatorname{\text{{\rm poly}}}(\log n) \cdot O(n) = \tilde{O}(n)$.
\section{Computation-Efficient Derandomization of Hitting Set}\label{sc:hs}
In this section, we give a deterministic \textsf{MPC}\ algorithm for the following hitting set variant defined in \cite{coyconnectivity2021}:
\begin{definition}[\textit{Hitting Set for Leader Election}]\label{def:HS}
Let $S_1,\ldots,S_n$ be subsets of $[n]$ with $i \in S_i$ and $|S_i| = b$, for each $i \in [n]$. The goal is to find a \textit{(small) hitting set} $\mathcal{L} \subseteq [n]$, that is, a set for which $S_i \cap \mathcal{L} \neq \emptyset$ holds for all $i \in [n]$.
\end{definition}
Coy and Czumaj~\cite{coyconnectivity2021} gave an algorithm with the same parameters as those of the random sampling approach in \cite{8948671}, except that they need large $\operatorname{\text{{\rm poly}}}(n)$ computation.
\begin{theorem}[Theorem 5.6 of \cite{coyconnectivity2021}]
\label{thm:hitting_set_coy}
Let $b$ and $n$ be integers with $\log^{10} (n) \leq b \leq n$. One can deterministically find a subset $\mathcal{L} \subseteq [n]$ that solves the Hitting Set for Leader Election problem with $|\mathcal{L}| \leq O(n (\min \{ b,\memory \} )^{-1/5})$ within a constant number of \textsf{MPC}\ rounds using local space $\memory = O(n^{\delta})$, global space $\memory_{Global} = O(nb)$, and total computation $\operatorname{\text{{\rm poly}}}(n)$.
\end{theorem}
We extend the randomized approach their algorithm relies on by using the method of alterations and reducing the amount of randomness needed to prove the following result:
\begin{theorem}\label{thm:hs}
There exists an algorithm with the same properties as those in Theorem \ref{thm:hitting_set_coy} with two differences.
The total computation reduces to $O(n\cdot \operatorname{\text{{\rm poly}}}(b))$ and the global space increases to $O(n \cdot \operatorname{\text{{\rm poly}}}(b))$.
\end{theorem}
We will show in \cref{sec:blackbox} that the algorithm from Theorem~\ref{thm:hs} together with minor changes to the parameters of the connectivity algorithm results in a deterministic connectivity \textsf{MPC}\ algorithm with near-linear total computation.
\customsubsubsection{Review of Hitting Set Algorithm of Coy and Czumaj} Consider adding each element to $\mathcal{L}$ with probability $p = b^{-1/5}$. Assuming full independence, the assumption $b \geq \log^{10}(n)$ together with a simple Chernoff Bound implies that $\mathcal{L}$ is a hitting set with high probability. The high probability bound still holds with $O(\log_b n)$-wise independence, but fails to hold with $o(\log_b n)$-wise independence. As $n$ $k$-wise independent random variables require a seed length of $\Omega(k \log n)$, using $O(\log_b n)$-wise independence would not result in a seed length of $O(\log n)$, which is necessary for an $O(1)$ \textsf{MPC}\ round derandomization based on the method of conditional expectation. To shorten the seed length, the authors of \cite{coyconnectivity2021} use so-called $k$-wise $\varepsilon$-approximately independent random variables for $k = 15 \log_b(n)$ and $\varepsilon = n^{-6}$. In particular, the starting point of their algorithm is the following theorem.
\begin{theorem}[Theorem 5.2 of \cite{coyconnectivity2021}]\label{thm:coy-start}
Let $\log^{10}(n) \leq b \leq n$, $k$ be even with $k = 15 \log_b(n) \geq 4, \varepsilon = n^{-6}$, and $p = b^{-1/5}$. Then, if $X_1,X_2, \ldots, X_n$ are $k$-wise $\varepsilon$-approximately independent random variables with $X_i = 1$ with probability $b^{-1/5}$ and $X_i = 0$ otherwise. Then each of the following $n+1$ events hold with probability at least $1 - 9n^{-3}$:
\begin{bracketenumerate}
\item $\sum_{j \in S_i} X_j > 0$ for every $1 \leq i \leq n$, and
\item $\sum_{i=1}^n X_i \leq 2nb^{-\frac{1}{5}}$.
\end{bracketenumerate}
\end{theorem}
Next, we explain our randomized approach, which bears some similarities with that of \ref{thm:coy-start}, and proceed to the reduction of its seed length and its deterministic implementation on an \textsf{MPC}\ with strongly sublinear memory.
\customsubsubsection{Pairwise Analysis}
As a first step, we show that a minor modification to their randomized hitting set algorithm results in a hitting set of expected size at most $2nb^{-1/5}$, assuming only pairwise independence. As before, each element joins $\mathcal{L}$ with probability $p = b^{-1/5}$. In expectation, $b \cdot p = b^{4/5}$ elements are sampled from each set. Using only pairwise independence and Chebyshev's inequality, this implies that a set is bad, i.e., no element is sampled from it, with probability at most $\frac{1}{b^{4/5}}$. This directly follows from the following lemma:
\begin{lemma}
Let $X_1,\ldots,X_n$ be pairwise independent random variables taking values in $[0,1]$. Let $X = X_1 + \ldots + X_n$ and $\mu = \E[X]$. Then $\Var[X] = \sum_{i=1}^n \Var[X_i] \le \mu$ and
\begin{equation*}
\Pr\left[|X - \mu| \ge \mu\right] \le \frac{\sum_{i=1}^n \Var[X_i]}{\mu^2} \le \frac{1}{\mu}.
\end{equation*}
\end{lemma}
Hence, by adding for each unhit set an arbitrary element to $\mathcal{L}$, at most $n/b^{4/5}$ additional elements are added to $\mathcal{L}$ in expectation, resulting in a hitting set of expected size at most $n(b^{-1/5} + b^{-4/5})$.
\customsubsubsection{Reducing The Seed Length}
From the pairwise analysis above, we directly get a seed length of $O(\log n)$. Next, we show how to reduce the seed length to $O(\log b)$, which allows for a simple brute-force search.
We again employ a coloring idea, which is based on the simple observation that we only require pairwise independence between elements contained in the same set.
Hence, the goal is to color the elements with $\operatorname{\text{{\rm poly}}}(b)$ colors such that all elements in a given set $S_i$ are colored with a different color.
In general, this may not be possible as there might exist elements which are contained in a lot of sets. Fortunately, a simple calculation shows that there exist at most $n/b$ elements which are contained in more than $b^2$ different sets. Hence, by directly adding these elements to $\mathcal{L}$, we can assume ``for free'' that each element is contained in at most $b^2$ sets, which we will do from now on.
We can then obtain a coloring with the desired properties by finding a proper coloring in the graph $G_{conflict}$, defined as follows.
The vertex set consists of one vertex for each of the $n$ elements. Moreover, two elements are connected by an edge if there exists a set which contains both elements.
Note that the maximum degree $\Delta_{conflict}$ of $G_{conflict}$ is upper bounded by $b^3$. This follows from our assumption that each element is contained in at most $b^2$ sets.
Therefore, we can efficiently color $G_{conflict}$ with $C = O(\Delta^2_{conflict} \log^2(n)) = O(b^6 \log^2 n)$ colors.
For each $i \in [n]$, let $c(i)$ denote the color assigned to the $i$-th element.
Note that it directly follows from the definition of $G_{conflict}$ that all elements in a given set are assigned a different color.
We are now ready to present our randomized process that produces a hitting set with the desired properties.
Let $\{X_c \colon c \in [C]\}$ be a family of pairwise independent random variables with $X_c = 1$ with probability $p = b^{-1/5}$ and $X_c = 0$ otherwise.
For simplicity, we assume that $1/p$ is a power of $2$, i.e., there exists $\ell \in \mathbb{N}$ with $2^{\ell} = b^{1/5}$.
According to \cref{lemma-hash}, we can generate these random variables with a seed of length $2(\ell + \log C) + O(1) = O(\log b)$. Now, we add each element $i$ with $X_{c(i)} = 1$ to $\mathcal{L}$. Then, for each set $S_i$ with $\sum_{j \in S_i} X_{c(j)} = 0$, we add the element $i \in S_i$ to $\mathcal{L}$.
By the analysis and discussion above, $\mathcal{L}$ is a hitting set of expected size $O(nb^{-1/5})$.
\customsubsubsection{\textsf{MPC}\ Algorithm}
It remains to discuss the \textsf{MPC}\ implementation, which will prove \cref{thm:hs}.
In the following, we say that something can be efficiently computed if there exists a deterministic \textsf{MPC}\ algorithm running in $O(1)$ rounds with local space $\space = O(n^\delta)$, global space $O(n \operatorname{\text{{\rm poly}}}(b))$, and using $O(n \operatorname{\text{{\rm poly}}}(b))$ total computation.
In the preprocessing step, we add all elements which are contained in at least $b^2$ sets to the hitting set and remove all sets which contain at least one such element from consideration.
The preprocessing step requires us to compute for each element in how many sets it is contained in.
This can be done efficiently by using the colored summation primitive.
Next, we explain how to efficiently construct the graph $G_{conflict}$.
We generate the edges of $G_{conflict}$ in two steps. First, each set $S = \{e_1,e_2,\ldots,e_b\}$ creates $\binom{b}{2}$ entries $\{\{e_i,e_j\} \colon i \neq j \in [b]\}$.
This can easily be done with $\operatorname{\text{{\rm poly}}}(b)$ global space per set and $\min(\memory,\operatorname{\text{{\rm poly}}}(b))$ local space in $O(1)$ rounds by using the primitives of Lemma \ref{lem:primitives}.
Hence, we can efficiently generate all these edges in parallel.
Afterwards, we use the duplicate removal procedure of Lemma \ref{lem:primitives} to remove duplicate edges.
As $G_{conflict}$ has maximum degree $b^3$, we can use \cref{lm:coloring} to efficiently compute a coloring of $G_{conflict}$ with $C = O(b^6 \log^2 n) = \operatorname{\text{{\rm poly}}}(b)$ colors.
As before, we denote with $c(i)$ the color assigned to the $i$-th element.
For $\ell := \log_2(b^{1/5})$, let $\mathcal{H} = \{h \colon [C] \mapsto \{0,1\}^\ell\}$ be a family of $2$-wise independent hash functions of size at most $2^{2(\ell + \log C) + O(1)} = \operatorname{\text{{\rm poly}}}(b)$ such that evaluating a function from $\mathcal{H}$ takes time $\operatorname{\text{{\rm poly}}}(\ell, \log C) = \operatorname{\text{{\rm poly}}}(\log b)$ time. \cref{lemma-hash} guarantees the existence of such a family.
For each function $h \in \mathcal{H}$, we define a hitting set $\mathcal{L}_h$ as follows.
First, each element $i$ with $h(c(i)) = 0$ is contained in $\mathcal{L}_h$. Moreover, if for a given set $S_i$ no element contained in it was added in the first step, then we add element $i$ to $\mathcal{L}_h$.
The discussion above implies that there exists at least one hash function $h \in \mathcal{H}$ with $|\mathcal{L}_h| = O(n b^{-1/5})$.
Using \cref{lem:primitives}, it is easy to see that for a single hash function $h \in \mathcal{H}$, we can efficiently compute $\mathcal{L}_h$ and its size. As $\mathcal{H}$ only contains $\operatorname{\text{{\rm poly}}}(b)$ hash functions, this implies that we can efficiently compute $\mathcal{L}_h$ for every $h \in \mathcal{H}$. After we have done this, we can output the hitting set $\mathcal{L}_{h^*}$ of smallest size. As remarked above, $\mathcal{L}_{h^*}$ has size $O(n b^{-1/5})$, which finishes the proof.
\section{Connectivity Algorithm}\label{sec:blackbox}
In this section, we discuss the necessary changes to the randomized connectivity algorithm of Behnezhad et al.~\cite{8948671} and its analysis in order to prove the main result of this paper.
The deterministic approximate matching from Section~\ref{sec:matching} is used to replace steps $5$ and $6$ of Algorithm 2 of \cite{8948671}. The same modification was already done by \cite{coyconnectivity2021} and they showed that the total number of vertices drop by a constant factor, assuming that no isolated vertex exists. Hence, by applying this modified algorithm $O(\log \log_{\frac m n} n)$ times, one can in $O(\log \log_{\frac m n} n)$ rounds ensure that $m \ge n \log^{C} n$, for a given constant $C$. All the steps of the modified deterministic algorithm can be implemented by invoking the primitives of \cref{lem:primitives} $O(1)$ times, which in particular ensures that the algorithm can be implemented with total computation $\tilde{O}(m)$. Hence, we can from now on assume that $m \ge n \log^{C} n$, for a given constant $C$.
It remains to prove that Algorithm 1 of \cite{8948671} can be implemented deterministically with the same asymptotic complexity and using $\tilde{O}(m)$ total computation, assuming $m \geq n \log^C (n)$ for a sufficiently large constant $C$. To this end, Coy and Czumaj proved the following lemma:
\begin{lemma}[Lemma 6.3 of \cite{coyconnectivity2021}]\label{lem:coy-blackbox1}
Let $S_i$ denote the set of saturated vertices at level $i$ after Step 2 of the \textsc{RelabelIntraLevel} routine in \cite{8948671}, let $L_i$ denote the set of selected leaders at level $i$ after Step 3 of the same execution of \textsc{RelabelIntraLevel}, let $\beta_i$ denote the budget of vertices at level $i$, let $b(v)$ denote the budget of vertex $v$, and let $\gamma, \varepsilon$ be arbitrary constants such that $0 < \gamma, \varepsilon < 1$. If we make the following modifications to \textsc{RelabelIntraLevel}:
\begin{itemize}
\item set $\beta_{i+1} \coloneqq \beta_i \cdot (\min\{\beta_i, n^\varepsilon\})^{\gamma/4}$,
\item replace Step 3 of \textsc{RelabelIntraLevel} with any \textsf{MPC}\ algorithm that in $O(1)$ rounds selects $O\left(\frac{|S_i|}{(\min\{\beta_i, n^\varepsilon\})^{\gamma}}\right)$ leaders for each level $i$ with high probability or deterministically, and
\item replace the budget update rule in Step 4 of \textsc{RelabelIntraLevel} with $$b(v) \coloneqq b(v)\cdot (\min\{b(v), n^\varepsilon\})^{\gamma/4},$$
\end{itemize}
then the connectivity algorithm of \cite{8948671} remains correct with the same asymptotic local and global space complexity.
\end{lemma}
We extend the above lemma to make it work with the deterministic hitting set from Section \ref{sc:hs} by proving the following slight modification of it. The main technical challenge will be to ensure that our deterministic hitting set algorithm, which adds a polynomial factor (in $b$) increase in the memory and computation required, can still be run in parallel with linear global space and total computation.
\begin{lemma}\label{lem:blackbox1}
Let $c \ge 3$ be the smallest integer such that both the global space and the total computation required by the algorithm from \cref{thm:hs} are bounded by $n \cdot b^c$, and let $\varepsilon = \delta / c$ so that $n^{c\cdot \varepsilon} \le n^{\delta}$. The same result as that of Lemma~\ref{lem:coy-blackbox1} can be achieved with the following modifications to \textsc{RelabelIntraLevel}:
\begin{itemize}
\item set $\beta_{i+1} \coloneqq \beta_i \cdot (\min\{\beta_i, n^\varepsilon\})^{\frac{\gamma}{4c}}$,
\item replace Step 3 of \textsc{RelabelIntraLevel} with any \textsf{MPC}\ algorithm that in $O(1)$ rounds selects $O\left(\frac{|S_i|}{(\min\{\beta_i, n^\varepsilon\})^{\gamma}}\right)$ leaders for each level $i$ with high probability or deterministically using at most $n \beta_i^c$ global space and total computation, and
\item replace the budget update rule in Step 4 of \textsc{RelabelIntraLevel} with $$b(v) \coloneqq b(v)\cdot (\min\{b(v), n^\varepsilon\})^{\frac{\gamma}{4c}},$$
\end{itemize}
and by replacing the initial budget $\left(\frac{m}{n}\right)^{1/2}$ assigned to each vertex with $\left(\frac{m}{n}\right)^{1/2c}$ in Algorithm 1 of \cite{8948671}. Then, the connectivity algorithm of \cite{8948671} remains correct with the same asymptotic local and global space complexity. Moreover, the resulting total computation is $O(m)$.
\end{lemma}
\begin{proof}
We need to show that all claims and lemmas involving the modified steps of Algorithm 1 of \cite{8948671} do not affect its correctness nor its bounds on local and global memory. As in \cite{coyconnectivity2021}, we need to prove the following three key properties:
\begin{bracketenumerate}
\item for any vertex $v$, the value of $\ell(v)$ never exceeds $O(\log \log_{m/n} n)$ (cf. \cite[Lemma 15]{8948671}),
\item the global space used is $O(\memory_{Global})$ (cf. \cite[Lemma 17]{8948671}),
\item the sum of the squares of the budgets does not exceed $O(\memory_{Global})$ (cf. \cite[Lemma 21]{8948671}).
\end{bracketenumerate}
\begin{bracketenumerate}
\item Recall that the budget of each vertex is increased as $\beta_{i+1} \coloneqq \beta_i \cdot (\min\{\beta_i, n^\varepsilon\})^{\frac{\gamma}{4c}}$ and that $\beta_0 = \left(\frac{m}{n}\right)^{1/2c}$. Since the budget of any vertex cannot exceed $n$, we have that there are at most $O(\log \log_{m/n} n)$ levels as required.
\item Let $n_i$ denote the number of vertices which \textit{ever} reach level $i$ over the course of the algorithm. In the proof of Lemma 17 \cite{8948671}, it is shown that the total sum of the budget increases over the course of the algorithm is $O(m)$, namely
\begin{equation*}
\sum_{i=1}^L \beta_i n_i = O(m).
\end{equation*}
We extend this claim and prove that the total sum of the global space used by all hitting set instances over all iterations of the algorithm is bounded by $O(m)$, that is
\begin{equation*}
\sum_{i=1}^L \beta_i^c \cdot n_i = O(m).
\end{equation*}
Analogously to \cite{coyconnectivity2021}, we first show that $\beta_{i+1}^c \cdot n_{i+1} \le \beta_{i}^c \cdot n_{i}$. We have that the number of vertices at level $i$ removed from the graph (i.e., not marked as a leader) per vertex marked as leader is at least:
\begin{equation*}
\frac{|S_i \setminus L_i|}{|L_i|} = \frac{|S_i| - |L_i|}{|L_i|} = \Omega\left((\min\{\beta_i,n^\varepsilon\})^\gamma\right) \gg (\min\{\beta_i,n^\varepsilon\})^{\gamma/2}.
\end{equation*}
It then follows that
\begin{align*}
\beta_{i+1}^c \cdot n_{i+1} &= \left(\beta_i \cdot (\min\{\beta_i, n^\varepsilon\})^{\frac{\gamma}{4c}}\right)^c n_{i+1} \\ &< \left(\beta_i^c \cdot (\min\{\beta_i, n^\varepsilon\})^{\frac{\gamma}{4}}\right)\left(n_i (\min\{\beta_i,n^\varepsilon\})^{-\gamma/2}\right) \\ &\le \beta_{i}^c \cdot n_{i}.
\end{align*}
Using the fact that the maximum possible level for a vertex is $L = O(\log \log n)$, we obtain
\begin{equation*}
\sum_{i=1}^{L} \beta_i^c \cdot n_i \le L\cdot (\beta_0^c \cdot n_0) \le O(\log \log n) \cdot \left(\frac m n\right)^{\frac{1}{2}} \cdot n,
\end{equation*}
where the last inequality comes from the fact that $\beta_0 = \left(\frac{m}{n}\right)^{\frac{1}{2c}}$. Note that we can assume that $m \geq n \log^{20c} (n)$ and therefore each vertex has an initial budget of $\beta_0 = (m/n)^{1/2c} \ge \log^{10}(n) \gg O(\log \log n)$, as required by \cref{thm:hs}. This yields
\begin{align*}
O(\log \log n) \cdot \left(\frac m n\right)^{\frac{1}{2}} \cdot n \ll \left(\frac m n\right)^{\frac{1}{2}} \cdot \left(\frac m n\right)^{\frac{1}{2}} \cdot n = O(m).
\end{align*}
\item Follows by the same line of reasoning as in property (2).
\end{bracketenumerate}
By the choice of $c$, repeating the same calculations as in property (b) proves that the total computation required by running our deterministic hitting set algorithm over all instances in each iteration of the algorithm does not exceed $O(m)$. Moreover, Lemma \ref{lem:primitives} implies that all the other steps of the algorithm can be implemented with total computation $\tilde{O}(m)$.
\end{proof}
We are now ready to prove our main result.
\begin{proof}[Proof of \cref{thm:main}]
We apply \cref{lem:blackbox1} using our Hitting Set for Leader Election algorithm from \cref{thm:hs} setting $\gamma = \frac 1 5$ (Note that $m \geq n \log^C(n)$ for a sufficiently large constant $C$ implies $\beta_0 \geq \log^{10}(n)$). Then, it follows directly from Lemma 6.4 of \cite{coyconnectivity2021} combined with \cref{lem:blackbox1} that copies of our hitting set algorithms can be run in parallel, for each possible level and in a constant number of rounds within optimal global space and $\tilde{O}(m)$ total computation. Thus, we proved that all relevant aspects of the proof of correctness have been adjusted in comparison to \cite{coyconnectivity2021, 8948671}. Finally, as noted in \cite{coyconnectivity2021}, our extension of Lemma 15 in \cite{8948671} proves that the number of iterations remains asymptotically the same and that the deterministic algorithms replacing the $O(1)$-round random sampling approach take asymptotically the same number of rounds. Thus, we conclude that the round complexity is not affected.
\end{proof}
\subsection{#1}}
\input{commands.tex}
\renewcommand{\paragraph}[1]{\vspace{0.15cm}\noindent {\bf #1}:}
\usepackage{setspace}
\renewcommand{\baselinestretch}{1}
\usepackage{mathtools}
\DeclarePairedDelimiter{\@ifstar{\oldabs}{\oldabs*}}{\lvert}{\rvert}
\makeatletter
\let\oldabs\@ifstar{\oldabs}{\oldabs*}
\def\@ifstar{\oldabs}{\oldabs*}{\@ifstar{\oldabs}{\oldabs*}}
\makeatother
\newcommand{\separate}[1]{\clearpage #1\clearpage}
\newcommand{full}{full}
\ifthenelse{\equal{full}{full}}{
\newcommand{\fullOnly}[1]{#1}
\newcommand{\shortOnly}[1]{}
\newcommand{\footnotesize}{\small}
}{
\renewcommand{\baselinestretch}{1.00}
\newcommand{\fullOnly}[1]{}
\newcommand{\IncludePictures}[1]{}
\newcommand{\footnotesize}{\footnotesize}
}
\begin{document}
\date{}
\title{\textbf{Improved Deterministic Connectivity\\in Massively Parallel Computation}}
\author{
Manuela Fischer \\
\small{ETH Zurich}\\
\small{\texttt{[email protected]}}
\and
Jeff Giliberti \\
\small{ETH Zurich}\\
\small{\texttt{[email protected]}}
\and
Christoph Grunau \\
\small{ETH Zurich}\\
\small{\texttt{[email protected]}}
}
\date{}
\maketitle
\setcounter{page}{0}
\thispagestyle{empty}
\begin{abstract}
\input{0-abstract}
\end{abstract}
\newpage
\input{1-intro}
\input{2-preliminaries}
\input{3-matching}
\input{4-hittingset}
\input{5-connectivity}
\bibliographystyle{alpha}
| {'timestamp': '2022-06-06T02:14:33', 'yymm': '2206', 'arxiv_id': '2206.01568', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01568'} | arxiv |
\subsubsection*{References}}
\newcommand{\mathop{\mathrm{arg~max}}\limits}{\mathop{\mathrm{arg~max}}\limits}
\newcommand{\mathop{\mathrm{arg~min}}\limits}{\mathop{\mathrm{arg~min}}\limits}
\newtheorem{assumption}{Assumption}
\newtheorem{prop}{Proposition}
\newtheorem{dfn}{Definition}
\newtheorem{thm}{Theorem}
\newtheorem{lmm}{Lemma}
\newtheorem{col}{Corollary}
\newtheorem{rmk}{Remark}
\usepackage[acronym,nomain]{glossaries}
\usepackage[acronym,nomain]{glossaries}
\setlength{\glsdescwidth}{20cm}
\usepackage{authblk}
\newglossary[slg]{symbolslist}{syi}{syg}{Symbolslist}
\makeglossaries
\newcommand{\vspace*{-1ex} \noindent {\it Proof Sketch: }}{\vspace*{-1ex} \noindent {\it Proof Sketch: }}
\makeatletter
\newcommand{\figcaption}[1]{\def\@captype{figure}\caption{#1}}
\newcommand{\tblcaption}[1]{\def\@captype{table}\caption{#1}}
\makeatother
\title{Excess risk analysis for epistemic uncertainty with application to variational inference}
\author[1]{\href{mailto:Futoshi Futami <[email protected]>?Subject=Archiv paper}{Futoshi Futami\thanks{[email protected]}}{}}
\author[1]{Tomoharu Iwata}
\author[1]{Naonori Ueda}
\author[2]{Issei Sato}
\author[2]{Masashi Sugiyama}
\affil[1]{%
Communication Science Laboratories\\
NTT\\
Kyoto, Japan
}
\affil[2]{%
The University of Tokyo\\
Tokyo, Japan
}
\begin{document}
\maketitle
\begin{abstract}
We analyze the epistemic uncertainty (EU) of supervised learning in Bayesian inference by focusing on the excess risk. Existing analysis is limited to the Bayesian setting, which assumes a correct model and exact Bayesian posterior distribution. Thus we cannot apply the existing theory to modern Bayesian algorithms, such as variational inference. To address this, we present a novel EU analysis in the frequentist setting, where data is generated from an unknown distribution. We show a relation between the generalization ability and the widely used EU measurements, such as the variance and entropy of the predictive distribution. Then we show their convergence behaviors theoretically. Finally, we propose new variational inference that directly controls the prediction and EU evaluation performances based on the PAC-Bayesian theory. Numerical experiments show that our algorithm significantly improves the EU evaluation over the existing methods.
\end{abstract}
\section{Introduction}\label{ch:intro}
\vspace{-2mm}
Understanding behavior of a machine learning algorithm in a systematic way is gaining importance in order to provide transparency to non-experts \cite{bhatt2021uncertainty}. For example, in regression tasks, the fitting performance for the test data and associated error bars are needed to capture the prediction behavior. The fitting performance is known as the generalization ability and has been extensively studied theoretically and numerically \cite{10.5555/2371238}. Conversely, the error bars are known as the ``uncertainty'' and are the subject of recent attention \cite{hullermeier2021aleatoric,gawlikowski2022survey}. Uncertainty represents a lack of information and is said to be caused by two types of factors \cite{bhatt2021uncertainty}: 1) Aleatoric uncertainty (AU), which is caused by noise in the data itself, and 2) Epistemic uncertainty (EU), which is caused by a lack of training data. In particular, since the EU can tell us where in the input space is yet to be learned, it is used in various applications, such as dataset shift \cite{NEURIPS2019_8558cb40}, adversarial data detection \cite{NEURIPS2018_586f9b40}, active learning \cite{houlsby2011bayesian}, Bayesian optimization \cite{hernandez2014predictive}, and reinforcement learning \cite{janz2019successor}, integrated with deep learning methods.
Mathematically, AU is defined as the Bayes risk, which expresses the fundamental difficulty of the learning problem \cite{depeweg2018decomposition,jain2021deup,xu2020continuity}. As for EU, Bayesian inference was shown to be useful in many applications because the posterior distribution updated from the prior distribution can represent a lack of data \cite{hullermeier2021aleatoric}. In practice, measurements such as the entropy, variance of the posterior predictive distribution, and associated conditional mutual information were shown to be useful in many applications \cite{kendall2017uncertainties,depeweg2018decomposition}. Unlike AU, those measurements depend on the size of training data and algorithms. Thus, analysis depending on them are required, similar to generalization ability.
However, there has been limited study in that direction. Traditional EU analysis has focused on the properties of the exact Bayesian posterior and predictive distributions \cite{fiedler2021practical,lederer2019posterior} and large sample behaviors \cite{54897}. Since the modern Bayesian algorithms, such as the variational inference (VI) \cite{depeweg2018decomposition} or PAC-Bayesian algorithms \cite{alquier2021user}, focus on the problem's loss function and derive approximate posterior distributions, such traditional EU analysis is difficult to apply.
Recently, the analysis focusing on the loss function to define the EU in supervised learning has been proposed \cite{xu2020minimum,jain2021deup}. The EU was defined as the excess risk obtained by subtracting the Bayes risk corresponding to the AU from the total risk. Thus, the excess risk implies the loss due to insufficient data when the model is well specified. The analysis of the EU depending on the size of training data was then provided. Although the existing work successfully defines the EU beyond the distribution properties, the following limitation still exists. Namely, they assume that the data generating mechanism follows the ``Bayesian setting,'' where the training data follows the marginal distribution of the model and the test data follows the posterior predictive distribution. As described in Section~\ref{sec:Background}, this means that the data generating mechanism is known, and the correct model and exact posterior distribution are available. The correct model is not necessarily a realistic assumption and the assumption about the exact Bayesian posterior prevents us from developing an algorithm-dependent analysis which is especially required for understanding the EU in the modern Bayesian algorithms.
When considering the generalization ability, the ``frequentist setting'' has been widely used \cite{alquier2021user}, where training and test data are generated independent identically distributed (i.i.d.)~from an unknown distribution. Under this setting, the PAC-Bayesian analysis showed great success in providing the prediction performance guarantee \cite{alquier2021user} for modern Bayesian algorithms. Thus, it would also be promising to theoretically analyze the EU in the frequentist setting using the excess risk. However, as shown in Sec.~\ref{sec:Background}, when directly considering the excess risk on the frequentist setting, it is impossible to evaluate the excess risk conditioned on the input data.
Moreover, the relations between the excess risk and the widely used EU measurements are unclear. This makes EU analysis highly challenging in the frequentist setting. Because of this difficulty, to the best of our knowledge, no research about the excess risk for the EU exists in the frequentist setting.
In this paper, we propose a new theoretical analysis for EU that addresses the above limitations of these existing settings. The idea of our analysis is to combine the frequentist and Bayesian settings appropriately. Our contributions are as follows.
i) In the frequentist setting, we show novel relations among the excess risk and widely used measurements for the EU, and the generalization ability. Our analysis is based on an approximation that the test data comes from a predictive distribution similar to the Bayesian setting (Eq.\eqref{generating2}). Under this approximation, we propose computing an ``approximate excess risk'' (Eq.\eqref{excss_bayes}). We show that the approximate excess risk is equal to widely used measurements for the EU when using the log loss and squared loss. We also characterize the convergence behavior of the approximate excess risk theoretically using the PAC-Bayesian theory (Theorem~\ref{thm_square} and \ref{thm_freq_excess_risk}).
ii) Based on the theoretical analysis, we show a new interpretation of the existing VI that clarifies how the EU is regularized (Eqs.\eqref{gp} and \eqref{eq_mutual}). Then we propose a novel algorithm that directly controls the prediction and the EU estimation performance simultaneously based on the PAC-Bayesian theory (Eq.\eqref{proposal}). Numerical experiments suggest that our algorithm significantly improves EU evaluation over the existing VI.
\vspace{-2mm}
\section{Background of the Bayesian and PAC-Bayesian frequentist settings}\label{sec:Background}
\vspace{-2mm}
In this section, we review the Bayesian and frequentist settings and excess risk analysis. Capital letters such as $X$ represent random variables, while lowercase letters such as $x$ represent deterministic values.
We consider a supervised setting and denote input-output pairs by $Z=(X,Y)\in\mathcal{Z}:=\mathcal{X}\times\mathcal{Y}$. Learners can access $N$ training data, $Z^N:=(Z_1,\dots,Z_N)$ with $Z_n:=(X_n,Y_n)$, which are generated following some mechanism. We define $\mathcal{A}$ as an action space and define the loss function $l:\mathcal{Y}\times \mathcal{A}\to\mathbb{R}$. The loss of action $a\in\mathcal{A}$ and target variable $y$ is written as $l(y,a)$; for example, the log loss $l(y,q)=-\ln q(y)$, where $q$ is the probability density of $Y$ and $\mathcal{A}$ is the set of all probability densities on $Y$. The squared loss is given as $l(y, a)=|y-a|^2$, where $\mathcal{Y}=\mathcal{A}=\mathbb{R}$
\vspace{-2mm}
\subsection{The Bayesian setting and excess risk}\label{sec:Bayes_SBackground}
\vspace{-2mm}
We introduce the Bayesian setting, where we consider a generative model for the data $(Y,X)\sim P(Y|X,\theta)P(X)$, where $\theta\in\Theta\subset\mathbb{R}^d$ is a model parameter. We assume that the input is independent of the parameter $\theta$. We introduce a prior distribution $P(\theta)$ over $\theta$. The key idea of the Bayesian setting is that we assume test and training data is conditionally i.i.d.~as
\begin{align}\label{generating}
P(\theta,Z^N,Z):=P(\theta)\prod_{n=1}^{N}P(Y_n|X_n,\theta)P(X_n)P(Y|X,\theta)P(X).
\end{align}
Since this joint distribution is also expressed as $P(\theta, Z^N, Z)=P(Z^N)P(\theta|Z^N)P(Z|\theta)$, the Bayesian setting indicates that we assume the training data follows the marginal distribution of the model $P(Z^N)$ and test data follows $P(Y|X, \theta)$ under posterior distribution $P(\theta|Z^N)$. Thus, under the Bayesian setting, we assume that we know the true data generating mechanism.
Our goal is to infer a decision rule $\psi:\mathcal{Z}^N\times \mathcal{X}\to \mathcal{A}$ that minimizes the expected loss $\mathbb{E}[l(Y,\psi(X,Z^N))]$ among all decision rules. Following the previous work \cite{xu2020minimum}, we define the infimum of the expected loss as the Bayesian minimum risk:
\begin{align}\label{bayesian_risk}
R^l(Y|X,Z^N):=\inf_{\psi:\mathcal{Z}^N\times \mathcal{X}\to \mathcal{A}}\mathbb{E}[l(Y,\psi(X,Z^N))].
\end{align}
Next, we define a fundamental limit of learning as $\phi:\Theta\times\mathcal{X}\to\mathcal{A}$, which takes the true parameter $\theta$ instead of the training data $Z^N$:
\begin{align}\label{minimum}
\scalebox{0.98}{$\displaystyle R^l(Y|X,\theta):=\inf_{\phi:\Theta\times\mathcal{X}\to\mathcal{A}}\mathbb{E}[l(Y,\phi(\theta,X))]$}.
\end{align}
We cannot improve this risk by increasing the number of training data. Thus, this corresponds to AU. Here we introduce some examples of $R^l(Y|X,\theta)$. For the log loss, it corresponds to the conditional entropy $R^{\mathrm{log}}(Y|X,\theta)=\mathbb{E}H(Y|X,\theta)$ and for the squared loss, it is the conditional variance, $R^{(2)}(Y|X,\theta)=\mathrm{Var}(Y-\mathbb{E}[Y|X,\theta])^2$
Finally, we define the difference between the Bayesian minimum risk and the fundamental limit of learning as the minimum excess risk (MER):
\begin{align}
\mathrm{MER}^l(Y|X,Z^N):=R^l(Y|X,Z^N)- R^l(Y|X,\theta).
\end{align}
This corresponds to EU since this is the difference between the total risk and the fundamental limit of learning \cite{xu2020minimum,hafez2021rate}. Note that the EU is defined based on the loss function, which we solve. Since we know the data generating distribution as Eq.\eqref{generating}, we can analyze $\mathrm{MER}^l$ directly. \cite{xu2020minimum} showed that when the log-loss is used, $\mathrm{MER}^l(Y|X,Z^N)=I(\theta;Y|X,Z^N)$ holds, where $I(\theta;Y|X,Z^N)$ is the conditional mutual information.
Other than the log loss, if the loss function satisfies the $\sigma^2$ sub-Gaussian property conditioned on $(X,Z^N)=(x,z^N)$, it has been shown that $\mathrm{MER}^l(Y|X,Z^N)\leq\sqrt{2\sigma^2 I(\theta;Y|X,Z^N)}$ holds \cite{xu2020minimum}.
In many practical settings $I(\theta;Y|X,Z^N)$ is upper-bounded by $\mathcal{O}(\ln N/N)$ and thus, the excess risk converges to 0 as, $\mathcal{O}(\ln N/N)$ for the log loss and $\mathcal{O}(\sqrt{\ln N/N})$ for the sub-Gaussian loss functions. See Appendix~\ref{app_compare} for more details.
\vspace{-1mm}
\subsection{The PAC-Bayesian frequentist setting and excess risk}\label{sec_freqe}
\vspace{-1mm}
In the frequentist setting, we assume that all the data are unconditionally i.i.d.~from some unknown data-generating distribution $\nu(Z)=\nu(Y|X)\nu(X)$. We access the training dataset $Z^N\sim \nu(Z)^{N}$ and introduce a predictor $f_\theta:\mathcal{X}\to\mathcal{A}$, which is parameterized by $\theta\in\Theta\subset\mathbb{R}^d$. The PAC-Bayesian theory \cite{alquier2021user,germain2016pac} provides us a guarantee of the prediction performance by focusing on the average of the loss with respect to the posterior distribution $Q$ over $f$. Here we put on a prior $P(\theta)$ and consider the posterior $Q(\theta|Z^N)$.
The PAC-Bayesian theory provides a PAC guarantee for the generalization of test data as $R^l(Y|X,Z^N)=\mathbb{E}_{\nu(Z)^NQ(\theta|Z^N)\nu(Y|X)\nu(X)}l(Y,f_\theta(X))$ and the training error $r^l(Z^N)=\mathbb{E}_{\nu(Z)^NQ(\theta|Z^N)}\frac{1}{N}\sum_{n=1}^N l(Y_n,f_\theta(X_n))$.
Then a typical PAC-Bayesian error bound takes the form
\begin{align}
R^l(Y|X,Z^N)\leq r^l(Z^N)+\mathrm{Gen}^l(Z^N).
\end{align}
The last term $\mathrm{Gen}^l(Z^N)$ is called the generalization error. Under suitable assumptions \cite{alquier2021user}, $\mathrm{Gen}^l(Z^N)$ is upper-bounded by $\mathcal{O}(1/N^\alpha)$ for some $\alpha\in(1/2,1]$. Usually it depends on the complexity of the predictors such as the Kullback-Leibler (KL) divergence $\mathrm{KL}(Q(\theta|Z^N)|P(\theta))$ or mutual information $I(\theta:Z^N)$. It has been shown that under additional moderate assumptions, we can derive the following bound from the PAC-Bayesian generalization bound \cite{alquier2021user}:
\begin{align}\label{base_PAC}
R^l(Y|X,Z^N,\theta^*):=R^l(Y|X,Z^N)-R^l(Y|X,\theta^*)\leq C_1\left(\frac{\ln N}{N^\alpha}\right),
\end{align}
where $\theta^*=\mathrm{argmin}_\theta \mathbb{E}_{\nu(Y|X)\nu(X)}l(Y,f_\theta(X))$.
The constant $C_1$ depends only on the problem setup. We aim to analyze the EU, so we do not furthur discuss the details of the PAC-Bayesian bound. See \cite{alquier2021user} and Appendix~\ref{app_prelimi_pac} for the explicit conditions.
Next, we introduce commonly used EU measurements in modern Bayesian algorithms, including variational inference (VI). For the log loss $l(y,f_\theta(y|x))=-\ln p(y|x,\theta)$ conditioned on $(X,Z^N)=(x,z^N)$, the mutual information has been widely used for uncertainty estimation \cite{depeweg2018decomposition}:
\begin{align}\label{freq_mutual_information}
I_{\nu}(\theta;Y|x,z^N)
&=\mathbb{E}_{Q(\theta|z^N)}\mathbb{E}_{p(Y|x,\theta)}\left[-\ln\mathbb{E}_{Q(\theta|z^{N})}p(Y|x,\theta)+\ln p(Y|x,\theta)\right]\nonumber \\
&=H(p(Y|x,z^N))-E_{Q(\theta|z^{N})}H(p(Y|x,\theta)),
\end{align}
where $H(p(Y|x,z^N))$ is the entropy of the predictive distribution and $E_{Q}H(p(Y|x,\theta))$ is the conditional entropy. This has also been used in Bayesian experimental design \cite{foster2019variational} or uncertainty estimation \cite{depeweg2018decomposition}. Note that this is slightly different from the mutual information in the Bayesian setting, where we used $P(Z^N)$ instead of $\nu(Z)^N$ for the data generating distribution. See Appendix~\ref{app_compare} for a detailed comparison between the Bayesian and frequentist settings.
When the squared loss is used, the variance of the predictor has been widely utilized for uncertainty estimation, which is a common practice in VI, Monte Carlo (MC) dropout \cite{kendall2017uncertainties}, and deep ensemble methods \cite{lakshminarayanan2017simple}. Conditioned on $(X,Z^N)=(x,z^N)$, it is written as
\begin{align}\label{drop_out}
\mathrm{Var}f_\theta(x)=\mathbb{E}_{Q(\theta|z^N)}(f_\theta(x)-\mathbb{E}_{Q(\theta|z^N)}f_\theta(x))^2.
\end{align}
Eqs.\eqref{freq_mutual_information} and \eqref{drop_out} are intuitively meaningful expressions of the EU. However, the following points are still unclear theoretically. {\bf (Q1)} First, it is unclear how these measurements relate to the loss function and fundamental learning limit. {\bf (Q2)} Second, the convergence behaviors of these measurements are not apparent. As the number of training data points increases, we expect these measurements to converge to 0. {\bf (Q3)} Third, the relationship between these measurements and the generalization ability is unclear. Since these measurements depend on the training data and the algorithm, we expect that there must be some meaningful relation.
To analyze the EU in the frequentist setting, we consider introducing the excess risk in the same way as Sec.~\ref{sec:Bayes_SBackground}. We define the total risk at point $x$ as $\mathrm{TR}_\mathrm{f}^l(Y|X=x,Z^N)=\mathbb{E}_{\nu(Z)^N\nu(Y|X=x)}l(y,\mathbb{E}_{Q(\theta|Z^N)}f_\theta(x))$ and express $\mathrm{TR}_\mathrm{f}^l(Y|X,Z^N)=\mathbb{E}_{\nu(x)}\mathrm{TR}_\mathrm{f}^l(Y|X=x)$. The total risk expresses the prediction performance of $\mathbb{E}_{Q(\theta|Z^N)}f_\theta(x)$. Then the fundamental limit of learning at point $x$ is defined as $R_\mathrm{f}^l(Y|X=x)=\min_{a}\mathbb{E}_{\nu(Y|X=x)}l(y,a)$.
Finally the excess risk (ER) is defined as the difference between the total risk and the fundamental limit of learning:
\begin{align}
&\mathrm{ER}_\mathrm{f}^l(Y|X,Z^N)=\mathrm{TR}_\mathrm{f}^l(Y|X,Z^N)-R_\mathrm{f}^l(Y|X)\label{eq_erfreq},
\end{align}
where $R_\mathrm{f}^l(Y|X)=\mathbb{E}_{\nu(x)}R_\mathrm{f}^l(Y|X=x)$. For simplicity, we express $\mathrm{ER}_\mathrm{f}^l(Y|X=x,Z^N=z^n)$ as $\mathrm{ER}_\mathrm{f}^l(Y|x,z^n)$. We call Eq.\eqref{eq_erfreq} the {\bf frequentist excess risk} to make the meaning clearer. In practice, we are interested in estimating the EU at test data point $x$ without using target variable $y$, similarly to Eqs.\eqref{freq_mutual_information} and \eqref{drop_out}. However, we cannot use Eq.\eqref{eq_erfreq} for that purpose since we do not know both $\nu(Y|X=x)$ and $R_\mathrm{f}^l(Y|X=x)$. Thus, it is difficult to use Eq.\eqref{eq_erfreq} to evaluate the EU. Moreover, {\bf (Q4)} the relations among Eq.\eqref{eq_erfreq} and the widely used EU measurements Eqs.\eqref{freq_mutual_information} and \eqref{drop_out} are unclear.
\vspace{-2mm}
\section{Analysis of excess risk in the PAC-Bayesian frequentist setting}\label{sec_freq}
\vspace{-3mm}
In this section, we develop theories to analyze EU in the frequentist setting that answer the questions {\bf (Q1)} to {\bf (Q4)} raised in Sec.~\ref{sec_freqe}. All the proofs in this section are shown in Appendix~\ref{app_proof_sec_3}.
\vspace{-2mm}
\subsection{Approximating the test data by the Bayesian setting for the excess risk analysis}\label{sec_freq_bayes}
\vspace{-2mm}
As we have seen in Sec.\ref{sec:Bayes_SBackground}, in the Bayesian setting, we can analytically calculate the excess risk thanks to the data generation assumption. This motivates us to introduce the Bayesian setting for the frequentist setting.
Following the joint distribution of the Bayesian setting in Eq.\eqref{generating}, we approximate the joint distribution of test data, training data, and the parameters in the frequentist setting by
\begin{align}\label{start_approx}
\nu(Z)^NQ(\theta|Z^N)\nu(X)\nu(Y|X)\approx P_\mathrm{f}(Z^N,\theta,Z).
\end{align}
Here $P_\mathrm{f}(Z^N,\theta,Z)$ is defined as
\begin{align}\label{generating2}
P_\mathrm{f}(Z^N,\theta,Z):=\nu(Z)^NQ(\theta|Z^N)\nu(X)P(Y|X,\theta),
\end{align}
where $P(dy|x,\theta)=p(y|f_\theta(x))dy$ when the log loss is used. When the squared loss is used, assume a Gaussian distribution $P(dy|x,\theta)=N(y|f_\theta(x),v^2)dy$ for some $v\in\mathbb{R}$.
When a model is well specified, that is, $\nu(Y|x)=P(Y|x,\theta^*)$ holds for some $\theta^*\in\Theta$, we expect that the posterior predictive distribution converges to $P(Y|x,\theta^*)$ and the approximation of Eq.\eqref{start_approx} becomes accurate as $N$ increases. We discuss the quality of this approximation in Sec.\ref{sec_pactob}. Under this setting, we define the excess risk following the Bayesian setting as
\begin{align}\label{excss_bayes}
\mathrm{ER}_\mathrm{b}^l(Y|X,Z^N)=\mathrm{TR}_\mathrm{b}^l(Y|X,Z^N)-R_\mathrm{b}^l(Y|X,\theta),
\end{align}
where $\mathrm{TR}_\mathrm{b}^l(Y|X,Z^N)$ is a total risk given as
\begin{align}
\mathrm{TR}_\mathrm{b}^l(Y|X,Z^N):=\mathbb{E}_{P_\mathrm{f}(Z^N,Z)}l(Y,\mathbb{E}_{Q(\theta'|Z^N)}f_{\theta'} (X)),
\end{align}
and $R_\mathrm{b}^l(Y|X,\theta)$ is the fundamental limit of learning, which is defined similarly to Eq.\eqref{minimum} as,
\begin{align}\label{minimum_bayes}
R_\mathrm{b}^l(Y|X,\theta):=\inf_{\phi:\Theta\times\mathcal{X}\to\mathcal{A}}\mathbb{E}_{P_\mathrm{f}(\theta,Z^N,Z)}l(Y,\phi(\theta,X)).
\end{align}
We call $\mathrm{ER}_\mathrm{b}^l(Y|X,Z^N)$ the {\bf Bayesian excess risk}. We point out that $\mathrm{ER}_\mathrm{b}^l(Y|X,Z^N)$ is always larger than 0; see Appendix~\ref{app_proof_sec_3} for details. When the log loss is used, we express it as $\mathrm{ER}_\mathrm{b}^{\mathrm{log}}(Y|X,Z^N)$ and when the squared loss is used, we express it as $\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)$.
The next theorem is our first main result that connects the widely used uncertainty measurements, such as the mutual information Eq.\eqref{freq_mutual_information} and dropout variance Eq.\eqref{drop_out} to $\mathrm{ER}_\mathrm{b}^l(Y|X,Z^N)$ as follows:
\begin{thm}\label{freq_to_bayes}Under the definition of Eq.\eqref{excss_bayes}, conditioned on $(x,z^N)$, we have
\begin{align}
\mathrm{ER}_\mathrm{b}^{\mathrm{log}}(Y|x,z^N)=I_{\nu}(\theta;Y|x,z^N), \quad \quad\quad\mathrm{ER}_\mathrm{b}^{(2)}(Y|x,z^N)=\mathrm{Var}f_\theta(x).
\end{align}
\end{thm}
\vspace{-2mm}
Thus, by studying the Bayesian excess risk, we can analyze the widely used EU measurements. We point out that $\mathrm{TR}_\mathrm{b}^{\mathrm{log}} (T|x,z^N)=H(p(Y|x,z^N))$ and $R_\mathrm{b}^{\mathrm{log}} (Y|x,\theta)=E_{Q(\theta|z^{N})}H(p(Y|x,\theta))$ hold.
\vspace{-3mm}
\subsection{Analysis of the Bayesian and PAC-Bayesian frequentist excess risks}\label{sec_pactob}
\vspace{-2mm}
Here, we show the theoretical properties of the Bayesian and frequentist excess risk for the squared and log loss. Then, we discuss how they are related to the generalization ability.
\vspace{-2mm}
\paragraph{Analysis of the squared loss:}
We present an analysis of the squared loss. For simplicity, assume $\mathcal{Y}=\mathbb{R}$. See Appendix~\ref{app_multi_dim} for $\mathcal{Y}=\mathbb{R}^d$. The following basic relation is useful for the latter analysis:
\begin{lmm}\label{mv_vi}
For any $(x,y)$ and any posterior distribution conditioned on $z^N$, we have
\begin{align}
|y-\mathbb{E}_{Q(\theta|z^N)}f_\theta(x)|^2+ \mathrm{Var}f_\theta(x)=\mathbb{E}_{Q(\theta|z^N)}|y-f_\theta(x)|^2.
\end{align}
\end{lmm}
\vspace{-2mm}
This lemma clarifies the relation between the Jensen gap and the Bayesian excess risk. The next theorem provides answers to questions {\bf (Q1)} to {\bf (Q3)} for the squared loss.
\begin{thm}\label{thm_square}
Conditioned on $(x,z^N)$, assume that a regression function is well specified, that is, $\mathbb{E}_{\nu(Y|x)}[Y|x]=f_{\theta^*}(x)$ holds. Then we have
\begin{align}\label{square_joint}
\mathrm{ER}_\mathrm{f}^{(2)}(Y|x,z^N)+\mathrm{ER}_\mathrm{b}^{(2)}(Y|x,z^N)=R^{(2)}(Y|x,z^N,\theta^*)\leq R^{(2)}(Y|x,z^N).
\end{align}
By taking the expectation, we have
\begin{align}\label{eq_bound_square}
\scalebox{0.96}{$\displaystyle \mathrm{ER}_\mathrm{f}^{(2)}(Y|X,Z^N)\!+\!\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)\!=\!R^{(2)}(Y|X,Z^N,\theta^*)\leq R^{(2)}(Y|X,Z^N).$
\end{align}
Furthermore assume that the PAC-Bayesian bound Eq.\eqref{base_PAC} holds. Then we have
\begin{align}\label{eq_bound_square2}
\mathrm{ER}_\mathrm{f}^{(2)}(Y|X,Z^N)+\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)\leq\frac{C_1\ln N}{N^\alpha}.
\end{align}
\end{thm}
\begin{rmk}
When we use a flexible model such as a deep neural network for $f_\theta(x)$, the assumption $\mathbb{E}_{\nu(Y|x)}[Y|x]=f_{\theta^*}(x)$ will be satisfied. Thus, the assumption still holds when we misspecify the noise function $\nu(Y|x)$.
\end{rmk}
\vspace{-2mm}
From Eq.\eqref{square_joint}, it is clear that $\mathrm{Var}f_\theta(x)$ is a lower bound of the conditional test error. This is consistent with the well known result that the variance of the predictor often underestimates the EU \cite{lakshminarayanan2017simple}. Moreover, from Eqs.~\eqref{eq_bound_square} and \eqref{eq_bound_square2}, $\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)$ converges to 0 with the same order as the PAC-Bayesian bound. Moreover, from Eq.\eqref{eq_bound_square}, we have $|\mathrm{ER}_\mathrm{f}^{(2)}(Y|X,Z^N)-\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)|\leq \!R^{(2)}(Y|X,Z^N,\theta^*)\leq R^{(2)}(Y|X,Z^N)$. Thus, the gap between the Bayesian and frequentist excess risks decreases as the test error decreases. In Appendix~\ref{discuss_reverse}, we discuss when we can upper-bound the frequentist excess risk $\mathrm{ER}_\mathrm{f}^{(2)}(Y|X,Z^N)$ by the Bayesian excess risk $\mathrm{ER}_\mathrm{f}^{(2)}(Y|X,Z^N)$. Finally, we remark that from Lemma~\ref{mv_vi}, we have
\begin{align}\label{eq_22}
R^{(2)}(Y|X,Z^N)= \mathrm{TR}_\mathrm{f}^{(2)}(Y|X,Z^N)+\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N).
\end{align}
This indicates that the test error is decomposed into the total risk, which evaluates the prediction performance, and the Bayesian excess risk. This relation plays an important role in Sec.~\ref{sec_algorithm}.
\vspace{-2mm}
\paragraph{Analysis of the log loss:} To analyze the log loss, we apply change-of-measure inequalities \cite{ohnishi2021novel} to control the approximation error of Eq.\eqref{start_approx}. Using those inequalities requires an assumption about model $p(y|x,\theta)$. We define log density ratio $L(y,x,\theta,\theta^*):=-\ln p(y|x,\theta)+\ln p(y|x,\theta^*)$.
\begin{assumption}\label{sub_exp}Conditioned on $(x,\theta,z^N)$,
there exists function $h(\lambda)$ for $[0,b)$ such that the cumulant function $L(y,x,\theta,\theta^*)$ is upper-bounded by $h(\lambda)$,i.e., the following inequality holds:
\begin{align}
\ln\mathbb{E}_{p(Y|x,\theta)}e^{\lambda(L(Y,x,\theta,\theta^*)-\mathbb{E}_{p(Y|x,\theta)}L(Y,x,\theta,\theta^*))} \leq h(\lambda)
\end{align}
\end{assumption}
For example, if $h(\lambda)=\lambda^2\sigma^2(x,\theta)/2$ and $b=\infty$, this assumption is similar to the $\sigma^2$ sub-Gaussian property given $(x,\theta,z^N)$. When considering the Gaussian likelihood $p(y|x,\theta)=N(y|f_\theta(x),v^2)$, we have $\scalebox{0.90}{$h(\lambda)=\frac{\lambda^2}{2v^2}|f_\theta(x)-f_{\theta*}(x)|^2$}$. Thus, $\sigma^2(x,\theta)$ depends on $x$ and $\theta$ and we refer to this $\sigma^2(x,\theta)$ sub Gaussian property. Other than the Gaussian likelihood, when the log loss is bounded, it satisfies the sub-Gaussian property. In this paper, we focus on this sub-Gaussian setting for Assumption~\ref{sub_exp} to make the presentation clear. We show the example of the logistic regression in Appendix~\ref{app_llogistc}.
When a model is well specified, the posterior predictive distribution converges to $\nu(Y|x)$; thus, we expect that $\mathrm{ER}_\mathrm{f}$ and $\mathrm{ER}_\mathrm{b}$ behave in a similar way. This intuition is formalized by the next theorem:
\begin{thm}\label{thm_freq_excess_risk}
When the model is well specified, that is, $\nu(dy|x)=p(y|x,\theta^*)dy$ holds and $\sigma^2(x,\theta)$ sub-Gaussian property is satisfied for $L(y,x,\theta,\theta^*)$ as discussed above. Assume that $\mathbb{E}_{Q(\theta|z^N)}\sigma^2(x,\theta)<\sigma_p^2<\infty$. Conditioned on $(X,Z^N)=(x,z^N)$, we have
\begin{align}\label{general}
\mathrm{ER}_\mathrm{f}^{\mathrm{log}}(Y|x,z^N)+\mathrm{ER}_\mathrm{b}^{\mathrm{log}}(Y|x,z^N)\leq \sqrt{2\sigma_p^2R^{\mathrm{log}}(Y|x,z^N,\theta^*)}.
\end{align}
Moreover, assume the PAC-Bayesian bound Eq.\eqref{base_PAC} and $\scalebox{0.90}{$\mathbb{E}_{\nu(\!Z\!)^NQ(\!\theta|Z^N\!)\nu(\!x\!)}\sigma^2(x,\!\theta)\!<\!\sigma_q^2\!<\!\infty\!$}$ hold, we have
\begin{align}\label{general2}
\mathrm{ER}_\mathrm{f}^{\mathrm{log}}(Y|X,Z^N)+\mathrm{ER}_\mathrm{b}^{\mathrm{log}}(Y|X,Z^N)\leq \sqrt{2\sigma_q^2R^{\mathrm{log}}(Y|X,Z^N,\theta^*)}\leq \sqrt{\frac{2\sigma_q^2C_1\ln N}{N^{\alpha}}}.
\end{align}
\end{thm}
This theorem corresponds to Theorem~\ref{thm_square} for the squared loss. From Eq.\eqref{general}, $I_{\nu}(\theta;Y|x,z^N)$ is a lower bound of the test log loss. From Eq.\eqref{general2}, the mutual information $\scalebox{0.95}{$I_{\nu}(\theta;Y|X,Z^N)$}$ converges in order of $\scalebox{0.95}{$\mathcal{O}(\sqrt{\ln N/N^{\alpha}})$}$ if we can upper-bound $\scalebox{0.95}{$\mathbb{E}_{\nu(Z)^NQ(\theta|z^N)\nu(x)}\sigma^2(x,\theta)<\sigma_q^2<\infty$}$. For the Gaussian likelihood, we have $\scalebox{0.95}{$\mathbb{E}\sigma^2(x,\theta)\leq\mathbb{E}\frac{1}{v^2}|f_\theta(x)\!-\!f_{\theta*}(x)|^2\!=\!2R^{\mathrm{log}}(Y|X,Z^N,\theta^*)\!\leq\frac{2C_1\ln N}{N^{\alpha}}:=\sigma_q^2$}$.
Finally, we have the following result for the entropy of the posterior predictive distribution:
\begin{col}\label{entropy}
Under the same assumption as Theorem~\ref{thm_freq_excess_risk}, assume that $\ln p(y|x,\theta)$ satisfies the $\sigma^2$ sub-Gaussian property similary to Assumption~\ref{sub_exp}. Conditioned on $(x,z^N)$, we have
\begin{align}
H(p(Y|x,z^N))\leq R^{\mathrm{log}}(Y|x,z^N)+2\sqrt{2\sigma_p^2R^{\mathrm{log}}(Y|x,z^N,\theta^*)}.
\end{align}
\end{col}
So far, we assumed the sub-Gaussian property. We show a similar results for Theorem~\ref{thm_freq_excess_risk} and Corollary~\ref{entropy} when a sub-exponential property holds in Appendix~\ref{app_sub_exp}.
In conclusion, from Theorems~\ref{thm_square} and \ref{thm_freq_excess_risk}, the widely used EU measurements are lower bounds of the test error. When the PAC-Bayesian bound Eq.\eqref{base_PAC} holds, we can derive their convergence rate. Conversely, the sum of the frequentist and Bayesian excess risk is upper-bounded by the test error. This implies improving the generalization ability leads to small excess risk.
When we cannot evaluate $Q(\theta|Z^N)$ explicitly, such as with Langevin MC methods, we cannot calculate $\mathrm{KL}(Q(\theta|Z^N)|P(\theta))$ in the PAC-Bayesian bound of Eq.\eqref{base_PAC}. Under such a setting, the information theoretic generalization error bound \cite{xu2017information} is useful: we can upper-bound the generalization error bound by the mutual information $I(\theta;Z^N)$. Upper bounding $I(\theta;Z^N)$ in an algorithm dependent way \cite{pensia2018generalization} leads to the algorithm dependent bound of the widely used EU measurements.
Finally, we remark the setting of model misspecification; when the model is misspecified, the predictive distribution does not converge to $\nu(Y|x)$, thus the relation between $\mathrm{ER}_\mathrm{f}^l$ and $\mathrm{ER}_\mathrm{b}^l$ is not clear as compared to the well specified setting. In Appendix~\ref{app_model_misspecification}, we show a theoretical result similar to Theorem~\ref{thm_freq_excess_risk} by introducing an additional assumption of the Bernstein condition.
\vspace{-2mm}
\subsection{A novel EU regularization method for variational inference}\label{sec_algorithm}
\vspace{-2mm}
Here we discuss the relation between the objective functions of VI and Bayesian excess risk. As an explicit example, consider a regression problem using $N(y|f_\theta(x),v^2)$. Then from Lemma~\ref{mv_vi}, the objective function of the standard VI can be written as
\begin{align}\label{gp}
-\mathbb{E}_{Q(\theta|z^N)}\ln N(y|f_\theta(x),v^2)
&=\frac{|y-\mathbb{E}_{Q(\theta|z^N)}f_\theta(x)|^2+ \mathrm{Var}f_\theta(x)}{2v^2}+\frac{1}{2}\ln2\pi v^2
\end{align}
This indicates that the standard VI tries to fit the mean of the predictive distribution to the target variable $y$ with the regularization term of the Bayesian excess risk. Note that there is a relation about $\mathrm{Var}f_\theta(x)$ and $\mathrm{ER}_\mathrm{b}^{\mathrm{log}}(Y|x,z^N)$ as $\mathrm{ER}_\mathrm{b}^{\mathrm{log}}(Y|x,z^N)\leq \mathrm{Var}f_\theta(x)/v^2$ for the Gaussian likelihood. It had been reported numerically that the standard VI often underestimates the EU. To address this issue, alternative objective functions were proposed. For example, the entropic loss defined as
$\mathrm{Ent}_{\alpha}^l(y,x):=-\frac{1}{\alpha}\ln \mathbb{E}_{Q(\theta|z^N)}e^{-\alpha l(y,f_\theta(x))}$ for $\alpha>0$, which is used in the $\alpha$-divergence dropout ($\alpha$-DO) \cite{li2017dropout} and the second order PAC-Bayesian methods ($2^\mathrm{nd}$-PAC) \cite{NEURIPS2020_3ac48664,futami2021loss}, can capture the EU better than the standard VI. Note that for $\alpha=1$ and the log loss, the Entropic risk corresponds to the log loss using the predictive distribution.
For the Gaussian likelihood, we can upper-bound the entropic risk as
\begin{align}\label{eq_mutual}
\scalebox{0.92}{$\displaystyle\mathbb{E}_{\nu}\mathrm{Ent}_{\alpha=1}^{\mathrm{log}}(Y,X)\leq\!
\mathbb{E}_{\nu}\frac{|Y\!-\!\mathbb{E}_{Q(\theta|z^N)}f_\theta(X)|^2}{v^2}\!+\!\frac{\mathrm{Var}f_\theta(X)}{v^2}\!-\!\mathrm{ER}_\mathrm{b}^{\mathrm{log}}(Y|X,z^N)\!+\!\ln2\pi v^2$},
\end{align}
where we used Eq.\eqref{general}. See Appendix~\ref{app_general} for the derivation. Compared to Eq.\eqref{gp}, the entropic risk implicitly introduces the smaller regularization term about the Bayesian excess risk. This explains why $\alpha$-DO and $2^\mathrm{nd}$-PAC showed larger EU compared to the standard VI. We show a similar result about the entropic risk of the general log loss other than the Gaussian likelihood in Appendix~\ref{app_general}.
From these relations, introducing the appropriate Bayesian excess risk as regularization leads to a solution that better evaluates the EU. Motivated by the decomposition from Eq.\eqref{gp} to \eqref{eq_mutual}, we consider directly controlling the prediction performance and the Bayesian excess risk for the Gaussian likelihood as follows:
\begin{align}\label{proposal}
\scalebox{0.95}{$\displaystyle\mathrm{BER}(\lambda)=\frac{1}{N}\sum_{i=1}^N \frac{|y_i\!-\!\mathbb{E}_{Q(\theta|z^N)}f_\theta(x_i)|^2}{2v^2}\!+\lambda\frac{\mathrm{Var}f_\theta(x_i)}{2v^2}\!+\frac{\ln2\pi v^2}{2}\!+\frac{1}{N}\mathrm{KL}(Q(\theta|z^N)|P(\theta))$},
\end{align}
where $0<\lambda\leq 1$ is the coefficient of the regularizer of the Bayesian excess risk. $\mathrm{KL}(Q(\theta|z^N)|P(\theta))$ is the regularization term motivated by the PAC-Bayesian theory. We select $\lambda$ by cross-validation and it should be smaller than 1 since $\lambda=1$ correspond to the standard VI from Eq.\eqref{gp} and the standard VI often underestimates the EU. We call Eq.\eqref{proposal} as the Bayesian excess risk regularization (BER). We show the PAC-Bayesian generalization guarantee for our BER in Appendix~\ref{app_propose}. In Sec.~\ref{sec_nume_eval}, we evaluated this objective function numerically.
BER can also be seen as the extension of the standard VI. In the standard VI, the test loss is lower-bounded by the sum of the total risk and the Bayesian excess risk with equal weights, as shown in Eq.\eqref{eq_22}. BER has the flexible weights between them. See Appendix~\ref{app_propose} for the detailed comparison.
\vspace{-3mm}
\section{Discussion of existing work on the epistemic uncertainty analysis}
\vspace{-2mm}
Existing theoretical analysis of the uncertainty focused on the calibration performance and tried to clarify when a model over- and underestimates the uncertainty \cite{nixon2019measuring,bai2021don,naeini2015obtaining,guo2017calibration}. Other than calibration, the analysis of the Gaussian processes has been gaining attention since its posterior predictive distribution can be expressed analytically \cite{fiedler2021practical,lederer2019posterior}. Some research focused on the distance or geometry between test and training data points to derive the EU \cite{liu2020simple,tian2021geometric}. Other approaches connect the randomness of the posterior distribution to the prediction by the delta method \cite{nilsen2022epistemic}.
Differently, the information-theoretic approach in \cite{xu2020minimum} focused on the loss function of the problem and defined the excess risk as the EU. The loss function-based analysis has been proposed in the deterministic learning algorithm \cite{jain2021deup}.
Thus, our theories can be regarded as extension of the information-theoretic approach in \cite{xu2020minimum} to the frequentist settings and derived the convergence properties of the variance and entropy of the posterior predictive distributions for the first time.
In the frequentist setting, although Eq.\eqref{base_PAC}, which is closely related to the excess risk, has been discussed in terms of the PAC Bayesian generalization bound \cite{alquier2021user}, its relation to the EU has not been investigated. The relationship between the PAC-Bayesian bound and Bayesian inference has been investigated in terms of the marginal likelihood \cite{germain2016pac,pmlr-v139-rothfuss21a}. Our work established the new relationships that connect the uncertainty of the Bayesian predictive distribution and the PAC-Bayesian generalization bound. In the Bayesian setting, the information-theoretic approach \cite{xu2020minimum} clarified that the EU can be expressed by the conditional mutual information. This relation was extended to meta-learning \cite{jose2021information}. However, the researchers assumed that correct models and exact posterior distributions are available. Our proposed analysis relaxes those assumptions.
\vspace{-3mm}
\section{Numerical experiments}\label{sec:numerical}
\vspace{-2mm}
In this section, we numerically confirm the theoretical findings in Sec.~\ref{sec_freq} and our proposed BER in Eq.\eqref{proposal}. We show the detailed experimental settings and additional results in Appendix~\ref{app:experiment}.
\vspace{-2mm}
\subsection{Numerical evaluation of Theorem~\ref{thm_square}}
\vspace{-2.mm}
We confirm the statement of Theorem~\ref{thm_square} numerically. First, we consider toy data experiments where the true model $y=0.5x^3+\epsilon$, $\epsilon\sim N(0,1)$, $x\sim N(0,1)$. We consider a Bayesian neural network (BNN) for $f_\theta(x)$ as a 4 layer neural network model with ReLU activation. We approximate the posterior distribution of the parameters of the neural network by Bayes by backpropagation (BBP), \cite{hernandez2015probabilistic}, dropout \cite{kendall2017uncertainties}, and deep ensemble \cite{lakshminarayanan2017simple}. We evaluate $\mathrm{ER}_\mathrm{f}^{(2)}(Y|X,Z^N)$, $\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)$, and $R^{(2)}(Y|X,Z^N)$. The results are shown in Fig.~\ref{fig_toy}. We found that the numerical results satisfy Eq.\eqref{eq_bound_square} in Theorem~\ref{thm_square}. As the number of samples increases, $\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)$ and the gap $|\mathrm{ER}_\mathrm{f}^{(2)}(Y|X,Z^N) -\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)|$ decreases. We calculated the Spearman Rank Correlation (SRC) between $\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)$, $\mathrm{ER}_\mathrm{f}^{(2)}(Y|X,Z^N)$, and $R^{(2)}(Y|X,Z^N)$ and showed at least $0.97$ suggesting high correlation relation between them.
\begin{figure}[tb!]
\centering
\includegraphics[width=0.9\linewidth]{NN_toy.eps}
\vspace{-2mm}
\caption{The result of toy data experiments. $N$ represents the number of training data points and the vertical line is the value of each excess risk.}
\label{fig_toy}
\end{figure}
\begin{figure}[tb!]
\centering
\includegraphics[width=0.9\linewidth]{depth.eps}
\vspace{-3mm}
\caption{Real data experiments of depth estimation. The vertical line is the value of each risk.}
\label{fig_ensemble}
\end{figure}
Next, we confirm Theorem~\ref{thm_square} using a real-world dataset. Following the setting of existing work \cite{amini2020deep}, the data is NYU Depth v2 dataset \cite{silberman2012indoor}, which consists of RGB-to-depth, and we trained a U-Net style network \cite{ronneberger2015u} by dropout and Deep ensemble methods. Since we cannot evaluate the $\mathrm{ER}_\mathrm{f}^{(2)}(Y|X,Z^N)$, instead, we evaluate the Eq.\eqref{eq_22}, which only requires $\mathrm{TR}_\mathrm{f}^{(2)}(Y|X,Z^N)$, $\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)$, and $R^{(2)}(Y|X,Z^N)$. The result is shown in Fig.~\ref{fig_ensemble}. We found that the theoretical relation still holds for these real dataset experiments. We calculated the SRC between $\mathrm{TR}_\mathrm{f}^{(2)}(Y|X,Z^N)$, $\mathrm{ER}_\mathrm{b}^{(2)}(Y|X,Z^N)$, and $R^{(2)}(Y|X,Z^N)$ and showed at least $0.98$ suggesting high correlation relation between them.
\vspace{-3mm}
\subsection{New uncertainty regularization based on the Bayesian excess risk}\label{sec_nume_eval}
\vspace{-3mm}
We numerically compared the prediction and EU evaluation performances of our proposed method shown in Eq.\eqref{proposal} in regression and contextual bandit tasks. Motivated by the success of the entropic risk in the particle VI (PVI) \cite{NEURIPS2020_3ac48664,futami2021loss}, which approximates the posterior distribution by the ensemble of models, we also applied our BER to the PVI setting. Thus, the posterior distribution is expressed as $Q(\theta):=\frac{1}{N}\sum_{i=1}^M\delta_{\theta_i}(\theta)$, where $\delta_{\theta_i}(\theta)$ is the Dirac distribution that has a mass at $\theta_i$. See Appendix~\ref{app:experiment} for details about PVI.
We refer BER($0$) when $\lambda=0$ in Eq.\eqref{proposal}. We compared our method with existing PVI methods, f-SVGD \cite{DBLP:conf/iclr/WangRZZ19}, $\mathrm{PAC}^2_\mathrm{E}$ \cite{NEURIPS2020_3ac48664}, and VAR \cite{futami2021loss}.
For regression tasks, we used the UCI dataset \cite{Dua:2017}. The model is a single-layer network with ReLU activation, and we used 20 ensembles. The results of $20$ repetitions are shown in Table~\ref{tab:bench_regm}. We evaluated the fitting performance by RMSE and uncertainty estimation performance by the prediction interval coverage probability (PICP), which shows the number of test observations inside the estimated prediction interval and set the interval as 0.95. PICP is best when it is close to 0.95. We evaluated the mean prediction interval width (MPIW), which shows an average width of a prediction interval. A smaller MPIW is a better uncertainty estimate. Due to the space limitations, results of $\mathrm{PAC}^2_\mathrm{E}$ and other $\lambda$s and the negative log-likelihood are shown in Appendix~\ref{app:experiment}. We found the existing PVIs show small PICP and MPIW, which indicate that existing methods underestimate the uncertainty. BER($0$) shows the large PICP and MPIW since the Bayesian excess risk is not regularized. BER($0.05$) shows the moderate MPIW with better PICP, and almost identical prediction performance in RMSE. Thus, BER successfully controls the prediction and uncertainty evaluation performances.
Next, we evaluated the BER using contextual bandit problems \cite{riquelme2018deep}. We need to balance the trade-off between exploitation and exploration to achieve small cumulative regret. For that purpose, our algorithms must appropriately control the prediction and uncertainty evaluation performance. We used the Thompson sampling algorithm with BNN having two hidden layers. We used 20 ensembles for approximating the posterior distribution. The results of $10$ repetitions are shown in Table~\ref{tab:bench_regretm}. Our approach outperforms other methods, which means our proposed method showed better prediction and uncertainty control over existing methods.
\begin{figure}
\centering
\begin{minipage}{1.0\textwidth}
\centering
\tblcaption{Benchmark results on test RMSE, PICP, and MPIW.}
\label{tab:bench_regm}
\resizebox{1.\textwidth}{!}{
\begin{tabular}{c|cccc|cccc}
\toprule
\fontsize{9}{7.2}\selectfont \bf{\multirow{2}{*}{Dataset}} &
\multicolumn{4}{|c}{\fontsize{9}{7.2}\selectfont Avg. Test RMSE} & \multicolumn{4}{|c}{\fontsize{9}{7.2}\selectfont Avg. Test PICP and MPIW in parenthesis} \\
& \fontsize{9}{7.2}\selectfont f-SVGD&
\fontsize{9}{7.2}\selectfont VAR&
\fontsize{9}{7.2}\selectfont BER($0$) & \fontsize{9}{7.2}\selectfont BER($0.05$) &
\fontsize{9}{7.2}\selectfont f-SVGD &
\fontsize{9}{7.2}\selectfont VAR &
\fontsize{9}{7.2}\selectfont BER($0$) & \fontsize{9}{7.2}\selectfont BER($0.05$) \\
\hline
\fontsize{8}{7.2}\selectfont Concrete&
\fontsize{8}{7.2}\selectfont 4.33$\pm$0.8&
\fontsize{8}{7.2}\selectfont 4.30$\pm$0.7 &
\fontsize{8}{7.2}\selectfont 4.47$\pm$0.6 &
\fontsize{8}{7.2}\selectfont 4.48$\pm$0.7 &
\fontsize{8}{7.2}\selectfont 0.82$\pm$0.03 (0.13$\pm$0.00) &
\fontsize{8}{7.2}\selectfont 0.87$\pm$0.04 (0.16$\pm$0.01) &
\fontsize{8}{7.2}\selectfont 0.99$\pm$0.02 (0.50$\pm$0.04)&
\fontsize{8}{7.2}\selectfont {\bf 0.95$\pm$0.02} (0.25$\pm$0.02) \\
\fontsize{8}{7.2}\selectfont Boston&
\fontsize{8}{7.2}\selectfont 2.54$\pm$0.50 &
\fontsize{8}{7.2}\selectfont 2.53$\pm$0.50 &
\fontsize{8}{7.2}\selectfont 2.53$\pm$0.50 &
\fontsize{8}{7.2}\selectfont 2.53$\pm$0.51 &
\fontsize{8}{7.2}\selectfont 0.63$\pm$0.07 (0.10$\pm$0.02) &
\fontsize{8}{7.2}\selectfont 0.76$\pm$0.05 (0.14$\pm$0.01) &
\fontsize{8}{7.2}\selectfont 0.97$\pm$0.01 (0.33$\pm$0.04) &
\fontsize{8}{7.2}\selectfont {\bf 0.92$\pm$0.04}(0.22$\pm$0.02) \\
\fontsize{8}{7.2}\selectfont Wine&
\fontsize{8}{7.2}\selectfont 0.61$\pm$0.04 &
\fontsize{8}{7.2}\selectfont 0.61$\pm$0.04 &
\fontsize{8}{7.2}\selectfont 0.64$\pm$0.04 &
\fontsize{8}{7.2}\selectfont 0.63$\pm$0.02 &
\fontsize{8}{7.2}\selectfont 0.79$\pm$0.03 (0.32$\pm$0.05) &
\fontsize{8}{7.2}\selectfont 0.85$\pm$0.02 (0.39$\pm$0.06) &
\fontsize{8}{7.2}\selectfont 0.99$\pm$0.00 (1.61$\pm$0.00) &
\fontsize{8}{7.2}\selectfont {\bf 0.95$\pm$0.03} (0.32$\pm$0.15) \\
\fontsize{8}{7.2}\selectfont Power&
\fontsize{8}{7.2}\selectfont 3.78$\pm$0.14 &
\fontsize{8}{7.2}\selectfont 3.75$\pm$0.13 &
\fontsize{8}{7.2}\selectfont 3.66$\pm$0.15 &
\fontsize{8}{7.2}\selectfont 3.69$\pm$0.12&
\fontsize{8}{7.2}\selectfont 0.43$\pm$0.01 (0.07$\pm$0.00) &
\fontsize{8}{7.2}\selectfont 0.82$\pm$0.01 (0.15$\pm$0.00) &
\fontsize{8}{7.2}\selectfont 0.99$\pm$0.01 (0.81$\pm$0.01) &
\fontsize{8}{7.2}\selectfont 0.96$\pm$0.01 (0.37$\pm$0.01) \\
\fontsize{8}{7.2}\selectfont Yacht&
\fontsize{8}{7.2}\selectfont 0.64$\pm$0.28 &
\fontsize{8}{7.2}\selectfont 0.60$\pm$0.28 &
\fontsize{8}{7.2}\selectfont 0.75$\pm$0.41 &
\fontsize{8}{7.2}\selectfont 0.78$\pm$0.48 &
\fontsize{8}{7.2}\selectfont 0.92$\pm$0.04 (0.02$\pm$0.01) &
\fontsize{8}{7.2}\selectfont 0.93$\pm$0.04 (0.04$\pm$0.01) &
\fontsize{8}{7.2}\selectfont {\bf 0.96$\pm$0.03} (0.10$\pm$0.01)&
\fontsize{8}{7.2}\selectfont {\bf 0.94$\pm$0.04} (0.08$\pm$0.01)\\
\fontsize{8}{7.2}\selectfont Protein&
\fontsize{8}{7.2}\selectfont 3.98$\pm$0.54 &
\fontsize{8}{7.2}\selectfont 3.92$\pm$0.05 &
\fontsize{8}{7.2}\selectfont 3.83$\pm$0.10 &
\fontsize{8}{7.2}\selectfont 3.85$\pm$0.05 &
\fontsize{8}{7.2}\selectfont 0.53$\pm$0.01 (0.24$\pm$0.01) &
\fontsize{8}{7.2}\selectfont 0.83$\pm$0.00 (0.58$\pm$0.01) &
\fontsize{8}{7.2}\selectfont 1.0 $\pm$0.00 (5.04$\pm$0.01)&
\fontsize{8}{7.2}\selectfont {\bf 0.96$\pm$0.01} (0.86$\pm$0.00)\\
\bottomrule
\end{tabular}}
\end{minipage}\\
\begin{minipage}{1.0\textwidth}
\centering
\tblcaption{Cumulative regret relative to that of the uniform sampling.}
\label{tab:bench_regretm}
\resizebox{1.0\textwidth}{!}{
\begin{tabular}{c|ccccccc}
\toprule
\fontsize{9}{7.2}\selectfont \bf{Dataset}
& \fontsize{9}{7.2}\selectfont MAP & \fontsize{9}{7.2}\selectfont $\mathrm{PAC}^2_\mathrm{E}$ & \fontsize{9}{7.2}\selectfont f-SVGD & \fontsize{9}{7.2}\selectfont VAR &
\fontsize{9}{7.2}\selectfont BER($0$) &
\fontsize{9}{7.2}\selectfont BER($0.01$) &
\fontsize{9}{7.2}\selectfont BER($0.05$)\\
\hline
\fontsize{8}{7.2}\selectfont Mushroom&
\fontsize{8}{7.2}\selectfont 0.129$\pm$0.098 &
\fontsize{8}{7.2}\selectfont 0.037$\pm$0.012 &
\fontsize{8}{7.2}\selectfont 0.043$\pm$0.009 &
\fontsize{8}{7.2}\selectfont 0.029$\pm$0.010 &
\fontsize{8}{7.2}\selectfont 0.075$\pm$0.005 &
\fontsize{8}{7.2}\selectfont {\bf0.024$\pm$0.009} &
\fontsize{8}{7.2}\selectfont {\bf0.021$\pm$0.004} \\
\fontsize{8}{7.2}\selectfont Financial&
\fontsize{8}{7.2}\selectfont 0.791$\pm$0.219 &
\fontsize{8}{7.2}\selectfont 0.189$\pm$0.025 &
\fontsize{8}{7.2}\selectfont 0.154$\pm$0.017 &
\fontsize{8}{7.2}\selectfont 0.155$\pm$0.024 &
\fontsize{8}{7.2}\selectfont 0.351$\pm$0.030 &
\fontsize{8}{7.2}\selectfont {\bf0.075$\pm$0.024} &
\fontsize{8}{7.2}\selectfont {\bf0.075$\pm$0.031}\\
\fontsize{8}{7.2}\selectfont Statlog&
\fontsize{8}{7.2}\selectfont 0.675 $\pm$0.287 &
\fontsize{8}{7.2}\selectfont 0.032$\pm$0.003 &
\fontsize{8}{7.2}\selectfont 0.010$\pm$0.000 &
\fontsize{8}{7.2}\selectfont 0.006$\pm$0.000 &
\fontsize{8}{7.2}\selectfont 0.145$\pm$0.223 &
\fontsize{8}{7.2}\selectfont 0.005$\pm$0.001 &
\fontsize{8}{7.2}\selectfont {\bf0.005$\pm$0.000}\\
\fontsize{8}{7.2}\selectfont CoverType&
\fontsize{8}{7.2}\selectfont 0.610$\pm$0.051 &
\fontsize{8}{7.2}\selectfont 0.396$\pm$0.006 &
\fontsize{8}{7.2}\selectfont 0.372$\pm$0.007 &
\fontsize{8}{7.2}\selectfont {\bf0.291$\pm$0.004} &
\fontsize{8}{7.2}\selectfont 0.610$\pm$0.051 &
\fontsize{8}{7.2}\selectfont 0.351$\pm$0.003 &
\fontsize{8}{7.2}\selectfont {\bf0.290$\pm$0.002}\\
\bottomrule
\end{tabular}}
\end{minipage}
\end{figure}
\section{Conclusion}
In this work, we theoretically and numerically analyzed the epistemic uncertainty of probabilistic inference. Our theorem clarified the novel relation between excess risk, epistemic uncertainty, and generalization ability. We then show the convergence rate of the widely used uncertainty measures for the first time. Motivated by the theoretical analysis, we proposed the novel epistemic uncertainty regularization algorithm and applied it to the particle variational inference. In future work, it would be interesting to explore the lower bound of the excess risk and its relation to the evidential learning framework \cite{amini2020deep}.
| {'timestamp': '2022-06-06T02:15:36', 'yymm': '2206', 'arxiv_id': '2206.01606', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01606'} | arxiv |
\section{Introduction}
\vspace*{-1mm}
\IEEEPARstart{V}{isible} light communication (VLC) has attracted significant research interest and is expected to be a key component of future communication systems \cite{8669813}. VLC, a communication technology that uses frequencies in the visible light spectrum, offers a vast amount of license-free bandwidth, high security due to the poor penetration of visible light signals, and relatively lower power consumption since the same power is used for the dual-purpose of illumination and communication. VLC uses readily available light sources such as light emitting diodes (LEDs) as transmitters and the receivers are equipped with photodetectors (PDs). Data transmission is achieved in VLC systems via intensity modulation at the transmitter side and direct detection at the receiver side.
Like other high-frequency communication technologies (e.g., terahertz and millimeter-wave), signal propagation at such frequencies is short-range and highly susceptible to blockages. Hence, successful signal transmission in VLC requires a direct line-of-sight (LoS) path between the transmitter and the receiver. The inherent characteristics of visible light signals promote a mutually beneficial co-existence of VLC and radio frequency (RF) communication systems. More particularly, RF communication systems cannot support the ongoing rapid increase in demand for capacity due to the limited available radio spectrum in the sub-6 GHz band and the rising costs of installation and maintenance of RF cell sites. Hence, the co-existence of VLC and RF communication systems allows the combination of the former's high-speed data transmission and the latter's ubiquitous connectivity. It also provides a promising solution to the potential connectivity issues (resulting from blockages and users being in dead zones) in VLC.
The design of communication systems that allow the co-existence of VLC and RF systems can be realized in two main ways, namely, hybrid RF/VLC systems \cite{7593453,8013858,8949364,9484068,8966290,9159585,9411734,9578932,6965999,6655152,9148909,8110682,8741202,8395016,9667214,8862946,8970349} and aggregated RF/VLC systems \cite{7417378,7437374,7293077,7402263,9149834,9614989,8314706,8926487}. The former realizes signal transmission to any user via a VLC or an RF link, while the latter utilizes both VLC and RF links simultaneously to serve any user. However, the challenging problems of access point (AP) assignment due to the mixture of heterogeneous APs and the efficient allocation of transmit power and bandwidth resources arise in such communication systems \cite{8669813,8013858,9411734}.
Specifically, the APs and receivers in VLC systems have limited field-of-view (FoV), affecting the strength of any received signal. As a result, the closest AP might no longer provide the strongest channel gain \cite{9121765}. Moreover, network densification is expected to continue to play a vital role in the next generation of communication networks. This dense deployment can cause severe overlapping of the coverage areas, resulting in strong interference effects. Furthermore, the co-existence of RF/VLC systems will be characterized by multiple heterogeneous layers (e.g., macrocell, picocell, femtocell, and optical attocell layers) with different coverage sizes and operating characteristics \cite{7593453}. Hence, developing highly scalable and novel AP assignment and resource management schemes that can exploit the distinguishing characteristics of RF and VLC systems is of utmost importance.
A number of studies have been carried out to tackle the AP assignment problem and/or the resource management issue in hybrid RF/VLC systems under various objectives such as sum-rate \cite{7593453,8013858,8949364,9484068,8966290,9159585,9411734,9578932}, spectral efficiency \cite{6965999,6655152,9148909}, power consumption \cite{8110682,8741202,8395016,9667214}, and energy efficiency (EE) \cite{8862946,9148909,8970349}. Unlike hybrid RF/VLC systems, few papers have considered the problem of resource allocation in aggregated RF/VLC systems and none has studied the AP assignment problem. The authors in \cite{8314706} investigated EE maximization via subchannel allocation (SA) and power allocation (PA) for an orthogonal frequency division multiple access (OFDMA)-based software-defined aggregated RF/VLC system with multiple RF and VLC APs. However, the authors made the simplifying assumption that the multiple LED arrays transmit the same signal simultaneously and, as a result, ignored any inter-cell interference (ICI) effects. In \cite{7417378}, the problem of transmit power optimization to maximize the achievable rate was investigated for an aggregated RF/VLC system with one VLC AP, one RF AP, and one user.
In \cite{7437374}, the authors optimized the transmit power and bandwidth allocation to maximize the EE of an aggregated system, with a single RF AP and a single VLC AP, that serves multiple users.
By leveraging the bonding technique in the Linux operating system, the design and real-time implementation of an aggregated system were explored in \cite{7293077,7402263}. The authors focused on a system with one RF AP, one VLC AP, and multiple users and provided a theoretical analysis of the average system delay.
The authors in \cite{9149834} studied the EE maximization problem by optimizing the transmit power of an aggregated system with a single user, a single RF AP, and multiple VLC APs. In \cite{9614989}, the authors investigated the joint optimization of the discrete constellation input distribution and PA to maximize the achievable rate of an aggregated system with a single user, a single LED, and one RF antenna. The study in \cite{8926487}
explored the PA optimization problem for an aggregated RF/VLC
system with a single RF AP, multiple VLC APs, and multiple users. However, the authors made the simplifying assumption that the coverage regions of the VLC APs do not overlap and, consequently, did not
consider ICI effects.
None of the studies mentioned above on aggregated RF/VLC systems (i.e., \cite{7417378,7437374,7293077,7402263,9149834,9614989,8314706,8926487}) consider the design and optimization of such a system with multiple APs and users with ICI for both the RF and VLC systems. Indoor environments are typically equipped with multiple LEDs with overlapping coverage areas to guarantee uniform illumination. Moreover, the overlapping illumination areas ensure seamless connectivity in VLC systems. The performance of aggregated RF/VLC systems with multiple APs (i.e., multiple RF and VLC APs) will suffer from ICI effects. Besides, the LoS blockage problem in VLC systems needs to be considered in optimizing the usage of any available resources and the performance analysis of aggregated RF/VLC systems. This is important since the proposed approaches in \cite{7417378,7437374,7293077,7402263,9149834,9614989,8314706,8926487} are not applicable to aggregated RF/VLC systems with multiple APs. Moreover, none of the above-mentioned papers considered the problems of AP assignment, SA, and transmit PA to optimize the EE of aggregated RF/VLC systems.
This paper investigates the EE optimization of aggregated RF/VLC systems equipped with multiple RF and VLC APs serving multiple users, taking into account ICI effects and LoS blockages. The main contributions are summarized as follows:
\begin{itemize}
\item We consider an aggregated RF/VLC system composed of a single macrocell AP and multiple VLC and picocell APs, that serves multiple users. Under the electrical transmit power budgets for the APs and users' minimum quality-of-service (QoS) requirements, we study the joint optimization problem of AP assignment, SA, and transmit PA, while considering the effects of LoS blockages in the VLC systems and ICI in both communication systems. This aims to maximize the EE of the aggregated RF/VLC system. To the best of the authors' knowledge, this is the first time that such an EE optimization problem and constraint sets have been considered for an aggregated RF/VLC system.
\item The formulated design problem turns out to be a challenging non-convex optimization problem. To handle the non-convexity efficiently, the joint problem is decomposed into three subproblems, for which we propose a three-stage alternating solution technique. In the first stage, we exploit matching theory (MT) to assign users to APs while considering any ICI and blockage effects as well as the transmit power budgets of the APs. Then, in the second stage, each AP allocates its subchannels to the assigned users according to the quality of the channel condition. Finally, the APs optimize the transmit PA on the allocated subchannels such that the users' QoS requirements and the APs' transmit power budgets are satisfied while reducing any impact from blockages and ICI. For the transmit power optimization, the quadratic transform approach is first used to express the terms of the signal-to-interference plus noise ratio (SINR) into non-fractional forms. Then with a fixed AP assignment and SA, the formulated EE optimization problem is recast as an equivalent multi-objective optimization problem (MOOP). We propose a solution for the MOOP based on the $\epsilon$-constraint method to obtain the globally optimal solution.
\item Finally, we demonstrate the effectiveness of the proposed alternating solution for the joint problem and compare it with existing schemes and a hybrid RF/VLC system. Moreover, we also investigate the impact of LoS blockages and users' QoS requirements on the EE performance of the aggregated RF/VLC system.
\end{itemize}
The remainder of this paper is structured as follows. The considered system model as well as the channel models for the VLC and RF communication links are introduced and described in Section~\ref{lsm}. The proposed joint AP assignment, SA, and transmit PA optimization problem for aggregated RF/VLC systems is formulated and discussed in Section~\ref{leemp}. The proposed energy-efficient AP assignment and SA solutions are detailed in Section~\ref{leeaasa}, and the proposed solution for the PA subproblem is presented in Section~\ref{eepsca}. Section~\ref{srs} presents and analyzes the simulation results. Finally, Section~\ref{ccs}
summarizes the work.
\vspace*{-3mm}
\section{System Model}\label{lsm}
\vspace*{-2mm}
\subsection{Aggregated RF/VLC Systems}
\vspace*{-2mm}
Figure~\ref{th} illustrates the three-tier network model for the considered aggregated RF/VLC system. In this figure, the macro base station (MBS), also called a macrocell AP, provides blanket coverage for all users in the network. The pico base stations (PBSs), also called picocell APs, provide smaller coverages such as hotspot areas, while the VLC APs are used exclusively for indoor data transmission. According to \cite{7593453}, such a network model involving the coexistence of RF and VLC systems provides several potential benefits that include: (i) high security induced by the poor penetration of the VLC signals; (ii) high total network capacity by employing picocell and VLC APs; (iii) high EE by realizing illumination and data transmission simultaneously in the VLC system; and (iv) reduced interference since the RF and VLC systems use different spectral bands.
\begin{figure}
\centering
\includegraphics[width=0.45\textwidth]{three2}
\vspace*{-4mm}
\caption{Network model of a three--tier heterogeneous network.}
\label{th}
\vspace*{-1.1cm}
\end{figure}
The set of RF and VLC APs are denoted by $\mathcal{K} = \left\{ {0, \ldots ,k \ldots ,\left|{\mathcal{K}}\right| - 1} \right\}$ and\\ $\mathcal{V} = \left\{ {1, \ldots ,v \ldots ,\left|{\mathcal{V}}\right|} \right\}$, respectively, where the index $k=0$ represents the macrocell AP and $\left|{\cdot}\right|$ is the cardinality of a set. The RF and VLC APs employ the OFDMA scheme \cite{6825834,7360112}. The macrocell and the picocell APs use different sets of subchannels to avoid cross--tier ICI. However, the same subchannels are reused among all picocell APs and, as a result, there is co-tier ICI. The OFDMA subchannels for the macrocell and picocell APs are represented by the set $\mathcal{N}=\left\{1, \ldots,n, \ldots, \left|{\mathcal{N}}\right|\right\}$ and $\mathcal{M}=\left\{1, \ldots,m, \ldots, \left|{\mathcal{M}}\right|\right\}$, respectively. Each VLC AP in any indoor environment consists of an array of LEDs, and all attocells reuse the same set of subchannels. Hence, there is the occurrence of ICI in places where the illumination coverage of the VLC APs overlap. The VLC subchannels are represented by the set $\mathcal{Q}=\left\{1, \ldots,q, \ldots, \left|{\mathcal{Q}}\right|\right\}$.
The network serves $J$ users, represented by the set ${\mathcal J} = \left\{ {1, \ldots ,j, \ldots, \left|{\mathcal{J}}\right|} \right\}$, with multi-homing capability that allows any user to aggregate resources from RF and VLC APs, simultaneously. The users are uniformly and randomly distributed within the macrocell. A block diagram of signal transmission and reception in the downlink for any user with multi-homing capability is depicted in Fig.~\ref{mh}. In this figure, the message signal is transmitted simultaneously via the RF and VLC APs assigned to the user, where the signal $s_1$ is a real signal and $s_2$ is a complex signal for the VLC and RF links, respectively. The user's receiver comprises a single PD, with a transconductance amplifier (TCA) that converts the current output from the PD to voltage, and a single RF antenna for receiving the independently transmitted signal over the VLC and RF links, respectively. It is assumed in this work that the channel state information is known at the APs, and there are backhaul links between the macrocell AP and all the other APs for the reliable exchange of channel state information. The channel state information can be collected in the following way. Each AP broadcasts pilot signals to all users. Then, each user estimates the channel state information and sends it to the related AP via a feedback channel. Finally, all the APs send the channel state information to a centralized control unit (CCU).
\begin{figure}
\centering
\includegraphics[width=0.85\textwidth]{agsm3}
\vspace*{-4mm}
\caption{Block diagram of data transmission in an aggregated RF/VLC system.}
\label{mh}
\vspace*{-8mm}
\end{figure}
\vspace*{-5mm}
\subsection{Channel Model}
\vspace*{-2.7mm}
\subsubsection{RF Channel} The channel power gain between user $j$ and the macrocell AP on subchannel $n$ can be expressed as
\vspace*{-5mm}
\begin{equation}\label{cg}
{G_{0,j}^n} = {10^{ - \frac{{{{L\left(d_{0,j}\right) + \Psi + \Gamma + {X_{\sigma}}}}\left[ {{\rm{dB}}} \right]}}{{10}}}},
\end{equation}
where $L\left(\cdot\right)$ denotes the distance-dependent pathloss given by \cite{3gpp}:
\vspace*{-4mm}
\begin{equation}\label{pl1}
L\left(d_{0,j}\right)=128.1 + 37.6{\log _{10}}\left( {{d_{{{0,j}}}}} \right),
\end{equation}
with $d_{0,j}$ being the distance between user $j$ and the macrocell AP in km, $\Psi$ is the penetration loss which is defined as $\Psi=0\,{\rm dB}$ for outdoor users and $\Psi=20\,{\rm dB}+0.5d$ for any indoor user, with $d$ being a distance parameter in m that takes an independent uniform random value from $\left[ {0,\min \left( {25,{d_{0,j}}} \right)} \right]$. The parameters $\Gamma$ and $X_{\sigma}$ represent the multipath fading and the log-normal shadowing standard deviation, respectively.
The channel power gain between user $j$ and picocell $k,\,k\ne0$ on subchannel $m$ is
\vspace*{-4mm}
\begin{equation}\label{cgp}
{G_{k,j}^m} = {10^{ - \frac{{{{L\left(d_{k,j}\right) + \Psi + \Gamma + {X_{\sigma}}}}\left[ {{\rm{dB}}} \right]}}{{10}}}},
\vspace*{-3mm}
\end{equation}
where
\vspace*{-4mm}
\begin{equation}\label{pl2}
L\left(d_{k,j}\right)=140.7 + 36.7{\log _{10}}\left( {{d_{{{k,j}}}}} \right),
\end{equation}
with $d_{k,j}$ being the distance between user $j$ and the AP $k$, and $\Psi=23\,{\rm dB}+0.5d$ for any indoor user served by any picocell AP with $d$ being a distance parameter with value from $\left[ {0,\min \left( {25,{d_{k,j}}} \right)} \right]$.
\subsubsection{VLC Channel}
Only the LoS paths are considered as, according to \cite{7437374}, the non-LoS signals degrade significantly and may result in unsuccessful data transmissions. The LoS channel power gain between user $j$ and the VLC AP $v$ on subchannel $q$ can be expressed as follows:
\vspace*{-4mm}
\begin{equation}\label{cg1}
\begin{array}{*{20}{l}}
{{G_{v,j}^q} = \rho_{v,j}^q\frac{{{A_{{\rm{PD}}}}\left( {m_1 + 1} \right)}}{{2\pi d_{v,j}^2}}{\cos ^{m_1}}\left( {{\phi _{v,j}}} \right)T\left( {{\psi _{v,j}}} \right)}{G\left( {{\psi _{v,j}}} \right) {\cos }\left( {{\psi _{v,j}}} \right),}
\end{array}
\end{equation}
where $\rho_{v,j}^q$ is the probability of LoS availability (i.e., the probability that there is no obstacle in the communication link) between AP $v$ and user $j$ on subchannel $q$, $A_{\rm{PD}}$ is the physical area of the PD, $m_1$ is the order of the Lambertian emission which is calculated as $m_1 = - {{{{\log }_2}\left( {\cos \left( {{\phi _{{1}/{2}}}} \right)} \right)}}^{-1}$, with ${{\phi _{{1}/{2}}}}$ as the LED's semi-angle at half power, ${\phi _{v,j}}$ represents the AP $v$ irradiance angle to user $j$, $\psi _{v,j}$ is the angle of incidence of AP $v$ to user $j$, $T\left( {{\psi _{v,j}}} \right)$ is the gain of the optical filter, and $G\left( {{\psi _{v,j}}} \right) = {{{f^2}}}/{{{{\sin }^2}{\psi _{{\rm{FoV}}}}}},\,0 \le {\psi _{v,j}} \le {\psi _{{\rm{FoV}}}}$, represents the gain of the non-imaging concentrator, where $f$ and ${\psi _{{\rm{FoV}}}}$ denote the refractive index and FoV, respectively.
\vspace{-3mm}
\subsection{Achievable Rates}
Shannon's capacity formula for additive white Gaussian noise (AWGN) channels is used to represent the achievable data rate on any RF link for mathematical tractability in this work. Based on this equation, the achievable downlink rate on subchannel $n$ of the macrocell AP for user $j$ is calculated as
\vspace{-3mm}
\begin{equation}\label{seq1}
R_{0,j}^n=B_{\rm RF} \log_2 \left( 1 + \frac{p_{0,j}^n \left|G_{0,j}^m\right|^2}{N_{\rm RF}B_{\rm RF}}\right),
\end{equation}
where $B_{\rm RF}$ is the subchannel bandwidth, $p_{0,j}^n$ is the transmit power allocated to user $j$ on subchannel $n$, and $N_{\rm RF}$ is the power spectral density of AWGN at the RF receiver. Similarly, the downlink rate on subchannel $m$ of picocell AP $k$ for user $j$ is given by
\vspace{-3mm}
\begin{equation}\label{seq2}
R_{k,j}^m=B_{\rm RF} \log_2 \left( 1 + \frac{p_{k,j}^m \left|G_{k,j}^m\right|^2}{{\sum\limits_{j'\ne j} \sum\limits_{k'\ne {{k}}} {p_{k',j'}^{{m}} { {{ \left|G_{k',j}^m\right|^2 }} } } } + N_{\rm RF}B_{\rm RF} }\right), k\ne 0,
\end{equation}
where $p_{k,j}^m$ is the transmit power from picocell AP $k$ to user $j$ on the subchannel $m$, and $j'$ and $k'$ denote other users and picocell APs that reuse the same subchannel $m$, respectively.
In optical wireless communication systems in general, and VLC systems in particular, there is no suitable closed-form channel capacity formula. Thus, the following tight lower bound on the achievable data rate for user $j$ on subchannel $q$ of the VLC AP $v$ is used \cite{6636053,9578932}
\vspace{-3mm}
\begin{equation}\label{ls}
R_{v,j}^q={ \rho_{v,j}^q B_{\rm VLC} \log_2 \left({ 1 + {\frac{\exp(1)}{2\pi}} \frac{p_{v,j}^{q} {\left( {{R_{\rm{PD}}}{G_{v,j}^{q}}} \right)}^2} {\sum\limits_{j'\ne j} {\sum\limits_{v'\ne v} p_{v',j'}^{q} {\left( {{R_{\rm{PD}}}{G_{v',j}^{q}}} \right)}^2 } + N_{\rm VLC}B_{\rm VLC}} } \right)},
\end{equation}
where $B_{\rm VLC}$ is the subchannel bandwidth, $p_{v,j}^{q}$ is the electrical transmit power from VLC AP $v$ to user $j$ on the VLC subchannel $q$, $v'$ ranges over other VLC APs that reuse subchannel $q$ to serve other users, denoted as $j'$, and $N_{\rm VLC}$ is the power spectral density of AWGN at the PD.
According to the block diagram in Fig.~\ref{mh} for data transmission in aggregated RF/VLC system, the achievable data rate of user $j$ is given as
\vspace*{-3mm}
\begin{equation}\label{adt}
R_j=\sum\limits_{\forall v}\sum\limits_{\forall q} R_{v,j}^q + \sum\limits_{\forall k, k\ne0}\sum\limits_{\forall m} R_{k,j}^m +\sum\limits_{\forall n} R_{0,j}^n,
\end{equation}
and the sum of the achievable rates in the three-tier heterogeneous network is calculated as $R_T=\sum\limits_{\forall j} R_j$. The total transmit power allocated to user $j$ is given by
\vspace*{-3mm}
\begin{equation}\label{adt}
P_j=\sum\limits_{\forall v}\sum\limits_{\forall q} p_{v,j}^q + \sum\limits_{\forall k, k\ne0}\sum\limits_{\forall m} p_{k,j}^m +\sum\limits_{\forall n} p_{0,j}^n,
\end{equation}
where the first, second, and third summation terms represent the total power consumed by the VLC, the picocell, and the macrocell APs, respectively. The total transmit power used to serve all users in the entire network is calculated as
\begin{equation}\label{tot}
P_T=P_{\rm PBS} \left( \left|{\mathcal{K}}\right| - 1\right) +P_{\rm MBS} + P_{\rm VLC}\left( \left|{\mathcal{V}}\right| \right) +\sum\limits_{\forall j} P_j,
\end{equation}
where $P_{\rm PBS}$, $P_{\rm MBS}$, and $P_{\rm VLC}$ denote the circuit power consumption for any picocell, macrocell, and VLC AP, respectively.
\section{Energy Efficiency (EE) Maximization Problem}\label{leemp}
The efficiency of any system is a measurable quantity determined by the ratio of its output to input. In the system model presented in Fig.~\ref{th}, efficiency can be seen as the extent to which the RF and VLC APs are assigned among the users, the available subchannels are allocated to the users, and the available transmit power to the RF and VLC APs are utilized to provide users with at least their required data rates. To that end, the EE [in bit/Joule] can be defined as the ratio of the amount of data transmitted to the amount of power consumed in the network. The considered EE maximization problem via the joint optimization of AP assignment, SA, and transmit PA can be formulated as in (\ref{eep}). Under this formulation, the variables to be optimized are the AP assignment vector ${\bf x}$, the SA vector ${\bf s}$, the transmit PA vector ${\bf p}$, and the outage vector ${\bf a}$, where user $j$ is said to be in an outage (i.e., $a_j=0$) if that user is not assigned any subchannel and $a_j=1$ means otherwise. Specifically, the AP assignment variables $x_{k,j}$ and $x_{v,j}$ denote the assignment of RF AP $k$ to user $j$ and that of VLC AP $v$ to user $j$, respectively. The SA variables $s_{k,j}^m$, $s_{0,j}^n$, and $s_{v,j}^q$ indicate the assignment of subchannel $m$ of picocell AP $k$ to user $j$, subchannel $n$ of the macrocell AP to user $j$, and subchannel $q$ of VLC AP $v$ to user $j$, respectively. Similarly, $p_{k,j}^m$, $p_{0,j}^n$, and $p_{v,j}^q$ represent the transmit power allocated by picocell AP $k$ to user $j$ on subchannel $m$, by the macrocell to user $j$ on subchannel $n$, and by VLC AP $v$ to user $j$ on subchannel $q$, respectively.
\setlength{\abovedisplayskip}{-15pt}
\begin{equation}\label{eep}
\begin{array}{l}
\mathop {\max }\limits_{{\bf x},{\bf p},{\bf s},{\bf a}} \eta=\frac{R_T}{P_T}\\
{\rm{s}}{\rm{.t}}{\rm{.}}\\
C1: s_{k,j}^m \le x_{k,j},\,\,\forall k,j,m,k\ne 0, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,C6: \sum\limits_{\forall k} x_{k,j}=1,\,\,\, \forall j,\\
\,\,\,\,\,\,\,\,\,\,\,\,s_{0,j}^n \le x_{0,j},\,\,\forall j,n, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,C7: \sum\limits_{\forall v} x_{v,j}\le 1,\,\,\, \forall j,\\
\,\,\,\,\,\,\,\,\,\,\,\,s_{v,j}^q \le x_{v,j},\,\, \forall v,j,q, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,C8: {\rm R}_j\ge {\rm R}_{\min}a_j,\,\,\, \forall j,\\
C2: p_{k,j}^m \le s_{k,j}^m P_k,\,\, \forall k,j,m,k\ne0, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, C9: p_{k,j}^m \ge 0, \,\, \forall k,j,m,k\ne0, \\
\,\,\,\,\,\,\,\,\,\,\,\,p_{0,j}^n \le s_{0,j}^n P_0,\,\,\forall j,n, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, p_{0,j}^n \ge 0, \,\,\forall j,n, \\
\,\,\,\,\,\,\,\,\,\,\,\,p_{v,j}^q \le s_{v,j}P_v,\,\, \forall v,j,q,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, p_{v,j}^q \ge 0, \,\, \forall v,j,q,\\
C3: \sum\limits_{\forall j}\sum\limits_{\forall m}p_{k,j}^m \le P_k,\forall k,k\ne 0, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, C10: s_{k,j}^m \in \{0,1\},\,\,\forall k,j,m,k\ne 0,\\
\,\,\,\,\,\,\,\,\,\,\,\,\sum\limits_{\forall j}\sum\limits_{\forall n}p_{0,j}^n \le P_0,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, s_{0,j}^n \in \{0,1\}, \,\, \forall j,n,\\
\,\,\,\,\,\,\,\,\,\,\,\,\sum\limits_{\forall j}\sum\limits_{\forall q}p_{v,j}^q \le P_v,\,\,\forall v, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\, s_{v,j}^q \in \{0,1\}, \,\, \forall v,j,q,\\
C4: \sum\limits_{\forall j} s_{k,j}^m \le 1,\,\,\forall k,m,k\ne 0, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,C11: x_{k,j} \in \{0,1\},\,\, x_{v,j} \in \{0,1\},\,\,\, \forall k,v,j,\\
\,\,\,\,\,\,\,\,\,\,\,\,\sum\limits_{\forall j} s_{0,j}^n \le 1,\,\,\forall n, \,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,\,C12: a_{j} \in \{0,1\},\,\, \forall j.\\
\,\,\,\,\,\,\,\,\,\,\,\,\sum\limits_{\forall j} s_{v,j}^q \le 1,\,\,\forall v,q,\\
C5: a_j \left(\left|{\mathcal{N}}\right|+\left|{\mathcal{M}}\right|+\left|{\mathcal{Q}}\right|\right) \ge \sum\limits_{\forall k,k\ne0}\sum\limits_{\forall m}s_{k,j}^m + \sum\limits_{\forall n}s_{0,j}^n + \sum\limits_{\forall v}\sum\limits_{\forall q}s_{v,j}^q,\,\, \forall j,\\
\end{array}
\vspace*{-5mm}
\end{equation}
The physical meaning of the constraints in (\ref{eep}) is explained as follows. Constraint $C1$ ensures that any subchannel of an AP can only be allocated to a user if that user is assigned to that AP. For example, considering the picocell AP $k$ and user $j$, the variable $s_{k,j}^m$ can take the value of $0$ or $1$ when $x_{k,j}=1$, and can only take the value of $0$ when $x_{k,j}=0$. Constraint $C2$ implies that the transmit power on each subchannel should not exceed the maximum value specified by $P_k$, $P_0$, and $P_v$, for picocell AP $k$, the macrocell AP, and VLC AP $v$, respectively. Moreover, $C2$ ensures that no power is allocated to any user on any subchannel if that particular subchannel is not assigned to that user. Constraint $C3$ is the transmit power budget for the APs. Constraint $C4$ guarantees that any subchannel of an AP is allocated to at most one user. Constraint $C5$ ensures that no more subchannels than available are allocated to user $j$. Constraints $C6$ and $C7$ ensure that each user is assigned to one RF AP and at most to one VLC AP, respectively. Constraint $C8$ guarantees the minimum QoS requirement, $R_{\min}$. It requires that the aggregate data rate of user $j$ not in an outage is constrained to be equal to or higher than $R_{\min}$. Constraints $C9$, $C10$, $C11$, and $C12$ are imposed to guarantee that the transmit power variables are non-negative, the SA variables are binary, the AP assignment variables are binary, and the outage variables are binary, respectively.
Problem (\ref{eep}) is unique for aggregated RF/VLC systems and has not been studied before. For instance, the problem requires that each user should be assigned to an RF AP and a VLC AP if that will impact the EE performance positively. However, a user assigned to an AP does not necessarily guarantee that any subchannel(s) will be allocated to that user from the AP as specified in constraint $C1$. Note that subchannels are scarce resources that should be utilized efficiently. Allocating them to any user when the channel condition is bad would require the AP to transmit at a higher transmit power to guarantee $R_{\min}$. This could result in high interference for users sharing the same subchannel. Moreover, the joint problem in (\ref{eep}) is difficult to solve directly due to the existence of both binary and continuous
variables, the non-convex SINR structure in the objective function, the coupling of the decision variables, the QoS requirement constraint, as well as the
fractional form of the objective function. This joint problem belongs to the class of mixed-integer nonlinear programming problems. To obtain the global optimal solution, a direct approach would involve an exhaustive search of all the possible AP assignment, SA, and PA combinations to find the solution that yields the highest EE performance. However, the computational complexity associated with the exhaustive search method is exponential and, as a result, infeasible in practice, even for small network sizes. Moreover, by decoupling this joint problem into three subproblems, each subproblem remains challenging to solve with conventional convex and quasi-convex optimization techniques. Specifically, the AP assignment and SA subproblems are combinatorial optimization problems, while the PA subproblem is challenging due to its non-convex structure.
The proposed approach involves separately optimizing the AP assignment, the SA, and the transmit PA subproblems in order to reduce the associated computational complexity and solve the EE optimization problem in (\ref{eep}) faster \cite{8891923,8314706,9411734}. The joint solution to (\ref{eep}) can therefore be obtained by either alternating among the three subproblems until convergence or by just solving the three subproblems once but in a successive fashion, as illustrated in Fig.~\ref{solf}. Simulation results will be used to compare these two approaches.
\begin{figure}
\centering
\includegraphics[width=0.5\textwidth]{sol_st}
\caption{Framework to obtain the joint solution: (a) alternating optimization; (b) non-alternating.}
\label{solf}
\vspace*{-7mm}
\end{figure}
\vspace*{-3mm}
\section{Energy-efficient AP Assignment and Subchannel Allocation (SA)}\label{leeaasa}
\vspace*{-2mm}
In this section, the AP assignment and the SA optimization subproblems are investigated, and practical solution approaches are proposed. More particularly, the AP assignment subproblem is considered first, and a matching algorithm based on MT \cite{7105641,Roth1990}, is proposed to assign APs to users such that the EE performance is maximized. Then, each AP allocates the available subchannels to users according to the quality of the channel conditions.
\vspace*{-5mm}
\subsection{Energy-efficient Access Point (AP) Assignment}
The proposed matching algorithm for the AP assignment subproblem is described in this subsection for any given transmit PA. The main idea of this matching algorithm is explained as follows. Firstly, the potential EE performance for user $j$ within the coverage range of the RF AP $k$ and the VLC AP $v$ is calculated as in (\ref{x2}) and (\ref{ees1}), respectively.
\vspace*{-2mm}
\begin{equation}\label{x2}
{\rm EE}_{k,j} = \left\{ \begin{array}{l}
\frac{B_{\rm RF} \log_2 \left( 1 + \frac{{\overline P}_k \left|{\overline G}_{k,j}\right|^2}{N_{\rm RF}B_{\rm RF}}\right)}{P_{\rm MBS}+P_k},\,\,{\rm if}\,\, k=0,\\\\
\frac{B_{\rm RF} \log_2 \left( 1 + \frac{{\overline P}_k \left|{\overline G}_{k,j}\right|^2 }{{ \sum\limits_{k'\ne {{k}}} {{\overline P}_{k'} { {{ \left|{\overline G}_{k',j}\right|^2 }} } } } + N_{\rm RF}B_{\rm RF} }\right)}{P_{\rm PBS}+P_k}, \,\,{\rm otherwise}.\\
\end{array} \right.
\end{equation}
\begin{equation}\label{ees1}
{\rm EE}_{v,j}=\frac{{ \overline{\rho}_{v,j} B_{\rm VLC} \log_2 \left({ 1 + {\frac{\exp(1)}{2\pi}} \frac{{\overline P}_v {\left( {{R_{\rm{PD}}}{\overline{G}_{v,j}}} \right)}^2} { {\sum\limits_{v'\ne v} {\overline P}_{v'} {\left( {{R_{\rm{PD}}}{\overline{G}_{v',j}}} \right)}^2 } + N_{\rm VLC}B_{\rm VLC}} } \right)}} {P_{\rm VLC}+P_v}.
\end{equation}
In (\ref{x2}), ${\overline P}_k$, which is obtained by dividing the total power by the number of subchannels, is a predetermined transmit power that each user is allocated when assigned to RF AP $k$ and ${\overline{G}_{k,j}}=\left(\sum\limits_{\forall m} G_{k,j}^m \right)/ \left|{\mathcal{M}}\right|$ is the average channel power gain between AP $k$ and user $j$ over all the AP's subchannels. In (\ref{ees1}), ${\overline P}_v$ is the predetermined transmit power that is allocated to any user that is assigned to VLC AP $v$, $\overline{\rho}_{v,j}=\left(\sum\limits_{\forall q} \rho_{v,j}^q \right)/ \left|{\mathcal{Q}}\right|$ is the average of the probability of LoS availability between AP $v$ and user $j$, and ${\overline{G}_{v,j}}=\left(\sum\limits_{\forall m} G_{v,j}^q \right)/ \left|{\mathcal{Q}}\right|$ is the average channel power gain between AP $v$ and user $j$. Note that the EE definitions in (\ref{x2}) and (\ref{ees1}) accurately capture the LoS blockages for the VLC links as well as ICI effects in the VLC and RF communication systems. Secondly, each of RF AP $k$ and VLC AP $v$ constructs a preference list (PL) by sorting ${\rm EE}_{k,j}$ and ${\rm EE}_{v,j}$ in decreasing order of $j$, respectively. Similarly, user $j$ builds a PL of the RF APs and VLC APs by sorting ${\rm EE}_{k,j}$ and ${\rm EE}_{v,j}$ in decreasing order of $k$ and $v$, respectively. For the RF system, the PL of APs and users is denoted by the set ${\mathcal L}_{\rm RF}=\left\{ {{\bf l}_{{\rm RF}_0}^{\rm UT}, \ldots ,{\bf l}_{{\rm RF}_k}^{\rm UT} \ldots ,{\bf l}_{{\rm RF}_{\left|{\mathcal{K}}\right| - 1}} ^{\rm UT}, {\bf l}_1^{\rm RF}, \ldots, {\bf l}_j^{\rm RF}, \ldots, {\bf l}_{\left|{\mathcal{J}}\right|}^{\rm RF} } \right\}$, where ${\bf l}_{{\rm RF}_k}^{\rm UT}$ denotes the preference relation of RF AP $k$ over the set of user terminals (UTs), while ${\bf l}_j^{\rm RF}$ represents the preference relation of user $j$ over the set of the available RF APs. Thus, the first user in ${\bf l}_{{\rm RF}_k}^{\rm UT}$ corresponds to $j^*=\arg \max_j {\rm EE}_{k,j},\,j\in {\mathcal{J}}$. Given RF AP $k$ and users $j_1,j_2\in {\mathcal{J}}$, it can be concluded that AP $k$ prefers $j_1$ to $j_2$ if $j_1$ precedes $j_2$ on AP $k$'s PL. For the VLC system, the PL of APs and users is denoted by the set ${\mathcal L}_{\rm VLC}=\left\{ {{\bf l}_{{\rm VLC}_1}^{\rm UT}, \ldots ,{\bf l}_{{\rm VLC}_v}^{\rm UT} \ldots ,{\bf l}_{{\rm VLC}_{\left|{\mathcal{V}}\right|}} ^{\rm UT}, {\bf l}_1^{\rm VLC}, \ldots, {\bf l}_j^{\rm VLC}, \ldots, {\bf l}_{\left|{\mathcal{J}}\right|}^{\rm VLC} } \right\}$, where ${\bf l}_{{\rm VLC}_v}^{\rm UT}$ and ${\bf l}_j^{\rm VLC}$ represent the preference relation of VLC AP $v$ over the set of UTs and user $j$ over the available VLC APs, respectively. Finally, the energy-efficient AP assignment can therefore be formulated as a 4-tuple $\left({\mathcal{K}},{\mathcal{J}}, {\mathcal{P}}_{\rm RF}, {\mathcal{L}}_{\rm RF} \right)$ and $\left({\mathcal{V}},{\mathcal{J}}, {\mathcal{P}}_{\rm VLC}, {\mathcal{L}}_{\rm VLC} \right)$, for the RF and VLC systems, respectively, with ${\mathcal{P}}_{\rm RF} = \left\{P_0,\ldots, P_k, \ldots, P_{{\mathcal K}-1} \right\}$ and ${\mathcal{P}}_{\rm VLC}=\left\{P_1,\ldots, P_v, \ldots, P_{\mathcal V}\right\}$ being the quotas for the RF and VLC APs, respectively, that indicate the available transmit power budget of each AP. It is desired to match the elements in the disjoint sets ${\mathcal{K}}$ and ${\mathcal{J}}$ for the RF system and ${\mathcal{V}}$ and ${\mathcal{J}}$ for the VLC system using the preference relations defined in ${\mathcal{L}}_{\rm RF}$ and ${\mathcal{L}}_{\rm VLC}$, respectively. Note that the AP assignment matching games for the RF and VLC systems can be implemented simultaneously and in parallel since our formulated matching game only considers the transmit power budgets.
A formal definition of this bilateral matching\footnote{The matching is bilateral because a user is associated with a given AP if and only if that AP is assigned to that user.} game is given as follows.
A one-to-many matching $\mu_{RF}$ $\left(\mu_{VLC}\right)$ is defined as a mapping from the set ${\mathcal K} \cup {\mathcal J}$ $\left({\mathcal V} \cup {\mathcal J} \right)$ into the set of all subsets of ${\mathcal K} \cup {\mathcal J}$ $\left({\mathcal V} \cup {\mathcal J} \right)$ such that for each $k\in {\mathcal K}$, $v\in {\mathcal V}$ and $j\in {\mathcal J}$:
\begin{enumerate}[(a)]
\item $\left|\mu_{\rm RF} \left( j \right) \right| = 1$ for every user $j$, where $\mu_{\rm RF} \left( j \right)=k$ denotes that user $j$ is assigned to RF AP $k$ at the matching $\mu_{\rm RF}$, and $\left|\mu_{\rm VLC} \left( j \right) \right| \le 1$ for every user $j$, where $\mu_{\rm VLC} \left( j \right)=v$ indicates that user $j$ is assigned to VLC AP $v$ at the matching $\mu_{\rm VLC}$.
\item $\left|\mu_{\rm RF} \left( k \right) \right| {\overline P}_k \le P_k$ for every RF AP $k$ and $\left|\mu_{\rm VLC} \left( v \right) \right| {\overline P}_v \le P_v$ for every VLC AP $v$.
\item $\mu_{\rm RF} \left( j \right)=k$ if and only if $\mu_{\rm RF} \left( k \right)=j$, and $\mu_{\rm VLC} \left( j \right)=v$ if and only if $\mu_{\rm VLC} \left( v \right)=j$.
\end{enumerate}
Condition (a) ensures that each user is matched to only one RF AP and at most to one VLC AP. Condition (b) guarantees that the total power allocated to the matched users by any RF and VLC APs does not exceed the available power budget (i.e., quota). Condition (c) states that if a user $j$ is matched to the RF AP $k$, this AP $k$ is also matched to the same user $j$, and the same can be said about the VLC APs. The QoS requirement defined in constraint $C8$ of (\ref{eep}) is not included in the AP matching game since the existence of $R_{\min}$ will severely restrict the matching of users and APs and, as a result, affect the quality of the solution obtained from the matching game. The QoS requirement is considered in the PA subproblem, where the users' $R_{\min}$ can be satisfied by adjusting the PA coefficients.
The proposed algorithm to solve this bilateral matching game and obtain the global optimal solution to the EE AP assignment subproblem is summarized in Algorithm~\ref{A1}. This matching procedure is assumed to be performed by a CCU located at the macrocell AP or in the cloud and provided with any required input data. In this algorithm, the CCU takes as input data the initial transmit power values, the average channel gain information, the LoS availability information, the PLs of both users and APs, and the quota of the APs, and delivers a final matching relation $\mu^*$. In the initialization stage, the CCU denotes the preference index of user $j$ as $t_j$ with $t_j=1, \forall j$ and also represents the waitlist of RF AP $k$ as ${\mathcal W}_k=\emptyset$ and VLC AP $v$ as ${\mathcal W}_v=\emptyset$. At the $t_j$-th iteration of the matching game, user $j$ proposes to match with its top-ranked AP and removes this AP from its PL (thus, this is done in parallel for the RF and VLC system). RF AP $k$ (VLC AP $v$) places on its waitlist ${\mathcal W}_k$ $\left({\mathcal W}_v \right)$ the top-ranked users such that the sum of their allocated transmit powers do not exceed RF AP $k$'s (VLC AP $v$'s) quota $P_k$ ($P_v$). Thus, the PL's size of any user reduces by one at the end of each iteration, and the second-ranked AP at the $t_j$-th iteration becomes the first ranked one at the start of the $t_j+1$-th iteration. During the $t_j+1$-th iteration, each user submits a proposal to its most preferred RF and VLC APs on their respective updated PLs. Once again, each AP selects the top-ranked user among the new applicants and those on its waitlist, then places the selected user on an updated waitlist while rejecting the rest. This matching procedure terminates when every user is either on a waitlist (i.e., ${\mathcal W}_k\ne\emptyset, \,k\in {\mathcal K}$ and ${\mathcal W}_v\ne\emptyset,\,v\in{\mathcal V}$) or has been rejected by every AP on its RF and VLC PLs (i.e., $l_j^{\rm RF}=\emptyset,\,l_j^{\rm VLC}=\emptyset,\,j\in{\mathcal J}$). At this point, each AP accepts the users on its waitlist, and a final stable matching ${\mu}^*$ has been obtained. The AP for all users can be computed from the final matching according to
\vspace*{-3mm}
\begin{equation}\label{msol}
{x_{k,j}^*} = \left\{ {\begin{array}{*{20}{l}}
{1,\,\, {\rm if}\, {\mu^* \left(j\right)}=k, \forall k\in{\mathcal K} }
\\
{0{\mkern 1mu} ,{\kern 1pt} {\mkern 1mu} {\kern 1pt} {\mkern 1mu} {\kern 1pt} {\mkern 1mu} {\kern 1pt} {\rm{otherwise}}{\rm{,}}}
\end{array}} \right. {\rm and}\,\,\,\, {x_{v,j}^*} = \left\{ {\begin{array}{*{20}{l}}
{1,\,\, {\rm if}\, {\mu^* \left(j\right)}=v, \forall v\in{\mathcal V} }
\\
{0{\mkern 1mu} ,{\kern 1pt} {\mkern 1mu} {\kern 1pt} {\mkern 1mu} {\kern 1pt} {\mkern 1mu} {\kern 1pt} {\rm{otherwise}}{\rm{,}}}
\end{array}} \right.
\end{equation}
for RF AP $k$ and VLC AP $v$, respectively.
\begin{algorithm}
\caption{Energy-efficient MT-based AP Assignment.}
\label{A1}
\begin{algorithmic}
\STATE {{\textbf{Input:}} ${\overline P}_k$, ${\overline G}_{k,j}$, $\overline{\rho}_{v,j}$, ${\overline P}_v$, $\overline{G}_{v,j}$, ${\mathcal L}_{\rm RF}$, ${\mathcal L}_{\rm VLC}$, ${\mathcal P}_{\rm RF}$, and ${\mathcal P}_{\rm VLC}$, with $k\in {\mathcal K}$, $j\in{\mathcal J}$, and $v\in{\mathcal V}$.}
\STATE {{\textbf{Initialization:}} Set iteration counter for user $j$ as $t_j=1$, and let the waitlists for the APs be denoted by ${\mathcal W}_k=\emptyset$ for RF AP $k$ and ${\mathcal W}_v=\emptyset$ for VLC AP $v$, with $k\in {\mathcal K}$, $j\in{\mathcal J}$, and $v\in{\mathcal V}$.}
\WHILE{$l_j^{\rm RF}\ne \emptyset$, $\forall j\in {\mathcal J}$ and ${\mathcal W}_k=\emptyset$, $\forall k\in {\mathcal K}$}
\STATE {(i) At the $t_j$-th iteration, user $j$ sends a proposal request to the $t_j$-th preferred RF AP in its PL (i.e., $l_j^{\rm RF}$) and clears that AP from the PL.}
\STATE {(ii) For each of the RF APs, AP $k$ considers all the proposal requests from the users and places on the waitlist ${\mathcal W}_k$ the highest-ranked users in its PL and rejects proposals when the quota $P_k$ is reached.}
\STATE {(iii) Set $t_j=t_j+1$.}
\ENDWHILE
\WHILE{$l_j^{\rm VLC}\ne \emptyset$, $\forall j\in {\mathcal J}$ and ${\mathcal W}_v=\emptyset$, $\forall v\in {\mathcal V}$}
\STATE {(i) At the $t_j$-th iteration, user $j$ sends a proposal request to the $t_j$-th preferred VLC AP in its PL (i.e., $l_j^{\rm VLC}$) and clears that AP from the PL.}
\STATE {(ii) For each of the VLC APs, AP $v$ considers all the proposal requests from the users and places on the waitlist ${\mathcal W}_v$ the highest-ranked users in its PL and rejects proposals when the quota $P_v$ is reached.}
\STATE {(iii) Set $t_j=t_j+1$.}
\ENDWHILE
\STATE {{\textbf {Output:}} The APs accept all users on the waitlists to form the stable matching $\mu^*$ and the AP assignment solution ${\bf x}^*$ can be computed from (\ref{msol}).
}
\end{algorithmic}
\end{algorithm}
\setlength{\textfloatsep}{29pt
\vspace*{-7mm}
\subsection{Analysis of Stability, Optimality, and Convergence}
\vspace*{-1mm}
In this subsection, the properties of the proposed matching algorithm for the energy-efficient AP assignment subproblem are analyzed. Before discussing the stability property, the definition of a {\textit{blocking pair}} is provided.
\textit{Definition 1:}
Any pair of user $j\in {\mathcal J}$ and RF AP $k\in{\mathcal K}$ or user $j\in {\mathcal J}$ and VLC AP $v\in{\mathcal V}$ is said to be a blocking pair if user $j$ and the RF AP $k$ or user $j$ and the VLC AP $v$ prefer each other over their partners in the current matching.
\textit{Definition 2:} A matching is stable if there is no blocking pair.
The above definition of stability implies that there is no pair of user and AP or an unhappy user or an unhappy AP that prefers being matched to each other or to another AP or to another user instead of being matched to their current partner.
The proposed matching algorithm in Algorithm~\ref{A1} is guaranteed to converge to a stable matching $\mu_{\rm RF}^*$ and $\mu_{\rm VLC}^*$ for the RF and VLC systems, respectively, for any stated preferences. The reason is that, at the end of Algorithm~\ref{A1}, user $j^*$ is matched with the top-ranked (i.e., most preferred) RF AP $k^*$ on its final updated PL, $l_{j^*}^{\rm RF}$, under the matching $\mu_{\rm RF} \left( j^* \right)$. For the VLC system, user $j^*$ is matched with the top-ranked AP $v^*$ on its final updated PL, $l_{j^*}^{\rm VLC}$, under the matching $\mu_{\rm VLC} \left( j^* \right)$. This matching is stable since RF AP $k$ (VLC AP $v$) that user $j^*$ originally ranked higher than $k^*$ ($v^*$) was deleted from the PL $l_{j^*}^{\rm RF}$ $\left(l_{j^*}^{\rm RF}\right)$ after user $j^*$ sent a proposal request and got rejected. Therefore, the final matching gives RF AP $k$ and VLC AP $v$ a user that it ranked higher than $j^*$. It can be concluded that Algorithm~\ref{A1} produces the stable matching $\mu_{\rm RF}^*$ and $\mu_{\rm VLC}^*$ which is not blocked by RF AP $k$-user $j$ pair and VLC AP $v$-user $j$ pair, respectively.
Algorithm~\ref{A1} is guaranteed to produce a matching that gives each user $j^*$ its highest ranked VLC AP $v^*$ and/or its highest ranked RF AP $k^*$ and, as a result, obtains the globally optimal AP assignment solution. This follows from the fact that the output of Algorithm~\ref{A1} is a stable matching. Thus, the proposed algorithm guarantees that the final matching gives users the APs that contribute to the highest network EE and only rejects the proposals of users that cannot be accepted by APs in any stable matching.
Finally, Algorithm~\ref{A1} is guaranteed to converge in a finite number of iterations, which is upper bounded by the number of APs, since no user sends more than one proposal request to any AP.
\vspace*{-5mm}
\subsection{Subchannel Allocation (SA) Scheme}
\vspace*{-1mm}
Having obtained the AP assignment solution from Algorithm~\ref{A1}, a low-complexity sub-optimal SA is proposed in this subsection. This scheme assigns any subchannel of an AP to a user based on the quality of the channel condition. A sub-optimal scheme is motivated because the optimal SA scheme, i.e., the exhaustive search, needs to search all possible combinations of users and subchannels for all APs and select the solution that maximizes the EE of the aggregated system. However, the task of enumerating all the candidate SA solutions dramatically increases the associated complexity of the exhaustive search. In comparison, the proposed SA scheme is more straightforward and can tackle the SA subproblem faster.
The main idea of the SA scheme is that the macrocell AP, any picocell AP $k\in{\mathcal K},k\ne0$, and any VLC AP $v\in{\mathcal V}$ should allocate any subchannel $n\in{\mathcal N}$, $m\in{\mathcal M}$, and $q\in{\mathcal Q}$, respectively, to the user with the highest channel power gain. For instance, the macrocell AP assigns subchannel $n$ to user $j^*$ (i.e., ${s_{0,j^*}^n}=1$) if $j^*=\mathop{\arg\max}_{j} { {G_{0,j}^n} }$. Similarly, picocell $k$ and VLC AP $v$ perform SA according to ${s_{k,j^*}^m}=1$ if $j^*=\mathop{\arg\max}_{j} { {G_{k,j}^m} }$ and ${s_{v,j^*}^q}=1$ if $j^*=\mathop{\arg\max}_{j} { {G_{v,j}^q} }$, respectively. Based on the SA solution ${\bf s}^*$, any user $j\in{\mathcal J}$ can be said to be in outage (i.e., $a_j=0$) if $\sum\limits_{n\in{\mathcal{N}}} s_{0,j}^n + \sum\limits_{m\in{\mathcal{M}}} s_{k,j}^m +\sum\limits_{q\in{\mathcal{Q}}} s_{v,j}^q =0$. Such user can later try to access the network via the network's admission control scheme.
\vspace*{-5mm}
\section{Energy-efficient PA Scheme: $\epsilon$-Constraint Approach}\label{eepsca}
\vspace*{-1mm}
Given the AP assignment and SA solutions, the transmit PA is optimized in this section to maximize the EE of the aggregated RF/VLC system. Specifically, the energy-efficient PA subproblem can be formulated as
\vspace*{-2mm}
\begin{equation}\label{eepa}
\begin{array}{l}
\mathop {\max }\limits_{\bf p} \eta=\frac{R_T}{P_T}\\
{\rm{s}}{\rm{.t}}{\rm{.}}\\
C2,\,C3,\,C8,\,{\rm and}\,\, C9.
\end{array}
\end{equation}
The PA subproblem above is non-convex since (i) the objective function is in a fractional form with respect to $\bf p$ and (ii) there are ICI terms in the rate function of the objective function and the QoS requirement in $C8$. Moreover, problem (\ref{eepa}) can be classified as a MOOP and is hard to solve in general since it involves two conflicting objectives, namely, maximizing the sum-rate while minimizing the total power consumption. Typically, there is no single global solution; rather, there is a set of acceptable trade-off optimal solutions called the {\textit{Pareto optimal set}} and corresponding objective function values called the {\textit{Pareto optimal frontier}}. A solution belongs to this set if no other solution can improve one of the objective functions without reducing the other objective function values.
Although the MOOP in (\ref{eepa}) can be converted into a single objective function (i.e., by rewriting the objective function into a parametric subtractive form) and then tackled by the well known Dinkelbach algorithm \cite{dink}, such an approach has several limitations including \cite{1599245}: 1) the objective function in a parametric subtractive form leads to only one solution and system engineers may desire to know all possible optimization solutions; 2) trade-offs between the objectives (i.e., sum-rate and total power) cannot be easily evaluated; and 3) the solution may not be attainable unless the search space is convex.
In this section, a low-complexity solution, based on the framework of the $\epsilon$-constraint method for MOOPs \cite{chir}, is proposed to discover the entire Pareto optimal frontier of (\ref{eepa}) that also contain the global optimal solution. The concept of {{\textit {Pareto dominance}}} is first introduced.
\textit{Definition 3 (Pareto dominance):} Given two solution vectors ${\bf p}^{\left(1\right)}$ and ${\bf p}^{\left(2\right)}$, ${\bf p}^{\left(1\right)}$ is said to {\textit {Pareto dominate}} ${\bf p}^{\left(2\right)}$, if and only if (i) solution ${\bf p}^{\left(1\right)}$ is no worse than ${\bf p}^{\left(2\right)}$ in all objectives, and (ii) solution ${\bf p}^{\left(1\right)}$ is strictly better than ${\bf p}^{\left(2\right)}$ in at least one objective. Thus, solution ${\bf p}^{\left(1\right)}$ is non-dominated by ${\bf p}^{\left(2\right)}$.
According to the $\epsilon$-constraint method, the EE optimization problem in (\ref{eepa}) can be cast as
\vspace{-6mm}
\setlength{\abovedisplayskip}{0pt}
\begin{equation}\label{eepab}
\begin{array}{l}
\mathop {\min }\limits_{\bf p} {P_T}\\
{\rm{s}}{\rm{.t}}{\rm{.}}\\
C2,\,C3,\,C8,\,C9,\\
C13: R_T\ge {\epsilon},\,\,
\end{array}
\end{equation}
where $\epsilon=\lambda\times R_{\max}$ with $\lambda\in (0,1]$ and $R_{\max}$ determined from
\vspace{-6mm}
\begin{equation}\label{eepac}
\begin{array}{l}
R_{\max}=\mathop {\max }\limits_{\bf p} {R_T}\\
{\rm{s}}{\rm{.t}}{\rm{.}}\\
C2,\,C3,\,C8,\,{\rm and}\,C9.
\end{array}
\end{equation}
In (\ref{eepab}), the numerator function (i.e., the sum-rate) of the original EE problem in (\ref{eepa}) has been transformed into the constraint $C13$ that requires that the sum-rate of the aggregated RF/VLC system, $R_T$, should be greater than or equal to $\epsilon$. Thus, $\epsilon$ represents a lower bound of the value of $R_T$. The motivation for moving the sum-rate term to the constraint set is because the achievable rate is a function of the transmit power and, as a result, the impact of the total power consumed on the EE is much more significant than that of the sum-rate. By choosing different values for $\lambda$ and repeatedly solving (\ref{eepab}), we can generate its complete Pareto optimal set \cite{chir}. Specifically, for any value of $\lambda$ (and $\epsilon$), the resulting problem with $C13$ divides the original feasible objective space into two portions, $R_T\ge \epsilon$ and $R_T< \epsilon$. The right portion becomes the feasible solution of the resulting problem stated in (\ref{eepab}). In this way, intermediate Pareto optimal solutions can be obtained for nonconvex objective space problems as the unique solution of the $\epsilon$-constraint problem stated in (\ref{eepab}) is Pareto optimal for any given lower bound $\epsilon$. To solve (\ref{eepab}), the value of $R_{\max}$ must be determined first by solving (\ref{eepac}), which is a sum-rate optimization problem. An approach for solving the non-convex problem in (\ref{eepac}) is proposed below.
\subsection{Determining $R_{\max}$}
Problem (\ref{eepac}) is highly intractable and non-convex because of the SINR terms in both the objective function and the constraint $C8$. To overcome this difficulty, the quadratic transform approach, originally proposed in \cite{fp}, is used to transform the fractional SINR terms into an equivalent non-fractional form. According to the quadratic transform technique, any SINR term in the RF system can be equivalently represented as
\vspace{-5mm}
\begin{equation}\label{qt1}
\begin{array}{l}
{\rm SINR}_{k,j}^m= 2y_{k,j}^m \sqrt{{p_{k,j}^m \left|G_{k,j}^m\right|^2}} -y_{k,j}^m \left({{\sum\limits_{j'\ne j} \sum\limits_{k'\ne {{k}}} {p_{k',j'}^{{m}} {{{ \left|G_{k',j}^m\right|^2 }} } } } + N_{\rm RF}B_{\rm RF} } \right),
\end{array}
\end{equation}
where $y_{k,j}^m$ is an auxiliary variable for the SINR term introduced by the application of the quadratic transform technique. For the VLC system, a similar transformation can be carried out according to
\vspace{-5mm}
\begin{equation}\label{qt2}
\begin{array}{l}
{\rm SINR}_{v,j}^q= 2y_{v,j}^q \sqrt{p_{v,j}^{q} {\left( {{R_{\rm{PD}}}{G_{v,j}^{q}}} \right)}^2} -y_{v,j}^q \left({\sum\limits_{j'\ne j} {\sum\limits_{v'\ne v} p_{v',j'}^{q} {\left( {{R_{\rm{PD}}}{G_{v',j}^{q}}} \right)}^2 } + N_{\rm VLC}B_{\rm VLC}} \right).
\end{array}
\end{equation}
By utilizing the SINR terms in (\ref{qt1}) and (\ref{qt2}) to calculate the achievable rate of any user as well as the sum-rate $R_T$, problem (\ref{eepac}) can be equivalently reformulated as
\vspace*{-4mm}
\begin{equation}\label{abn1}
\begin{array}{l}
R_{\max}=\mathop {\max }\limits_{{\bf p},{\bf y}} {R_T}\\
{\rm{s}}{\rm{.t}}{\rm{.}}\\
C2,\,C3,\,C8,\,{\rm and}\,C9.
\end{array}
\end{equation}
Although, (\ref{abn1}) remains non-convex in ${\bf p}$ and ${\bf y}$, it becomes a convex optimization problem when ${\bf y}$ is fixed and the optimal solution can be obtained using the CVX toolbox \cite{cvx}. For a fixed ${\bf p}$, the optimal solution for ${\bf y}$, denoted by $\hat{\bf y}$ can be obtained in closed form by solving
${\partial {{\rm SINR}_{k,j}^m}}/{\partial y_{k,j}^m}=0$ for the RF system and ${\partial {{\rm SINR}_{v,j}^q}}/{\partial y_{v,j}^q}=0$ for the VLC system. Specifically,
\begin{equation}\label{edas1}
\begin{array}{l}
{\hat y}_{k,j}^n=\frac{\sqrt{{p_{k,j}^m \left|G_{k,j}^m\right|^2}}} {{\sum\limits_{j'\ne j} \sum\limits_{k'\ne {{k}}} {p_{k',j'}^{{m}} {\left( {{ \left|G_{k',j}^m\right|^2 }} \right)} } } + N_{\rm RF}B_{\rm RF} },\,\,\,\,\,\,\,\,\,\,\,
{\hat y}_{v,j}^q=\frac{\sqrt{p_{v,j}^{q} {\left( {{R_{\rm{PD}}}{G_{v,j}^{q}}} \right)}^2}} {{\sum\limits_{j'\ne j} {\sum\limits_{v'\ne v} p_{v',j'}^{q} {\left( {{R_{\rm{PD}}}{G_{v',j}^{q}}} \right)}^2 } + N_{\rm VLC}B_{\rm VLC}}}.
\end{array}
\end{equation}
Then, the optimal ${p}$ for any fixed ${\bf y}$ can be obtained by solving the resulting convex problem in (\ref{abn1}). The proposed algorithm to determine the value for $R_{\max}$ is summarized in Algorithm~\ref{A3}.
\begin{algorithm}
\caption{Proposed Algorithm to Determine $R_{\max}$}
\label{A3}
\begin{algorithmic}
\STATE {Set the iteration counter $c=1$, maximum error tolerance $\varepsilon > 0$, $R_{\max}^{(c)} > \varepsilon$, $R_{\max}^{(0)} = 0$, and initialize ${\bf p}^{(c)}$ using the equal power assignment (EPA) scheme, where $p_{0,j}^n=\frac{P_0}{\left|{\mathcal{N}}\right|}$,\\ $p_{k,j}^m=\frac{P_k}{\left|{\mathcal{M}}\right|},\,\forall k,k\ne0,$ and $p_{v,j}^q=\frac{P_v}{\left|{\mathcal{Q}}\right|},\,\forall v$; }
\WHILE {$R_{\max}^{(c)} - R_{\max}^{(c-1)} > \varepsilon$}
\STATE {$c = c + 1$;}
\STATE {Calculate ${\bf y}^{(c)}$ using ${\bf p}^{(c-1)}$ and (\ref{edas1});}
\STATE {Solve the convex problem (\ref{abn1}) given ${\bf y}^{(c)}$ to obtain ${R_{\max}^{(c)}}$ and ${\bf p}^{(c)}$;}
\ENDWHILE
\STATE {{\textbf{Output:}} ${R_{\max}}$}.
\end{algorithmic}
\end{algorithm}
\setlength{\textfloatsep}{0pt
\vspace*{-4mm}
\subsection{Determining the EE Solution}
Given the value of $R_{\max}$ and any value for ${\lambda}$, the transmit power minimization problem in (\ref{eepab}) can be formulated as in (\ref{abt}) after replacing the SINR terms with their equivalent quadratic forms given in (\ref{qt1}) and (\ref{qt2}).
\begin{equation}\label{abt}
\begin{array}{l}
\mathop {\min }\limits_{{\bf p},{\bf y}} {P_T}\\
{\rm{s}}{\rm{.t}}{\rm{.}}\\
C2,\,C3,\,C8,\,C9,\,{\rm and}\,C13.
\end{array}
\end{equation}
In (\ref{abt}), the decision variables are the transmit power vector ${\bf p}$ and the auxiliary variable ${\bf y}$. It is non-convex in both ${\bf p}$ and ${\bf y}$
due to the constraints in $C8$ and $C13$. However, for a fixed ${\bf y}$, (\ref{abt}) becomes a convex optimization problem. On the other hand, the optimal solution for ${\bf y}$ can be determined using the closed form expressions in (\ref{edas1}). Thus, for any given value of $\lambda$ (and its corresponding $\epsilon$ value), problem (\ref{abt}) is solved by optimizing ${\bf p}$ and ${\bf y}$ in an alternating fashion until convergence. The proposed algorithm for solving (\ref{abt}) and obtaining the optimal EE solution, denoted by $\eta^*$, is summarized in Algorithm~\ref{A4}.
\begin{algorithm}
\caption{Proposed Algorithm to Solve ({\ref{eepa}})}
\label{A4}
\begin{algorithmic}
\STATE {{\textbf{Input:}} ${R_{\max}}$;}
\STATE {Set $\lambda=0$, step size $\mu=0.1$, outer iteration counter $t=1$, maximum error tolerance $\varepsilon > 0$, and $\gamma^{(0)} = 0$; }
\STATE {Create an empty non-dominated set ${\boldsymbol {\mathcal G}}$ and Pareto optimal front ${\boldsymbol \eta}$;}
\WHILE {$\lambda \le 1$}
\STATE {Set inner iteration counter $c=1$, the convergence parameter $\gamma^{(c)} > \varepsilon$, and initialize ${\bf p}^{(c)}$ using the EPA scheme; }
\STATE{Set $\lambda=\lambda+\mu$;}
\STATE {Calculate $\epsilon=\lambda{R_{\max}}$;}
\WHILE {$\gamma^{(c)} - \gamma^{(c-1)} > \varepsilon$}
\STATE {$c = c + 1$;}
\STATE {Calculate ${\bf y}^{(c)}$ using ${\bf p}^{(c-1)}$ and (\ref{edas1});}
\STATE {Solve the convex problem (\ref{abt}) given $\epsilon$ and ${\bf y}^{(c)}$ to update ${\bf p}^{(c)}$;}
\STATE {Set $\gamma^{(c)}$ to the objective function value of (\ref{abt});}
\ENDWHILE
\STATE{Calculate $\eta^{t} = \frac{{R}_T \left({\bf p}^{(c)}, {\bf y}^{(c)} \right) } {{P}_T \left({\bf p}^{(c)}, {\bf y}^{(c)} \right)} $;}
\STATE{Set ${\mathcal G}^{t}=\left({\bf p}^{(c)},{\bf y}^{(c)}\right)$};
\STATE{Update $t=t+1$;}
\ENDWHILE
\STATE {{\textbf{Output:}} ${\boldsymbol \eta}$, ${\boldsymbol {\mathcal G}}$}.
\end{algorithmic}
\end{algorithm}
\setlength{\textfloatsep}{15pt
In this algorithm, problem (\ref{abt}) is solved repeatedly for the different values of the $\epsilon$ vector. Specifically, by initially setting $\lambda=0$ and increasing it by a small step size $\mu$ such that $\lambda$ always has a positive value in the range of $(0,1]$, different values of $\epsilon$ can be generated according to $\epsilon=\lambda \times R_{\max}$. The values of $\lambda$ must be in the range of $(0,1]$ because:
\begin{enumerate}
\item If $\lambda=0$, $\epsilon=0$ and, as a result, (\ref{abt}) becomes a transmit power minimization problem without any constraint on the sum-rate (i.e., $C13$ becomes inactive). Since EE seeks to balance the total power consumed and the achievable rate simultaneously, it becomes imperative to consider the sum rate. Since this is not the case when $\lambda=0$, $\lambda$ must always have a value greater than 0.
\item If $\lambda>1$, $\epsilon>R_{\max}$ and, problem (\ref{abt}) becomes infeasible since, with the given transmit power budgets of the APs and according to (\ref{abn1}), the maximum attainable sum-rate in the aggregated RF/VLC system is $R_{\max}$. Hence, values of $\lambda$ greater than one are not considered.
\item If $\lambda=1$, $\epsilon=R_{\max}$, and problem (\ref{abt}) becomes a sum-rate maximization problem.
\item If $0<\lambda<1$, $0<\epsilon<R_{\max}$ and (\ref{abt}) turns out to be a MOOP.
\end{enumerate}
Based on the above discussions, values for $\lambda$ in 3) and 4) are used in the proposed algorithm. At the $t$-th iteration of the algorithm, problem (\ref{abt}) is solved for the given values of $\lambda$ and $\epsilon$ to obtain the optimal solution, which is stored as the vector ${\mathcal G}^{t}$ and the corresponding EE solution is denoted as $\eta^t$. Note that ${\mathcal G}$ is the non-dominated set of solutions for the problem in (\ref{eepa}). For any solution outside this set, we can always find a solution in ${\mathcal G}$ that will dominate the former. Thus, ${\mathcal G}$ has the property of dominating all other solutions that do not belong to this set. At the end of the algorithm, the different solutions in ${\mathcal G}$ form the Pareto optimal set. Since it is desired to obtain the best EE performance (i.e., most appropriate trade-off between sum-rate and total power consumption), the Pareto optimal solutions are ranked based on their corresponding objective function values, and the best is selected as the solution for the EE optimization problem in (\ref{eepa}). This solution is the global optimum since it is determined by solving the convex problems in (\ref{abn1}) and (\ref{abt}).
\vspace*{-5mm}
\subsection{Complexity of the EE Optimization Solution}
\vspace*{-1.5mm}
The overall complexity of the proposed joint solution for the energy-efficient AP assignment, SA, and transmit PA involves the computations involved in solving each subproblem. For a given SA and PA, the worst-case complexity of the energy-efficient AP assignment algorithm in Algorithm~\ref{A1} can be given as ${\mathcal O}\left( {\left|{\mathcal{J}} \right| \times S_{\rm AP} \times \log S_{\rm AP}} \right)+{\mathcal O}\left(\left|{\mathcal{J}}\right| \times S_{\rm AP} \right)\approx{\mathcal O}\left( {\left|{\mathcal{J}} \right| \times S_{\rm AP} \times \log S_{\rm AP}} \right)$, where $S_{AP}$ is the number of subchannels for each AP, the term
${\mathcal O} \left( {\left|{\mathcal{J}} \right| \times S_{\rm AP} \times \log S_{\rm AP}} \right)$ is the complexity for all users constructing their PLs using off-the-shelf sorting algorithms such as {\textit {merge}} sort and {\textit {quick}} sort, and the term ${\mathcal O}\left(\left|{\mathcal{J}}\right| \times S_{\rm AP} \right)$ is the complexity of all users proposing to the subchannels of the APs assigned to them.
For any given AP assignment and PA, the worst-case complexity of the proposed SA procedure for each AP is ${\mathcal O}\left(\left|{\mathcal{K}} \cup {\mathcal{V}} \right| \times \left|{\mathcal{J}}\right| \times S_{\rm AP} \right)$. In comparison to the optimal SA procedure (i.e., exhaustive search) which has a computational complexity of ${\mathcal O}\left(\left(\left|{\mathcal{K}} \cup {\mathcal{V}} \right| \right) S_{\rm AP}!\times 2^{{\mathcal{J}}} \right)$, the proposed SA scheme has significantly lower complexity.
With regards to the PA subproblem for any given AP assignment and SA, the associated computational complexity comes from solving (\ref{abn1}) and (\ref{abt}). Since (\ref{abn1}) and (\ref{abt}) are convex problems for any given ${\bf y}$, and by following the standard convex analysis in \cite{boyd}, Algorithms~\ref{A3} and \ref{A4} have a polynomial time complexity in terms of the number of variables (i.e., $\left|{\mathcal{J}}\right| \times S_{AP}$) and constraints (i.e., $\left|{\mathcal{J}}\right|\left(S_{AP}+1\right)+ \left|{\mathcal{K}} \cup {\mathcal{V}} \right|$). From the above complexity analysis, the proposed resource allocation scheme, including AP assignment, SA, and transmit PA, has a polynomial-time worst-case complexity.
\vspace*{-4mm}
\section{Simulation Results}\label{srs}
\vspace*{-0.5mm}
In this section, the performance of the proposed AP assignment, SA, and PA optimization algorithm is investigated in terms of the EE, the sum-rate, and the outage performances of the aggregated RF/VLC system. The macrocell AP is located at the center of the macrocell and has a cell radius of 500 m. The picocell and the VLC APs are randomly and uniformly deployed overlaying the macrocell. Each picocell has a coverage radius of 100 m, and each VLC indoor environment is a room with an area of $5 \times 5$ m$^2$. Each VLC environment has two APs, deployed at the height of 2.15 m, with overlapping coverage to guarantee uniform illumination across the room. The total transmit power for the macrocell AP, each picocell AP, and each VLC AP is 46 dBm, 30 dBm, and 30 dBm, respectively. Each AP has 50 subchannels, with a subchannel bandwidth of 20 MHz and 10 MHz for the VLC and RF systems, respectively. The minimum rate requirement of each user is set as $50$ Mbps. The remaining system model parameters are summarized in Table~\ref{tab1}. The following benchmark schemes and configuration are considered for comparison:
\begin{table*}[t]
\centering
\caption{Simulation Parameters}
\label{tab1}
\begin{tabular}{|ll|ll|}
\hline
\multicolumn{2}{|c|}{\textbf{RF system}} & \multicolumn{2}{c|}{\textbf{VLC system}} \\ \hline
\multicolumn{1}{|l|}{\textbf{Parameter}} & \textbf{Value} & \multicolumn{1}{l|}{\textbf{Parameter}} & \textbf{Value} \\ \hline
\multicolumn{1}{|l|}{Noise power spectral density, $N_{\rm RF}$} & -174 dBm/Hz & \multicolumn{1}{l|}{Physical area of PD, $A_{\rm PD}$} & 1 cm$^2$ \\ \hline
\multicolumn{1}{|l|}{Log-normal shadowing standard deviation, $X_{\sigma}$} & 10 dB & \multicolumn{1}{l|}{LED semi-angle at half-power, ${{\phi _{{1}/{2}}}}$} & $60^{\circ}$ \\ \hline
\multicolumn{1}{|l|}{Multipath fading type} & Rayleigh fading & \multicolumn{1}{l|}{Gain of the optical filter, $T\left( {{\psi _{v,j}}} \right)$} & 1 \\ \hline
\multicolumn{1}{|l|}{Circuit power consumption, $P_{\rm PBS}$} & 6.8 W \cite{6056691} & \multicolumn{1}{l|}{Refractive index, $f$} & 1.5 \\ \hline
\multicolumn{1}{|l|}{\multirow{4}{*}{Circuit power consumption, $P_{\rm MBS}$}} & \multirow{4}{*}{130 W \cite{6056691}} & \multicolumn{1}{l|}{PD responsivity, $R_{\rm PD}$} & 0.53 A/W \\ \cline{3-4}
\multicolumn{1}{|c|}{} & & \multicolumn{1}{l|}{FOV of a PD, ${\psi _{{\rm{FoV}}}}$} & $70^{\circ}$ \\ \cline{3-4}
\multicolumn{1}{|c|}{} & & \multicolumn{1}{l|}{Circuit power consumption, $P_{\rm VLC}$} & 4 W \\ \cline{3-4}
\multicolumn{1}{|c|}{} & & \multicolumn{1}{l|}{Noise power spectral density, $N_{\rm VLC}$} & $10^{-21}$ A$^2$/Hz \\ \hline
\end{tabular}
\vspace*{-1mm}
\end{table*}
\begin{itemize}
\item SCG-SCG-EPA scheme: This scheme assigns APs to users based on the strongest channel power gain (SCG) rule. The available subchannels and power are allocated according to the SCG rule and the EPA policy, respectively, for the users assigned to an AP.
\item Baseline scheme: This scheme has been adopted from \cite{8314706}, in which the authors proposed an SA and PA procedure for an aggregated RF/VLC system under the assumption that users are assigned to the AP with the SCG. Specifically, the AP assignment scheme is according to the SCG rule, the SA scheme is according to Algorithm~2 of \cite{8314706}, and the PA scheme is per our proposed energy-efficient PA scheme.
\item Hybrid RF/VLC: In this configuration, each user is only assigned a macrocell AP or a picocell AP or a VLC AP (i.e., $\sum\limits_{\forall k} x_{k,j} + \sum\limits_{\forall v} x_{v,j}=1,\,\forall j$). The proposed iterative solution for the joint problem is adopted for this configuration.
\end{itemize}
Figure~\ref{res0} shows the convergence of the proposed joint solution as demonstrated in Fig.~\ref{solf}(a). It can be seen that the proposed approach converges to a stationary point after 6 iterations.
Figure~\ref{reexs1} illustrates the EE performance gap between the proposed scheme and the globally optimal solution obtained via exhaustive search. As can be seen, the average gap between the proposed and the exhaustive scheme is around $5\%$. This indicates that the proposed sub-optimal scheme approaches the globally optimal solution while offering a practical solution to the joint optimization problem of AP assignment, SA, and transmit PA.
\begin{figure}[!t]
\centering
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=1.1\linewidth]{convergence_plt}
\caption{Convergence of the proposed iterative joint solution.}
\label{res0}
\end{minipage}%
\hfill
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=1.1\linewidth]{extsch1}
\caption{EE comparison of the proposed and the global optimal scheme.}
\label{reexs1}
\end{minipage}
\vspace*{-2mm}
\end{figure}
Figure~\ref{res1} illustrates the average EE performance of the proposed iterative and non-iterative energy-efficient resource allocation schemes, the considered benchmarks, and the hybrid system for varying numbers of users. It can be seen that the proposed schemes outperform the two benchmarks and the hybrid RF/VLC system, and the EE performance improves as the number of users increases for all schemes. This is because the proposed approaches make use of the EE's definition and consider ICI effects when assigning APs to users and during the optimization of the transmit APs' transmit power to users. The energy-efficient MT-based AP assignment scheme in Algorithm~\ref{A1} can assign APs to users under a given PA, such that the overall best EE performance is achieved through the use of preference relations among users and APs. Once the users have been associated with the APs that guarantee the highest EE, the low-complexity SCG rule-based SA procedure efficiently allocates any subchannel of an AP to the user with the best channel condition. After the SA step, the proposed energy-efficient PA scheme is used to update the transmit power to the users. Thus, both the AP assignment and PA schemes of our proposed solution to the EE optimization problem consider the objective function definition and the ICI effects in their decision-making processes. In contrast, the baseline approach does not consider users' EE performance when assigning APs since it uses the SCG rule to assign APs to users. Moreover, the SA policy of the baseline approach focuses more on ensuring that the required minimum rate is guaranteed for all users since it first allocates subchannels to users to guarantee their QoS requirements.
Note that this results in a trade-off between assigning subchannels to users with the best channel condition and assigning subchannels to improve fairness among users. Specifically, the baseline scheme can assign a subchannel to a user with a relatively worse channel condition to meet the QoS requirement. This can cause the AP to transmit at a higher power level on that subchannel and thus generate significant interference to nearby users being served on that same subchannel. The SCG-SCG-EPA scheme performs worst since it does not consider the definition of EE and ICI effects when assigning APs to users, allocating subchannels, and allocating transmit power. Between the two joint solution approaches, it can be observed that alternating among the AP assignment, SA, and PA subproblems (i.e., the iterative approach) results in a superior EE performance when compared with the non-iterative approach. However, this performance improvement is obtained at the expense of an additional number of iterations. Moreover, the rate of increase in the EE decreases for all schemes with an increasing number of users due to the resulting stronger impact of ICI. The hybrid RF/VLC system performs worse than the aggregated system (except with the SCG-SCG-EPA scheme). This is because there are more available options for the aggregated system (i.e., there is better exploitation of the available resources) as the users can receive data transmission from both RF and VLC APs.
\begin{figure}[!t]
\centering
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=1.1\linewidth]{EE_UEss}
\caption{Average EE versus the total number of users.}
\label{res1}
\end{minipage}%
\hfill
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=1.1\linewidth]{RF_UEss}
\caption{Average sum-rate versus the total number of users.}
\label{res2}
\end{minipage}
\vspace*{-2mm}
\end{figure}
Figure~\ref{res2} shows the average sum-rate performance of the proposed schemes, the two benchmarks, and the hybrid RF/VLC system for a varying number of users. Clearly, the proposed schemes outperform the two benchmarks in terms of the average sum-rate, revealing the benefit of jointly optimizing the AP assignment, SA, and PA. Moreover, the sum-rate performance improves with increasing number of users for all four schemes. This is because increasing the number of users for a fixed number of subchannels and transmit power budget expands the feasible region of the considered optimization problem. However, the rate of increase for the baseline scheme decreases after a total of 140 users. This behavior is due to the SA policy used by the baseline scheme. More precisely, this policy fails to exploit all users' channel power gain differences, especially for a more significant number of users, since it always focuses on satisfying the QoS requirements of all users first.
The performance of the aggregated system (with the proposed schemes) is significantly better than the hybrid system because of the multi-homing capability of the users' receiving devices. Specifically, any user served simultaneously by an RF AP and a VLC AP can have communication links with better channel conditions with at least one AP. This can lead to an improvement in the achieved data rate. Since the proposed iterative approach outperforms the non-iterative approach and the hybrid RF/VLC system, the proposed iterative approach is considered in this paper's remaining EE performance analyses.
\begin{figure}[!t]
\centering
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=1.1\linewidth]{EE_Rmins}
\caption{Average EE versus the required minimum rate.}
\label{res5}
\end{minipage}%
\hfill
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=1.1\linewidth]{EE_Prob}
\caption{Average EE for different values of the probability of LoS communication.}
\label{res6}
\end{minipage}
\vspace*{-2mm}
\end{figure}
Figure~\ref{res5} depicts the average EE of the aggregated RF/VLC system versus the required minimum rate, which is varied from 50 Mbps to 1 Gbps. It can be observed that the average EE decreases as the required minimum rate value increases for both the proposed and the baseline schemes. This can be explained by the fact that increasing the value of $R_{\min}$ restricts the feasible region of the EE optimization problem. However, the trend grows much slower (especially between 50 to 125 Mbps) for the proposed solution compared to the baseline approach. This indicates the ability of our proposed approach to cope very well with higher users' rate requirements. On the contrary, increasing the minimum rate requirements of users does not affect the EE curve for the SCG-SCG-EPA scheme since the value of $R_{\min}$ is never used in the assignment of APs or the allocation of power and subchannel resources by this naive scheme.
Figure~\ref{res6} demonstrates how the existence of LoS communication links between VLC APs and users influences the EE performance of the proposed solution and the two benchmarks. The labels on the x-axis of this figure are defined as follows: ``Very low'' indicates that the probability of an LoS path is between 0 and 0.3; ``Low'' means the probability is between 0.3 and 0.5; ``Medium'' means the probability is between 0.5 and 0.8; ``High'' means the probability is between 0.8 and 1. Note that such labels allow the probability of an LoS scenario to vary among the various users and the access points, which depicts the fact that the VLC channel changes with changing the location of the receivers. The figure reveals that LoS path blockage affects the EE performance of all the considered schemes as it considerably impacts the propagation environment. Specifically, when the probability of having an LoS path is low, users are less likely to be served by the AP that can provide the highest EE. This would lead to a reduction in the overall EE. The proposed scheme has the best EE performance for the different scenarios considered.
\begin{figure}[!t]
\centering
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=1.1\linewidth]{OT_UEss}
\caption{Average number of users in outage versus the total number of users.}
\label{res3}
\end{minipage}%
\hfill
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=1.1\linewidth]{EE_CP}
\caption{Average EE versus the circuit power consumption.}
\label{res4}
\end{minipage}
\vspace*{-2mm}
\end{figure}
Figure~\ref{res3} shows the average number of users whose QoS requirements cannot be guaranteed by the three schemes versus the total number of users. The SCG-SCG-EPA scheme has the highest number of users in outage since this scheme does not take
into consideration users' minimum rate requirements when allocating the available resources. The hybrid system performs worst compared with the proposed and baseline schemes since users with relatively bad channel conditions and assigned to an AP may not be allocated any subchannel. As a result, their QoS requirements cannot be guaranteed. However, this is not the case in the aggregated system since users can receive from both RF and VLC APs to realize additional data rates to meet their QoS requirements. The baseline scheme outperforms the proposed approach since it prioritizes satisfying the minimum rate requirement of all users first by allocating subchannel resources to them such that the $R_{\min}$ value is achieved for most or all users. Moreover, the outage increases with increasing users for all schemes due to increased competition for the limited resources.
Figure~\ref{res4} indicates the average EE performance of the proposed scheme, the baseline scheme, and the SCG-SCG-EPA scheme when the values of the circuit power consumption for the macrocell, picocell, and VLC APs are varied. Note that the range of the considered circuit power values lies within the typical practical ranges for MBSs \cite{6056691}, PBSs \cite{6056691}, and VLC APs \cite{7437374}. It can be observed that the EE decreases for all the schemes as the circuit power consumption increases for the macrocell, picocell, and VLC APs. This observation is in line with the definition of the system EE. Hence, future designs should focus on hardware components with lower circuit power consumption.
\vspace*{-4mm}
\section{Conclusion}\label{ccs}
This paper has investigated EE optimization for aggregated RF/VLC systems by jointly optimizing AP assignment, SA, and PA. More specifically, the original EE optimization problem, which belongs to the class of mixed-integer nonlinear programming problems and is generally intractable, has been decoupled into AP assignment, SA, and transmit PA subproblems. A solution technique has been proposed for each, and two frameworks to obtain the joint solution have been introduced. A novel energy-efficient AP assignment scheme has been developed by invoking MT. Additionally, a simple yet efficient SA scheme has been designed based on the AP assignment result. Given the AP assignment and SA solutions, a PA algorithm based on the quadratic transform approach and from the viewpoint of multi-objective optimization has been proposed. Simulation results have demonstrated the effectiveness of the proposed algorithms. They have revealed the superior EE and sum-rate performances of aggregated RF/VLC systems compared with hybrid systems and existing schemes. Moreover, the impact of critical system parameters, such as the circuit power consumption, users' QoS requirements, and LoS availability for the VLC links, on the performance of the aggregated RF/VLC system has been examined. This paper has revealed that the considered aggregated system and the proposed algorithms can effectively combine resources from both RF and VLC APs to enhance the EE, sum-rate, and outage performances while offering ubiquitous connectivity solution to users. Interesting problems for future work in this area include developing techniques for supporting mobile users and for VLC LoS blockage-aware resource allocation in aggregated systems.
\bibliographystyle{IEEEtran}
| {'timestamp': '2022-06-06T02:14:31', 'yymm': '2206', 'arxiv_id': '2206.01567', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01567'} | arxiv |
\section{Introduction}
With the continuous advancement of machine learning methodologies and increasing availability of dedicated software and hardware, data-driven approaches have gained popularity across many different fields such as finance, medicine, science, and engineering. Across these disciplines, one important topic of interest is describing how a dynamical system changes through time to predict its future state \cite{devaney2018introduction}. While some dynamical systems can be predicted through traditional physics-based modeling, there are many real-world examples of systems with unpredictable or chaotic behavior \cite{hernandez2018chaotic,wang2019neural}. There are many different approaches for predicting and describing chaotic systems such as physics-based modeling, deep learning, physics-informed machine learning, deep operator inference (DeepONets), and operator inference (OpInf).
Physics-based models describing chaotic systems mainly rely on complex partial differential equations (PDEs) that require a tremendous amount of computational power running continuously on high-performance computing (HPC) infrastructure to be solved. Moreover, the systems' non-stationarities, nonlinearities, and intermittency make them intractable from a deterministic standpoint, rendering long-term forecasting unrealistic \cite{wang2019neural}. Reduced-order models (ROMs) aim to solve the computational complexity issue by creating a low-rank representation of the original system that is capable of accurately approximating its full spatiotemporal evolution \cite{brunton2019data,peherstorfer2016data}. This allows significant improvements in computational speed due to the lower number of variables at stake\cite{mohan2018deep,brunton2019data}.
ROMs are typically classified into two types: intrusive and non-intrusive. Intrusive ROMs project the high fidelity full order models (FOM) to a low-dimensional subspace through techniques such as proper orthogonal decomposition (POD) \cite{yildiz2021reduced}. They require access to the differential operators of the FOM to compute the reduced operators. This means that the solution is exclusive to the equation studied, thus, nongeneralizable. Non-intrusive methods have no such drawback; they adopt a data-driven approach where snapshots, i.e. measurements of the states of the dynamical system, are used to learn the ROM \cite{peherstorfer2016data,yildiz2021reduced}. Therefore, non-intrusive approaches can be applied in settings where the FOM operators are unavailable such as in the case of proprietary simulation software \cite{mcquarrie2021data,ghattas2021learning}.
An alternative approach for physics-based ROMs is deep learning methods. These methods circumvent the massive online computational requirements for solving PDEs by leveraging the offline training capacity of artificial neural networks with many hardware architectures such as GPUs, TPUs, CPUs, and cloud services \cite{wang2019neural}. However, one also expects challenges during the offline process such as long training time, availability of RAM, hyperparameter optimization, and scaling for large datasets. Parallelization schemes, such as the one implemented by \cite{vlachas2020backpropagation,pathak2018model}, can mitigate the scaling problem by training multiple models simultaneously. These parallel schemes for ROMs incorporate two extra hyperparameters associated with the training subset sizes and the communication band between neighboring subsets which makes the convergence to an optimal ROM harder. Parallel models are prone to produce less representative ROMs since they strongly depend on additional hyperparameter tuning \cite{vlachas2020backpropagation,nogueira2021reservoir}.
Physics-informed neural networks (PINNs) aim to improve upon traditional neural networks by imposing physical constraints that must be satisfied. These networks are composed of two parts. The first one is a neural network that works as an approximation function that receives time and space coordinates as input providing an approximate solution $\hat{u}$ of a given PDE. The second part takes the object $\hat{u}$ and applies automatic differentiation (AD) over it to compute the residual format of the PDE which, together with its corresponding boundary (BC) and initial conditions (IC), are plugged in the neural network loss function. Thus a multi-task learning problem is set through a composite loss function that aims to fit any available data while minimizing the residuals of the PDE, BCs, and ICs. The PDE residual, BC, and IC terms in the loss function act as regularization terms discarding unrealistic solutions and consequently constraining the space of admissible solutions to those that adhere to the imposed physical laws \cite{raissi2019physics}.
PINNs have many advantages compared to traditional deep learning: less data is required, a faster training process, and better extrapolation capacity \cite{guo2020solving}. The downsides, however, are that its architecture is not generalizable due to the physics embedding being unique to the problem considered, together with convergence rate and computational cost issues \cite{wang2021understanding,wang2021improved}. Recent advances such as the incorporation of Neural Tangent Kernel \cite{wang2021improved} approach, tailored architectures \cite{wang2021improved} and variational formulations \cite{kharazmi2019variational} represent great strides to overcome the stability and generalization issues of PINNs. Those techniques are key enabling features to make PINNs suitable for a wider range of real-world applications.
Deep Operator Networks (DeepONets) are a new class of machine learning frameworks that can learn nonlinear operator mapping between infinite-dimensional Banach spaces. These frameworks are built upon the generalized universal approximation theorem for operators ensuring that nonlinear operators that map input entities to the corresponding latent space solutions of a given PDE can be learned \cite{lu2021deeponet}. Although they provide a simple and intuitive model architecture, they require large amounts of high-fidelity data to be trained, whereas the learned operator may not be consistent with the underlying physical laws of the system \cite{wang2021learning}. Since the output of DeepONets is differentiable with respect to the input coordinates, they also inherit the basic properties of PINNs. Both can be combined in a single physics-informed DeepONet framework. Such a combination can regularize the target output satisfying physical constraints through its loss function, which can lead to higher data efficiency and improved accuracy \cite{wang2021understanding}.
The non-intrusive Operator inference (OpInf) technique proposed in \cite{peherstorfer2016data} is another particularly suitable approach within the broad class of operator learning methods since it offsets some of the disadvantages of intrusive ROMs and deep learning schemes. The non-intrusive nature of OpInf leads to a more general and explainable model compared to intrusive ROMs and standard deep learning architectures while having much fewer hyperparameters and a quite straightforward training procedure. Such features make the method pretty affordable and efficient since it doesn't rely on minimizing loss functions through gradient descent like DeepONets or other kinds of deep neural networks. The method learns the operators by solving a simple least-squares regression problem (more details in section \ref{sec_opinf}).
In a previous work, the authors applied echo state networks (ESN) alongside ROMs to capture the most relevant features of chaotic dynamical systems and analyzed their forecasting capability \cite{nogueira2021reservoir}. The benchmark chaotic systems Lorenz 63/96 and the GEOS Composition Forecasting (GEOS-CF) dataset for atmospheric pollutants over the continental United States were used as examples. For the Lorenz 63 and 96, the ESN showed remarkable forecasting feature up to 11.8 and 22.8 Lyapunov time units respectively. For the GEOS-CF dataset, ESN showed fair results with pointwise errors of about 15\% for a target 44-hour time horizon. However, that model was unable to perform long-term recursive predictions, being effective only as a single step ahead predictor. In this case, the ROM could reduce the number of dimensions from $24,000$ to $200$ while maintaining 99\% of the system's total energy but showed a limited performance due to a lack of any physical driven mechanism, which turned the extrapolation process of the reduced time series quite hard. Such behavior demonstrated that even in reduced space with $200$ dimensions, a pure data-driven machine learning approach based on ESN can fail in a long-term extrapolation regime. While machine learning approaches deal well with classical chaotic systems, they are still not quite generalizable to more realistic systems. Such empirical evidence clearly showed the need to further explore physics-driven machine learning schemes.
Aiming at demonstrating the suitability of physics-inspired ROMs over pure machine learning-based ROMs to forecast canonical chaotic systems \cite{vlachas2020backpropagation}, this work focuses on demonstrating the effectiveness of applying OpInf to the classical Lorenz 96 and Kuramoto-Sivashinsky chaotic systems. The main contributions of this work are described below:
\begin{itemize}
\item The assessment of long-term forecasting features of Operator Inference (OpInf) technique for benchmark chaotic systems, namely, Lorenz 96 and Kuramoto-Sivashinsky equation.
\item An improved parallelization scheme for decomposing the original data matrices used for solving the OpInf least-squares problem in batches.
\end{itemize}
\section{Lorenz 96}
\label{sec:Lorenz}
The Lorenz 96 equations are a 3-tier extension of the original Lorenz 63 model, resulting in three coupled nonlinear ODEs. Such system of equations are shown below:
\begin{align}
\frac{d X_{k}}{d t} &=X_{k-1}\left(X_{k+1}-X_{k-2}\right)+ F-\frac{h c}{b} \, \Sigma_{j} Y_{j, k} \label{eq:1_Lorenz} \\
\frac{d Y_{j, k}}{d t} &=-c \, b \, Y_{j+1, k}\left(Y_{j+2, k}-Y_{j-1, k}\right)-c \, Y_{j, k} + \frac{h c}{b} \, X_{k}-\frac{h e}{d} \, \Sigma_{i} Z_{i, j, k} \label{eq:2_Lorenz} \\
\frac{d Z_{i, j, k}}{d t} &=e \, d \, Z_{i-1, j, k}\left(Z_{i+1, j, k}-Z_{i-2, j, k}\right)-g \, e \, Z_{i, j, k} + \frac{h e}{d} \, Y_{j, k} \label{eq:3_Lorenz}
\end{align}
This improved model encompasses additional features to its predecessor Lorenz 63 including a large-scale forcing $F$ that makes the system highly chaotic and a set of constant coefficients $b, c, d, e, g, h$ that can be tuned to produce appropriate spatiotemporal variability in all state variables $X_{k},Y_{j, k}$ and $Z_{i, j, k}$. Lorenz 96 was designed to model the large-scale behavior of the mid-latitude atmosphere \cite{chattopadhyay2020data}. The numerical setup of this problem is outlined in section \ref{res:lor}.
\section{Kuramoto–Sivashinsky equation}\label{sec:KS}
The Kuramoto–Sivashinsky (KS) equation was developed almost simultaneously by Yoshiki Kuramoto and Gregory Sivashinsky while studying the turbulent state in a chemical reaction system \cite{kuramoto1978diffusion} and the hydrodynamic instability in laminar flames \cite{sivashinsky1977nonlinear}. This equation can be written as:
\begin{equation}
\frac{\partial u}{\partial t} + u\frac{\partial u}{\partial x} + a\frac{\partial^2 u}{\partial x^2} + b\frac{\partial^4 u}{\partial x^4} = 0 \label{eq_kuramoto}
\end{equation}
The parameters $a$ and $b$ in Equation \ref{eq_kuramoto} were both chosen as unitary. We considered a smooth initial condition for the KS system, which is shown in Equation \eqref{ks_boundary}, and periodic boundary conditions that match the periodicity of the initial condition. The boundary conditions are given by Equations \eqref{periodic1}, \eqref{periodic2}, \eqref{periodic3}.
\begin{equation}
u(0,x) = cos\left(\frac{\pi x}{20}\right)\left[1+sin\left(\frac{\pi x}{20}\right)\right]\label{ks_boundary}
\end{equation}
\begin{equation}
u(t,0) = u(t,L) \label{periodic1}
\end{equation}
\begin{equation}
u_x(t,0) = u_x(t,L) \label{periodic2}
\end{equation}
\begin{equation}
u_{xx}(t,0) = u_{xx}(t,L) \label{periodic3}
\end{equation}
The numerical setup and parameters used in solving Kuramoto-Sivashinsky's equation are detailed in section \ref{res:ks}.
\section{Operator inference}\label{sec_opinf}
Operator inference (OpInf) provides a non-intrusive way of creating ROMs by learning the physical operators of the FOM in latent space by solving a least-squares optimization problem \cite{yildiz2021reduced}. Given measurements of the full order model, an approximate output operator that describes the mapping from the full state to the outputs is found \cite{peherstorfer2016data}.
Upon discretization, many important dynamical systems including those considered in this work can be cast into a linear-quadratic system of ODEs as follows:
\begin{equation}
\begin{split}
\frac{d}{dt}\mathbf{q}(t) =\mathbf{c}+\mathbf{Aq}(t)+\mathbf{H}(\mathbf{q}(t)\otimes \mathbf{q}(t)) + \mathbf{Bu}(t), \\
\mathbf{q}(t_0) = \mathbf{q_0}, t \in [t_0,t_f] \label{eq:1}
\end{split}
\end{equation}
where $\mathbf{q}(t) \in \mathbb{R}^n$ is the state vector at time $t$ with dimension $n$, $\mathbf{q}_0 \in \ \mathbb{R}^n$ is the initial condition, $\mathbf{A} \in \mathbb{R}^{n \times n}$ is the linear ODE operator, $\mathbf{H} \in \mathbb{R}^{n \times n^2}$ is the quadratic ODE operator, $\mathbf{c} \in \mathbb{R}^{n}$ are constant terms, $\mathbf{u}(t) \in \mathbb{R}^{m}$ are input terms related to BCs or forcing terms, $\mathbf{B} \in \mathbb{R}^{n \times m}$ is a linear operator in the forcing term $\mathbf{u(t)}$, and $\mathbf{q} \otimes \mathbf{q} = [q_1^2,q_1 q_2,...,w_1,q_n,q_2q_1,q_2^2,...,q_2q_n,...,q_n^2] \in \mathbb{R}^{n^2}$
Note that Equation \eqref{eq:1} has a polynomial structure. OpInf is especially suited for dynamical systems with polynomial nonlinearities such as Lorenz 96 and KS. For systems with non-polynomial nonlinear operators, one can use lifting maps to transform non-polynomial dynamics into higher-order polynomial dynamics \cite{peherstorfer2016data,qian2020lift}.
The OpInf method is built upon a sequence of steps starting by gathering a snapshot matrix $\mathbf{Q}$ that contains a finite set of measurements of the FOM, as seen in the following:
\begin{equation}
\mathbf{Q} = [\mathbf{q}(t_0),\mathbf{q}(t_1),...,\mathbf{q}(t_{f})] \ \in \ \mathbb{R}^{n \times k} \label{eq:2}
\end{equation}
where $k$ is the total number of snapshots.
In the next step, one chooses a low-dimensional basis $\mathbf{V} \in \mathbb{R}^{n \times r}$, with $r \ll n$, to represent each vector $\mathbf{q}(t)$ of the matrix $\mathbf{Q}$. In this case, $\mathbf{q}(t) \approx \mathbf{V} \mathbf{q}_{r}(t)$, where $\mathbf{q}_{r}(t) \in \mathbb{R}^{r}$ is the reduced state vector. This study applied Principal Component Analysis (PCA) to generate the basis $\mathbf{V}$.
A Galerkin projection on Equation \eqref{eq:1} using the basis $\mathbf{V}$ results in a system of ODEs representing the original dynamics in the reduced order space. If the PDE operators of the FOM are known, it is straightforward to check that the Galerkin projection preserves the polynomial structure of the operators. This observation suggests that even if we do not have access to the FOM operators, we can assume that the reduced model operators have the same shape (i.e., the same polynomial structure) as those in Equation \eqref{eq:1}. Such an assumption is central in the OpInf method and constitutes the third building block of the OpInf ROM. Rewriting the projected snapshots $\mathbf{q}_{r}(t)$ as $\widehat{\mathbf{q}}(t)$, the OpInf seeks reduced operators $\widehat{\mathbf{c}} \sim \mathbf{c}$, $\widehat{\mathbf{A}} \sim \mathbf{A}$, $\widehat{\mathbf{H}} \sim \mathbf{H}$, $\widehat{\mathbf{B}} \sim \mathbf{B}$ that mimic the original full order operators in a non intrusive way, which are shown in Equation \eqref{eq:3}
\begin{equation}
\begin{split}
\frac{d}{dt}\mathbf{\widehat{q}}(t) =\mathbf{\widehat{c}}+\mathbf{\widehat{A}\widehat{q}}(t)+\mathbf{\widehat{H}}(\mathbf{\widehat{q}}(t)\otimes \mathbf{\widehat{q}}(t)) + \mathbf{\widehat{B}u}(t), \\
\mathbf{\widehat{q}}(t_0) = \mathbf{V}^{T}\mathbf{q_0}, t \in [t_0,t_f] \label{eq:3}
\end{split}
\end{equation}
Given the projected state variables $\mathbf{\widehat{q}}(t)$ and its time derivatives $\mathbf{\dot{\widehat{q}}}(t)$, calculated with any numerical procedure such as finite differences, the best possible match of the reduced operators with respect to the reduced-order system of ODEs can be found by minimizing the residual of Equation \eqref{eq:3}. Thus, the fourth and final building block of the OpInf is to solve a least-squares problem, where the objective function seeks to minimize the residual of the latent dynamics in the Euclidean norm and the objective variables are the reduced operators $\widehat{\mathbf{c}}, \widehat{\mathbf{A}}, \widehat{\mathbf{H}}, \widehat{\mathbf{B}}$. This problem is ill-conditioned and prone to overfitting \cite{mcquarrie2021data}. To mitigate this issue, we can rewrite the least-squares problem in a regularized version as shown below \eqref{eq:5}.
\begin{equation}
\begin{split}
\min _{\widehat{c}, \widehat{A}, \widehat{\mathbf{H}}, \widehat{\mathbf{B}}} \sum_{j=0}^{k-1}\left\|\widehat{\mathbf{c}}+\widehat{\mathbf{A}} \widehat{\mathbf{q}}_{j}+\widehat{\mathbf{H}}\left(\widehat{\mathbf{q}}_{j} \otimes \widehat{\mathbf{q}}_{j}\right)+\widehat{\mathbf{B}} \mathbf{u}_{j}-\dot{\widehat{\mathbf{q}}}\right\|_{2}^{2}+ \\ \lambda_{1}\|\widehat{\mathbf{c}}\|_{2}^{2}+\lambda_{2}\|\widehat{\mathbf{A}}\|_{F}^{2}+\lambda_{3}\|\widehat{\mathbf{H}}\|_{F}^{2}+\lambda_{4}\|\widehat{\mathbf{B}}\|_{F}^{2} \label{eq:5}
\end{split}
\end{equation}
For the sake of conciseness, the regularized regression problem can be cast into a matrix form written as
\begin{equation}
\min _{\mathbf{O}}\left\|\mathbf{D O}^{\top}-\mathbf{R}^{\top}\right\|_{F}^{2}+\left\|\mathbf{\Gamma O}^{\top}\right\|_{F}^{2} \label{eq:6}
\end{equation}
where
\begin{equation*}
\begin{aligned}
&\mathbf{O}=\left[\begin{array}{llll}
\widehat{\mathbf{c}} & \widehat{\mathbf{A}} & \widehat{\mathbf{H}} & \widehat{\mathbf{B}}
\end{array}\right] \in \mathbb{R}^{r \times d(r, m)} \\
&\mathbf{D}=\left[\begin{array}{llll}
\mathbf{1}_{k} & \widehat{\mathbf{Q}}^{\top} & (\widehat{\mathbf{Q}} \otimes \widehat{\mathbf{Q}})^{\top} & \mathbf{U}^{\top}
\end{array}\right] \in \mathbb{R}^{k \times d(r, m)} \\
&\widehat{\mathbf{Q}}=\left[\begin{array}{llll}
\widehat{\mathbf{q}}_{0} & \widehat{\mathbf{q}}_{1} & \cdots & \widehat{\mathbf{q}}_{k-1}
\end{array}\right] \in \mathbb{R}^{r \times k} \\
&\mathbf{R}=\left[\begin{array}{llll}
\dot{\widehat{\mathbf{q}}}_{0} & \dot{\widehat{\mathbf{q}}}_{1} & \cdots & \dot{\widehat{\mathbf{q}}}_{k-1}
\end{array}\right] \in \mathbb{R}^{r \times k} \\
&\mathbf{U}=\left[\begin{array}{llll}
\mathbf{u}_{0} & \mathbf{u}_{1} & \cdots & \mathbf{u}_{k-1}
\end{array}\right] \in \mathbb{R}^{m \times k} \\
&\mathbf{\Gamma}= \lambda \mathbf{I} = \Lambda(\lambda_1,\lambda_2,\lambda_3,\lambda_4), \ \lambda > 0 .
\end{aligned}
\end{equation*}
In this set of equations $d(r,m) = 1 + r + \binom{r+1}{2} + m$ and $\mathbf{1}_{k} \in \mathbb{R}^{k}$ is a column vector of length $k$ with unity entries.
We notice that in Equation \eqref{eq:6}, $\mathbf{O}$ contain the unknown operators, $\mathbf{D}$ are known data values, $\widehat{\mathbf{Q}}$ are the projected state variables, $\mathbf{R}$ are the time derivatives of the projected state variables, $\mathbf{U}$ represents possible forcing terms, and $\mathbf{\Gamma}$ is a diagonal regularizer.
The minimizer of the regression problem in Equation \eqref{eq:6} satisfies the modified normal equations:
\begin{equation}
\left(\mathbf{D}^{\top} \mathbf{D}+\mathbf{\Gamma}^{\top} \boldsymbol{\Gamma}\right) \mathbf{O}^{\top}=\mathbf{D}^{\top} \mathbf{R}^{\top} \label{eq:8}
\end{equation}
which constitutes an algebraic linear system that can be solved by a variety of efficient algorithms. Furthermore, the optimization problem can also be transformed into $n$ independent least-squares problems and solved efficiently using standard solvers in parallel architectures.
The most computationally expensive operation in the closed-form construction stage (cf. Equation \eqref{eq:8}) is the evaluation of $\mathbf{D}^T\,\mathbf{D}$. Matrix $\mathbf{D}$ is usually dense and, depending on the number of samples and degrees of freedom required to fit the model, it becomes challenging to allocate such matrix operations to a single computational node. By splitting the inner product operation into batch-wise operations along the samples axis and dispatching them in multiple MPI processes, we can rely on huge amounts of data for creating $\mathbf{D}$ without suffering memory issues. Appendix \ref{parallel_eval} shows a pseudocode detailing this batch-wise approach. Alternatively, one can compute a solution for the algebraic linear system by using the Moore-Penrose pseudoinverse $\mathbf{O}^{\top}=\mathbf{D}^\dagger\mathbf{R}^{\top}$ in which no regularization parameter is necessary.
When OpInf learns the reduced operators, it indirectly considers information coming from the original PDE and, thus, learns the underlying Physics of the dynamical system without having access to the full order operators showed in Equation \eqref{eq:1}. The incorporation of physics principles into the machine learning pipeline is the main motivation for choosing OpInf as a chaotic dynamical system forecasting tool.
\section{Quantifying model performance}
To quantify a system's chaoticity, it is common to study its sensitivity to initial conditions. Consider two initial conditions represented by the vectors $x(t)$ and $x(t)+\delta(t)$, where $\delta(t)$ is an infinitesimally small displacement. At time $t=0$, the distance between both trajectories is set as $\delta(t=0)=\delta_0$. For chaotic systems, trajectories start diverging exponentially in time. Such divergence can be measured through the following mathematical relation:
\begin{equation}
\|\delta(t)\| \approx \|\delta_0\| \ e^{\Lambda t} \label{1}
\end{equation}
The variable $\Lambda$ in Equation \eqref{1} is referred to as the Lyapunov exponent and it characterizes the stability of the system. If the Lyapunov exponent is positive, it means the system is chaotic while negative values represent stability.
Considering multi-dimensional systems, typically, there are as many Lyapunov exponents as there are dimensions. If at least one positive Lyapunov exponent exists, the system is chaotic, however, the rate of divergence can be qualitatively observed by the magnitude of these exponents. The value of $\Lambda$ can also be different depending on the orientation of the displacement vector $\delta(t)$, given by $\delta(t)/|\delta(t)|$ \cite{vlachas2020backpropagation,wang2019neural}. Therefore, the possible values of $\Lambda$ defines a spectrum $\Lambda_1 \geq \Lambda_2 \geq \Lambda_3 \geq ... \geq \Lambda_n $ with $n$ being the dimensionality of the phase space. Note that when $\Lambda$'s with positive values are dominant, we observe faster divergence among trajectories.
From Equation \eqref{1}, the largest positive value of $\Lambda$ causes the largest divergence, which is called the Maximal Lyapunov exponent (MLE) denoted by $\Lambda_1$. The MLE has two main purposes:
\begin{itemize}
\item To measure the level of unpredictability of the dynamical system \cite{wang2019neural};
\item Provide a characteristic time scale to quantify the quality of predictions based on the forecasting error growth (Lyapunov time) \cite{vlachas2020backpropagation}.
\end{itemize}
In this work, we scale the time axis of all plots in numerical results by the largest Lyapunov exponent $\Lambda_1$ in order to characterize the chaoticity of the system. This is done by multiplying the time vector $t$ by the MLE of the model ($T^{\Lambda_1} = t \Lambda_1$). Aiming at establishing a straightforward comparison with methods based on backpropagation and reservoir computing RNN architectures showed in \cite{vlachas2020backpropagation}, we considered the same setups and geometries used in that paper. Thus, we considered the Lyapunov exponent of the Kuramoto-Sivashinsky problem as $\Lambda_1 = 0.094$ while for Lorenz-96 system we fixed $\Lambda_1=1.68$ for $F=8$ and $\Lambda_1=2.27$ for $F=10$.
As suggested in \cite{vlachas2020backpropagation}, this work also considers the valid prediction time $\mathrm{(VPT)}$ to quantify the model's predictive performance through a single metric. The VPT is computed in terms of the system's MLE ($\Lambda_1$) using the following definition
\begin{equation}
\mathrm{VPT}=\frac{1}{\Lambda_{1}} \underset{t_{f}}{\operatorname{argmax}}\left\{t_{f} \mid \operatorname{NRMSE}\left(\boldsymbol{o}_{t}\right)<\epsilon, \forall t \leq t_{f}\right\}. \label{2}
\end{equation}
Textually, $\mathrm{VPT}$ finds the largest time $t_f$ that the model can forecast with a normalized root mean square error (NRMSE) of the observable time-series $o_t$ smaller than a threshold $\epsilon$ and normalizes it using $\Lambda_1$. The value of $\epsilon$ is set to 0.5 to allow comparisons with \cite{vlachas2020backpropagation}.
$\mathrm{NRMSE}$ is computed as follows
\begin{equation}
\label{eq:nrmse}
\mathrm{NRMSE}(\mathbf{\widehat{x}}) = \sqrt{\frac{\sum^{N-1}_{i=0} (\mathbf{x}_{i} - \mathbf{\widehat{x}}_{i})^2}{N\boldsymbol{\sigma}^2}} ,
\end{equation}
where $\mathbf{x}_{i}$ and $\mathbf{\widehat{x}}_{i}$ identify the reference and predicted time-series, respectively, $N$ is the total number of time-series considered (possibly in latent space), and $\boldsymbol{\sigma}$ is the array of standard deviations over time for all time-series. The division in Equation \ref{eq:nrmse} should be understood as an element-wise operation, that is, for each time-series, there is a single $\sigma_{i}$.
\section{Numerical results}
In this section, we assess the effectiveness of the OpInf method in creating a reduced-order model through two benchmark examples: the Lorenz 96 and the Kuramoto-Sivashinsky systems. The former is a suitable emulator for complex multi-scale atmospheric systems. The latter shows rich dynamical characteristics with many bifurcations depending on the size $L$ of the spatial domain culminating in strong chaotic regimes.
\subsection{Lorenz 96} \label{res:lor}
The Lorenz 96 numerical experiment is performed using $N=40$ degrees of freedom for the interval $t = [0, 2000]\,s$ with a timestep $dt=0.01\,s$. The forcing term $F$ is chosen as either $F=8$ or $F=10$.
Assuming periodic boundary conditions and starting from a randomly generated initial condition, the problem is solved by employing SciPy's LSODA algorithm, a solver that automatically switches between a nonstiff Adams solver and a Backward Differentiation Formula method for stiff problems. The first $1000\,s$ are discarded to get rid of the initial transient behavior, and the remaining $1000\,s$ are split into two sets of equal size corresponding to the training and testing datasets. Since the Lorenz 96 system is randomly initialized, the simulation is repeated $100$ times for each forcing term to analyze the sensitivity of the reduced model with respect to the randomized ICs. The OpInf reduced models are obtained by solving a least-squares problem via Moore-Penrose pseudoinverse for each random initialization and subsequently used for computing extrapolations. To evaluate the quality of each model, we employ the VPT criteria. For each simulation set, corresponding to a different forcing term $F$, the VPT values are recorded and their minimum, maximum, mean, and standard deviation values are showed in Table \ref{tab:VPT}. In this table $\sigma^{*}$ is computed over all approximate solutions associated to each IC. The VPT threshold value was fixed as $0.5$.
\begin{table}[!h]
\caption{Minimum, Maximum, Avegare and Standard Deviation of VPT for the Lorenz 96 simulations.}
\centering
\begin{tabular}{ccc}
\hline
$F$ & 8 & 10 \\
\hline
VPT min & 3.00 & 1.45\\
VPT max & 6.66 & 3.19 \\
VPT avg & 4.42 & 2.32 \\
VPT $\sigma^{*}$ & 0.61 & 0.29\\
\hline
\end{tabular}
\label{tab:VPT}
\end{table}
The left-hand side of Figs. \ref{contour_lorenz_96_F=8} and \ref{contour_lorenz_96_F=10} compare the approximate and target contour plots of the spatiotemporal forecast of the Lorenz 96 chaotic system for the configurations $F=8$ and $F=10$, respectively. The right-hand side of the same Figs. show the normalized root square error (NRSE) associated to each one of the forcing configurations. The OpInf results correspond to the best approximation among all random ICs.
\begin{figure}[!h]
\centering
\begin{tabular}{cc}
\includegraphics[scale=0.67]{figs/nogue1.png} &
\includegraphics[scale=0.67]{figs/nogue2.png} \\
a) & \hspace{-0.6cm} b)
\end{tabular}
\caption{Contour plots of the spatiotemporal forecast of the Lorenz 96 system with $40$ degrees of freedom and $F=8$: a) OpInf prediction vs. ground truth; b) NRSE error.}
\label{contour_lorenz_96_F=8}
\end{figure}
\begin{figure}[!h]
\centering
\begin{tabular}{cc}
\includegraphics[scale=0.67]{figs/nogue3.png} &
\includegraphics[scale=0.67]{figs/nogue4.png} \\
a) & \hspace{-0.6cm} b)
\end{tabular}
\caption{Contour plots of the spatiotemporal forecast of the Lorenz 96 system with $40$ degrees of freedom and $F=10$: a) OpInf prediction vs. ground truth; b) NRSE error.}
\label{contour_lorenz_96_F=10}
\end{figure}
Fig. \ref{NRMSE_F=8_F=10} shows the evolution of the mean $NRMSE$ along time for both configurations of the forcing term, i.e., $F=8$ (Fig. \ref{NRMSE_F=8_F=10}a) and $F=10$ (Fig. \ref{NRMSE_F=8_F=10}b) considering all random ICs. The plots also depict the standard deviation envelope around the average $NRMSE$ which is computed as $\overline{NRMSE} \pm \sigma(NRMSE)$. These outcomes indicate a clear prediction improvement of the OpInf method over the backpropagation and reservoir computing RNN architectures considered in \cite{vlachas2020backpropagation}. For instance, comparing the average $NRMSE$ for F=8 and F=10 reported in \cite{vlachas2020backpropagation} with the ones in Fig. \ref{NRMSE_F=8_F=10}, their best forecasting model reached VPT at $0.79$ and $0.83$ Lyapunov time units (cf. Table 1 in \cite{vlachas2020backpropagation}) respectively, while OpInf did the same at $4.42$ and $2.32$ Lyapunov time units (Table \ref{tab:VPT}). Note that if we consider the standard deviation envelope, the worst OpInf results for F=8 is still better than the best $NRMSE$ in \cite{vlachas2020backpropagation} while for F=10, the worse OpInf results is better than the mean $NRMSE$ in \cite{vlachas2020backpropagation}.
\begin{figure}[!h]
\centering
\begin{tabular}{cc}
\hspace{-0.7cm}
\includegraphics[scale=0.5]{figs/nogue5.png} &
\includegraphics[scale=0.5]{figs/nogue6.png} \\
\hspace{0.2cm} a) & \hspace{0.8cm} b)
\end{tabular}
\caption{Mean $NRMSE$ and standard deviation envelope for the Lorenz 96 system over 100 random initial conditions sampled from the testing data: a) $F=8$; b) $F=10$. The dashed line indicates the threshold value of the VPT quality metric.}
\label{NRMSE_F=8_F=10}
\end{figure}
Fig. \ref{lorenz_96_modes_F=8,10} shows the predictive power of OpInf for five different discrete variables of the Lorenz 96 model with $F=8$ and $F=10$, respectively. The plots compare the approximate integrated solution with the ground truth over time for the best approximate solution among all random ICs. We can observe from those plots that the OpInf performed remarkably for both $F=8$ and $F=10$ configurations matching the exact solutions for as long as $6.66$ and $3.19$ Lyapunov time units, respectively.
\begin{figure}[!h]
\centering
\begin{tabular}{cc}
\includegraphics[width=7.4cm,height=4.3cm]{figs/nogue7.png} & \includegraphics[width=7.4cm,height=4.3cm]{figs/nogue12.png} \\
\includegraphics[width=7.4cm,height=4.3cm]{figs/nogue8.png} &
\includegraphics[width=7.4cm,height=4.3cm]{figs/nogue13.png} \\
\includegraphics[width=7.4cm,height=4.3cm]{figs/nogue9.png} &
\includegraphics[width=7.4cm,height=4.3cm]{figs/nogue14.png} \\
\includegraphics[width=7.4cm,height=4.3cm]{figs/nogue10.png} &
\includegraphics[width=7.4cm,height=4.3cm]{figs/nogue15.png} \\
\includegraphics[width=7.4cm,height=4.3cm]{figs/nogue11.png} &
\includegraphics[width=7.4cm,height=4.3cm]{figs/nogue16.png} \\
\hspace{0.1cm} a) & \hspace{0.2cm} b)
\end{tabular}
\caption{Predicted (blue) vs. ground truth (red) integrated discrete variables $X_{k}, \, k = 0,10,20,30,39$ for the Lorenz 96 system: a) $F=8$; b) $F=10$.}
\label{lorenz_96_modes_F=8,10}
\end{figure}
\subsection{Kuramoto-Sivashinsky}\label{res:ks}
The Kuramoto-Sivashinsky (KS) equation is defined over a domain $\Omega = [0,L]$ with periodic boundary conditions. We chose the domain size $L = 200 \,m$ and discretized it with $512$ equally spaced grid points. The KS equation marches in time for a total $T = 6 \cdot 10^4 \,s$ with a time step $dt = 0.125\,s$ corresponding to $48 \cdot 10^4$ steps. The reference solution of the KS equation is generated using the modified exponential time-differencing fourth-order Runge-Kutta scheme (ETDRK4) as described in \cite{Kassam2005}. The ETDRK4 scheme combines a modified version of the exponential time-differencing (ETD) scheme with the fourth-order Runge-Kutta (RK4) time integrator. Time-stepping is performed with sequential FFT analysis where the number of waves considered is a function of the number of grid points.
We employ the Principal Component Analysis (PCA) to reduce the dimensionality of the full order model from $512$, which corresponds to the number of grid points, to $r=160$ dimensions that match the number of reduced basis vectors in $\mathbf{V}$. The final shape of the spatiotemporal dataset used to train and test the OpInf model is set to $(t,x) = (4,8\,\times 10^5, 160)$. The PCA decomposition is applied to $90\%$ of the initial $(t,x)$ snapshots and the choice of $k$ is guided by the projection error evaluated over the remaining $10\%$ of the dataset. The projection error obtained in this region is approximately $0.51 \%$ and the expected variance ratio higher than $0.9999$ with respect to the $90\%$ portion of the initial snapshots. Fig. \ref{cumul_energy_PCA} shows the cumulative explained variance ratio (or the energy content) preserved by the PCA decomposition as a function of the number of modes.
\begin{figure}[!h]
\centering
\includegraphics[scale=0.45]{figs/nogue17.png}
\caption{Cumulative explained variance ratio for the PCA decomposition of the Kuramoto-Sivashinsky dataset. The vertical dashed line indicates the total number of eigenmodes used by the OpInf ROM which corresponds to $99.99\%$ explained variance.}
\label{cumul_energy_PCA}
\end{figure}
The modeling dataset is split into three subsets with proportions (90\%, 5\%, 5\%) corresponding to the training, validation and test datasets, respectively. The OpInf reduced model is generated considering a simple grid-search for the $log_{10}$ of the Thikonov regularization penalties $(\lambda_2, \lambda_3)$ for the discrete domain $\left\{(\lambda_2,\lambda_3); -3 \leq \lambda_2 \leq 3, -3 \leq \lambda_3 \leq 3\right\}$ with a $0.5$ step for both $\lambda_2$ and $\lambda_3$. For this specific case we found the combination $(\lambda_2,\lambda_3) = (10^{-3}, 10^{-3})$ as the best option for minimizing the extrapolation error in the validation dataset. For this particular case, the regularizers $\lambda_1$ and $\lambda_4$ are set to zero since the constant polynomial term $\mathbf{\widehat{c}}$ (cf. Equation \eqref{eq:3}) has minor influence over the final results and the KS system has no forcing term to fit the operator $\mathbf{\widehat{B}}$. Once OpInf operators are obtained, they are used for extrapolating the state variable $\widehat{\mathbf{q}}(t)$ over an unseen dataset. In order to evaluate the model sensibility to different initial conditions, we proceed by time-integrating the reduced model with the SciPy routine \textit{odeint} using a set of 100 initial conditions randomly selected from the test dataset. We uses the same time horizon of 90 s (empirically chosen) to assess the model extrapolation for each IC. Table \ref{tab:VPT_ks} shows minimum, maximum, mean, and standard deviation VPT values for the KS system. In this table, $\sigma^{*}$ is computed over all approximate solutions associated to each IC. The VPT threshold in this case was fixed as $0.5$.
\begin{table}[!h]
\caption{Minimum, Maximum, Average and Standard Deviation of VPT for the Kuramoto-Sivashinsky simulations.}
\centering
\begin{tabular}{ccc}
\hline
VPT min & 286 \\
VPT max & 794 \\
VPT avg & 520 \\
VPT $\sigma^{*}$ & 108\\
\hline
\end{tabular}
\label{tab:VPT_ks}
\end{table}
The extrapolated solutions are then reconstructed into the full dimensional space through the PCA basis $\mathbf{V}$. The relative approximation error in $L^2$-norm achieved by the best reconstructed solution among all time-integrated solutions associated to each IC is $25.8 \%$ for the time horizon of $90 s$. Considering only the first $75 s$ in the test dataset comprising the $90 s$, the relative approximation error drops to $1.2 \%$. The VPT metric associated to the best case gets the impressive value of $794$. The NRMSE is evaluated for the $160$ latent time-series $\mathbf{\widehat{x}}_{i}$ referenced in Equation \ref{eq:nrmse}. A summary of the VPT results for this numerical experiment can be seen in Figure \ref{NRMSE_KS}. Comparing OpInf performance for the KS system with the results in \cite{vlachas2020backpropagation}, OpInf is way superior with a forecasting capability two orders of magnitude larger. We should also notice that the OpInf performed remarkably well with a reduced number of dimensions (i.e., using $160$ eigenmodes). In contrast, all the network architectures analyzed in \cite{vlachas2020backpropagation} produced forecasts in the full order space. We still observe that OpInf also outperforms the Markov neural operators (MNO) as proposed in \cite{likovachki} in terms of accuracy and stability. MNO keeps up with the exact trajectory for the KS system until $t=50s$ while OpInf exceeds $t=70s$.
\begin{figure}[!h]
\centering
\includegraphics[scale=0.5]{figs/nogue18.png}
\caption{Mean $NRMSE$ and standard deviation envelope for the Kuramoto-Sivashinsky case over 100 initial conditions sampled from the testing data. The dashed line indicates the threshold value of the VPT quality metric.}
\label{NRMSE_KS}
\end{figure}
Fig. \ref{KS_approx_vs_exact} compares the contour plots of one of the best OpInf approximate solutions (considering all the solutions corresponding to each initial condition) with the ground truth solution of the KS chaotic system. The OpInf ROM can accurately predict the system dynamics for more than $744$ Lyapunov time units (cf. black dashed lines) which is far beyond the results achieved in \cite{vlachas2020backpropagation}.
\begin{figure}[!h]
\centering
\includegraphics[scale=0.5]{figs/nogue19.png} \hspace{-0.3cm}
\includegraphics[scale=0.5]{figs/nogue20.png}
\caption{Contour plots of the spatiotemporal forecast of the Kuramoto-Sivashinsky system with $160$ reduced dimensions: ground truth (left) vs. predicted (right). The dashed line indicates the visual limit for which OpInf prediction and ground truth match.}
\label{KS_approx_vs_exact}
\end{figure}
Fig. \ref{KS_error} shows the spatiotemporal contour plots of the approximation errors of the OpInf ROM based on two distinct metrics: a) pointwise error and b) NRSE. The white dashed lines point out how far the reduced model can keep errors at an extremely low level. Such an outstanding performance highlights how physics inspired machine learning architectures can outperform deep learning state-of-the-art models such as backpropagation and reservoir computing RNN architectures in extrapolation regime.
\begin{figure}[!h]
\centering
\begin{tabular}{cc}
\includegraphics[scale=0.5]{figs/nogue21.png} & \hspace{-0.7cm}
\includegraphics[scale=0.5]{figs/nogue22.png} \\
a) Pointwise error & \hspace{-0.7cm} b) NRSE
\end{tabular}
\caption{Contour plots of the error measure between the ground truth and the approximate solution of the Kuramoto-Sivashinsky system with $160$ reduced dimensions: a) pointwise error; b) NRSE. The color bar indicates absolute values (e.g., $1.0$ represents $100\%$ deviation). The dashed line indicates the visual limit for which OpInf prediction and ground truth match.}
\label{KS_error}
\end{figure}
Fig. \ref{ks_modes} shows the comparison between approximate and reference temporal eigenmodes for six distinct integrated time-series in the KS system latent space. The plots evidence the capacity of OpInf ROM to match the reference eigenmodes during long-term forecasting even for the lowest energetic modes (e.g., eigenvectors 120 and 159).
\begin{figure}[!h]
\centering
\includegraphics[width=8.0cm,height=3.7cm]{figs/nogue23.png}
\includegraphics[width=8.0cm,height=3.7cm]{figs/nogue24.png}
\includegraphics[width=8.0cm,height=3.7cm]{figs/nogue25.png}
\includegraphics[width=8.0cm,height=3.7cm]{figs/nogue26.png}
\includegraphics[width=8.0cm,height=3.7cm]{figs/nogue27.png}
\includegraphics[width=8.0cm,height=3.7cm]{figs/nogue28.png}
\caption{Six temporal eigenmodes out of the total $160$ modes for the Kuramoto-Sivashinsky system: predicted (blue) vs. ground truth (red) variables.}
\label{ks_modes}
\end{figure}
We notice in Fig. \ref{ks_modes} that the latent space representation of the KS data produces an increasing oscillatory pattern as the eigenmodes become less and less energetic. In contrast, the Lorenz 96 system with $F=10$, for instance, displays dominant high frequency oscillations in every temporal eigenmode since it is represented in the full order space (see Fig. \ref{lorenz_96_modes_F=8,10}). We conjecture that the regularized representation of the PCA decomposition, specially for the most energetic modes, is likely the reason why Lorenz 96 forecasting results did not perform as remarkably as those for the KS system.
As a final assessment, we check the physical consistency of the OpInf ROM. We select a point in the state-space of the ROM where the predicted solution and the ground truth already diverged ($\approx$ $750$ Lyapunov times in Fig. \ref{KS_error}) and use it as an initial condition for the discretized KS equation (i.e., the reference system). We then integrate the discretized equation in time for $20 s.$ ($\approx 212$ Lyapunov times) and compare the output with the OpInf solution. We call the time-integrated solution based on the reference system the restarted solution. Fig. \ref{KS_restarted_vs_predicted} shows the spatiotemporal representation of the restarted and OpInf solutions together with the absolute pointwise error between both solutions. We observe an excellent agreement between both KS systems' answers, with errors kept very small on most of the $(x,t)$ domain except for a few dark blue and red stripes.
\begin{figure}[!h]
\centering
\begin{tabular}{ccc}
\hspace{-1.1cm}
\includegraphics[scale=0.42]{figs/nogue29.png} & \hspace{-1.1cm}
\includegraphics[scale=0.42]{figs/nogue30.png} & \hspace{-1.1cm}
\includegraphics[scale=0.42]{figs/nogue31.png} \\
\hspace{-1.1cm} a) & \hspace{-1.1cm} b) & \hspace{-1.1cm} c)
\end{tabular}
\caption{Contour plots of the solution $u(x,t)$ of the KS system: a) restarted; b) OpInf (predicted); c) absolute pointwise error. }
\label{KS_restarted_vs_predicted}
\end{figure}
Fig. \ref{tseries_restarted_vs_opinf} compares the restarted and the OpInf ROM solutions at six regularly spaced grid points. These plots correspond to horizontal slices (time-series) of the contour plots in Fig. \ref{KS_restarted_vs_predicted}. Comparing the restarted and the OpInf solutions on these plots, we confirm a close similarity between them, especially at the boundaries of the KS domain $u(0,t)$ and $u(L,t)$ (cf. first and last plots from top to bottom in Fig. \ref{tseries_restarted_vs_opinf}). This result indicates that OpInf is physically meaningful since its outputs are consistent with the state-space generated by the reference system including its boundary conditions.
\begin{figure}[!h]
\centering
\includegraphics[width=8.0cm,height=3.68cm]{figs/nogue32.png}
\includegraphics[width=8.0cm,height=3.68cm]{figs/nogue33.png}
\includegraphics[width=8.0cm,height=3.68cm]{figs/nogue34.png}
\includegraphics[width=8.0cm,height=3.68cm]{figs/nogue35.png}
\includegraphics[width=8.0cm,height=3.68cm]{figs/nogue36.png}
\includegraphics[width=8.0cm,height=3.68cm]{figs/nogue37.png}
\caption{Restarted vs. OpInf ROM solutions of the KS system at regularly spaced grid points: $u(x_{1},t),\dots,u(x_{6},t)$. The top-left and bottom-right plots correspond to the solutions at the boundaries of the KS domain $u(x_{6} = L,t)$ and $u(x_{1} = 0,t)$, respectively.}
\label{tseries_restarted_vs_opinf}
\end{figure}
\clearpage
\section{Conclusion}
In this paper we develop surrogate models based on the Non-intrusive Reduced Order Modeling via Operator Inference (OpInf) method to simulate benchmark chaotic systems, namely, Lorenz 96 and Kuramoto-Sivashinsky (KS) equation. We also propose a parallel scheme for decomposing the matrix product $\mathbf{D}^T\,\mathbf{D}$ on the left hand side of Equation \eqref{eq:8} using a batch-wise approach as detailed in Appendix \ref{parallel_eval}.
OpInf shows remarkable forecasting capabilities for both dynamical systems with two setup configurations for Lorenz 96 and one for KS system. We observe robust time-series predictions in latent space outperforming by far state-of-the-art machine learning techniques such as ESN-RC, Unitary cell, LSTM, and GRU analyzed in \cite{vlachas2020backpropagation}. OpInf performance also excels in the MNO method \cite{likovachki} based on Fourier Neural Operators (FNO) being $40\%$ more accurate in representing the KS system trajectory. It is worth noticing that for Lorenz 96 system with 40 degrees of freedom, OpInf reached VPT at $4.42$ and $2.32$ Lyapunov time units on average for forcing terms $F=8$ and $F=10$, respectively, while the best forecasting model in \cite{vlachas2020backpropagation} topped at $0.79$ and $0.83$ Lyapunov time units. Regarding the KS system, OpInf performs even better matching ground truth simulations for as long as $520$ Lyapunov time units on average using $160$ degrees of freedom. Referring to Fig. 12a in \cite{vlachas2020backpropagation} we notice that their best surrogate model defined in full space dimension ($512$ degrees of freedom) reached $5$ Lyapunov time units as VPT. Numerical experiments for the KS system also revealed that OpInf ROM produces physically meaningful solutions consistent with the state-space generated by the discretized KS equation, as depicted in Figs. \ref{KS_restarted_vs_predicted} and \ref{tseries_restarted_vs_opinf}. In this case, the OpInf dynamics show close correspondence with the solution generated by the reference system using an OpInf unpaired physical state as the initial condition.
We confirm that OpInf has many attractive features. It is non-intrusive, generalizable (in the sense that it can approximate a large class of PDE operators with linear-quadratic structure), explainable, physics-informed, and computationally efficient. Moreover, it is based on a sound mathematical background (Koopman’s theory), does not depend on gradient descent algorithm, uses standard linear algebra tools, and needs only a few regularizing parameters. The regularization strategy in the least-squares problem is a key ingredient for the OpInf success but it is quite tricky. The Tikhonov-based regularization method used in OpInf is obtained by means of a grid search over the space of the regularization parameters which makes the process of finding a global minimum pretty challenging. Keeping time integration errors bounded is another crucial point which we address by using SciPy's LSODA algorithm.
As we are interested in tackling turbulent flows in the future, we plan to find ways to build closure mechanisms for the OpInf ROM in latent space aiming at capturing the energy of hidden scales smeared by the PCA decomposition. Closure mechanisms could be straightforwardly plugged into the OpInf least-squares problem through the $\mathbf{\widehat{B}}$ forcing operator (cf. Equation \eqref{eq:5}) producing a ROM closure. We also want to address the limitations of the OpInf grid search regularization technique by exploring convex and nonconvex optimization approaches that best fit the regularization parameters by means of approximations and exploration of equivalent formulations.
\section*{Acknowledgments}
ACNJ acknowledges the Brazil's IBM Research laboratory for supporting this work.
\bibliographystyle{unsrt}
| {'timestamp': '2022-06-07T02:31:17', 'yymm': '2206', 'arxiv_id': '2206.01604', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01604'} | arxiv |
\section{Introduction}
Nowadays, the web and social media are integral parts of our modern digital life as they are the main sources of the unprecedented amounts of data we have.
Thanks to the breakthrough in deep learning,
search engines are no longer restricted to keyword matching; instead, they are currently able to understand queries in natural language and satisfy the intended information need of users.
Question Answering (QA) is an essential task in information retrieval which is forming the basis for the new frontier of search engines.
Plenty of studies on question answering systems has been performed on English and other languages. However, very few attempts have addressed the problem of Arabic question answering ~\cite{survey}.
Arabic NLP research in question answering is particularly challenging due to the scarcity of resources and the lack of processing tools available for Arabic.
Arabic language, as well, has some unique characteristics by being a highly inflectional and derivational language with complex morphological structures~\cite{albayan}.
The Holy \quran is the sacred text for Muslims around the globe and it is the main source for teachings and legislation in Islam~\cite{ayatec},
there are 114 chapters in \quran corresponding to 6,236 verses, every verse consists of a sequence of words in Classical Arabic (CA) dating back to 1400 years ago.
This paper describes our proposed solutions for OSACT5 Qur'an QA 2022 shared task. The shared task introduced QRCD (The Qur’anic Reading Comprehension Dataset), which is a dataset for extractive question answering.
First, we experimented with a variety of Arabic pre-trained Bidirectional Encoder Representations from Transformers
(BERT) models, then we implemented an Ensemble approach to get more robust results from a mixture of experts (MOEs).
After that, we propose some post-processing operations to enhance the quality of answers according to the official evaluation measures.
The task is evaluated as a ranking task according to the Partial Reciprocal Rank (pRR) metric.
The rest of this paper is organized as follows. In section \ref{sec:related}, we describe the related work,
in section \ref{sec:dataset}, we outline the dataset details and official evaluation measures,
in section \ref{sec:qa_design}, we explain the system design and the implementation details,
in section \ref{sec:eval}, we report the system evaluation results,
and finally section \ref{sec:conc} concludes the paper.
\footnote{
The source code and trained models are available at \href{https://github.com/mohammed-elkomy/quran-qa}{\color{blue}https://github.com/mohammed-elkomy/quran-qa}.
}
\color{white}
\footnote{\label{foot}To enable fair comparison among the teams, the organizers only considered 238 examples for the official test-split results and excluded 36 samples due to being very similar to public splits.}\iftrue
\color{white}
\renewcommand{\thefootnote}{\fnsymbol{footnote}}
\footnote[1]{Tanta Computer Engineering}
\renewcommand{\thefootnote}{\arabic{footnote}}
\color{black}
\fi
\color{black}
\section{Related Work}
\label{sec:related}
Question answering systems have been an active point of research in recent years, particularly for highly-resourced languages such as English.
~\cite{squad} introduced SQuAD1.0 dataset which is a widely used dataset for question answering in English.
To tackle the data scarcity in Arabic NLP, ~\cite{SOQAL} presented Arabic Reading Comprehension Dataset (ARCD) which consists of 1,395 questions posed by crowdworkers.
Moreover, ~\cite{SOQAL} automatically translated SQuAD1.0 using google translation services.
Only a little attention has been paid to question answering on \quran.
~\cite{albayan} proposed a Support Vector Machine (SVM) question answering system with handcrafted features
to extract answers from both \quran and its interpretation books (Tafseer).
Recent work by ~\cite{ayatec} introduced \texttt{AyaTEC} as the first fully reusable test collection for Arabic QA on the Holy \quran where questions are posed in Modern Standard Arabic
(MSA) and their corresponding answers are qur'anic verses in CA.
\section{Dataset and Task Description}
\label{sec:dataset}
In this section, we describe QRCD (The Qur’anic Reading Comprehension Dataset),
the problem definition and official evaluation metrics of the \quran QA 2022 shared task of answering questions on the holy \quran ~\cite{QRCD_repo}.
\subsection{Dataset Details }
{The} Qur'anic Reading Comprehension Dataset
{(QRCD)~\cite{qrcd} is the first large scale question answering dataset on the holy \quran text. It was introduced as a part of the \quran QA 2022 Shared Task for question answering~\cite{qrcd}.}
The dataset consists of 1,093 tuples of question-passage pairs { that are coupled with their extractive answers to constitute 1,337 question-passage-answer triplets. The question-passage pairs are} split into training, development and
testing sets as shown in Table \ref{tab:splits_table}. The dataset follows the same format as the commonly used reading comprehension dataset SQuAD1.0~\cite{squad}.
However, QRCD is quite different in terms of size as it is much smaller than SQuAD1.0 which contains 100k unique pairs/questions.
{In addition, unlike SQuAD, the QCRD contains a small number of unique questions, each of which is repeated multiple times with different passage and answer pairs. As shown in Table \ref{tab:splits_table}, } the number of unique questions in QRCD is much lower than the number of question-passage pairs.
{This poses an additional challenge for learning a question answering system which should be able to predict different answers to the same question under different passage contexts}.
\begin{table}[!h]
\begin{center}
\begin{tabularx}{\columnwidth}{|l|X|X|X|}
\hline
\backslashbox[33mm]{Aspect}{Split} & \textbf{Train} & \textbf{Dev} & \textbf{Test} \\
\hline
Question-passage pairs & 710 & 109 & 274$^\text{\ref{foot}}$ \\
\hline
Unique questions & 118 & 17 & 34 \\
\hline
\end{tabularx}
\caption{Number of question-passage pairs and number of unique questions in each split of QRCD dataset.}
\label{tab:splits_table}
\end{center}
\end{table}
The QRCD dataset draws its inspiration from the prior work \texttt{AyaTEC} by reformulating the test collection into an extractive question answering task ~\cite{qrcd}.
Each sample in QRCD is a question-passage-answer triplet which comprises a question in MSA,
a passage taken from the Holy Qur'an
\footnote{
The Holy Qur'an is a very special classical Arabic text revealed 1,400 years ago, making it extremely challenging for computational linguistics tasks.
}
that spans one or more consecutive verses,
and an answer to the question extracted from the passage. Figure \ref{fig:qrcd_sample} demonstrates an example from the QRCD dataset\footnote{The verses from the Holy Qur'an in the dataset come from the simple-clean text style (diacritics removed) from
\href{http://tanzil.net/}{Tanzil Project}.}.
\begin{figure*}[htbp]
\centering
\includegraphics[page=1,width=.85\textwidth]{figures/qrcd_sample.pdf}
\caption{An example of question-passage-answer triplet from QRCD \protect\cite{qrcd}.}
\label{fig:qrcd_sample}
\end{figure*}
\subsection{\quran QA Shared Task Description}
{The \quran QA 2022 shared task~\cite{qrcd} aims to develop models for extractive question answering on the holy \quran passages. Given a Qura'nic passage and a question, the solution to the shared task should extract the answer to the question from the input passage. The answer always exists as a span within the given passage. Questions could be either factoid or non-factoid. Solutions to the shared task are required to extract any correct answer to the input question from the context passage even when the passage has more than one answer.}
\subsection{{Task Evaluation Measures}}
\label{subsec:prr_metric}
{
This question answering task is evaluated as a \textit{ranking} task. The QA system will return up to 5 potential answers ranked from the best to the worst according to their probability of correctness. The task evaluation measure produces a higher score when the correct answer is ranked at a higher position.
When the correct answer is predicted among the 5 potential answers but it is at a lower rank, then the evaluation score is discounted. The task adopts the \textit{partial Reciprocal Rank (\textbf{pRR})}~\cite{ayatec} as the official evaluation metric. Partial Reciprocal Rank (\textbf{pRR}) is a variant of the \textit{Reciprocal Rank} (RR) evaluation metric which is a commonly used metric for ranking tasks. Unlike \textit{Reciprocal Rank} (RR), the \textit{partial Reciprocal Rank (\textbf{pRR})} will give credit to systems that predict answers with a partial inexact matching with the correct answer.
Equation \ref{eq:prr} formally describes the \textbf{pRR} metric evaluation for a ranked list of answers $A$, where $m_{r_{k}}$ is the partial matching score for the returned answer at the $k^{th}$ rank,
as $k$ is taken to be equal to the rank position of the first answer with a non-zero matching score. More details can be found at ~\cite{ayatec} 5.2.
\begin{equation}
p R R(A)=\frac{m_{r_{k}}}{k} ; k=\min \left\{k \mid m_{r_{k}}>0\right\}
\label{eq:prr}
\end{equation}
In addition to the pRR scores, the task evaluation system reports other metrics such as the Exact Match (\textbf{EM}) and \textbf{F1@1}. The \textbf{EM} score is a binary measure that will be equal to one when the top predicted answer exactly matches the ground truth answer. The \textbf{F1@1} metric measures the degree of token overlap between the top predicted answer and any of the ground truth answers. Scores computed from individual passage-question-answer triplets are averaged to compute the overall score over the entire evaluation dataset.}
\section{{QA System Design}}
\label{sec:qa_design}
{\textbf{B}idirectional \textbf{E}ncoder \textbf{R}epresentations from
\textbf{T}ransformers (BERT)~\cite{bert} models achieve state-of-the-art results in many natural language understanding problems. Our solution is an ensemble of BERT based models pre-trained on Arabic language corpora and fine-tuned on the shared task dataset. We built an ensemble that merges predictions from individual models. Additionally, we also designed and implemented a set of post-processing operations that aim to improve the quality of predicted answers and boost the task evaluation measure.}
In this section, we describe our QA system developed to solve the \quran QA 2022 challenge. First, we give a brief background on BERT models and their usage for question answering tasks. Then we provide an overview of Arabic language BERT models that we used to build our ensemble. Finally, we provide the details of our ensemble building approach and the proposed post-processing operations to improve predicted answers quality.
\subsection{BERT for Question Answering}
\subsubsection{BERT}
\label{subsec:bert}
BERT models achieve their state-of-the-art performance due to a procedure called pre-training which allows BERT to discover the language structures and patterns.
BERT uses two pre-training tasks, namely masked language model (MLM) and next sentence prediction (NSP)~\cite{bert}.
After that, a second stage called fine-tuning, which is performed to adapt the model for a downstream task by making use of the features learnt during the pre-training phase.
\subsubsection{Question Answering using BERT}
\label{subsec:bert_qa}
As mentioned in \ref{subsec:bert}, the fine-tuning phase takes a pre-trained model and stacks a randomly-initialized output layer suitable for a particular downstream task.
For extractive question answering, both the question and passage are tokenized and packed into a single sequence
and the output layer is required to give a probability for the i$^{th}$ token in the passage to be the start of the answer span $P_i$ using the dot product
of a start vector $S$ and the i$^{th}$ token's hidden representation $T_i$ as seen from equation \ref{eqn:start_softmax}, a similar analysis holds for the end of the answer span with an end vector $E$.
The score of a candidate's answer span from the i$^{th}$ token to the j$^{th}$ token is defined in Equation \ref{eqn:span_score}.
Answers are only accepted for $j \geq i$ since the two probability distributions are independent and not guaranteed to produce a valid span ~\cite{bert}.
$S$ and $E$ are trainable weights and randomly initialized layers stacked on top of pre-trained BERT.
In our case the system is not limited to just one answer as in SQuAD1.0 ~\cite{squad}, instead, a ranked list of 20 answers is generated from the model and ranked based on the span score as in Equation \ref{eqn:span_score}.
\begin{equation}
P_{i}=\frac{e^{S \cdot T_{i}}}{\sum_{j} e^{S \cdot T_{j}}}
\label{eqn:start_softmax}
\end{equation}
\begin{equation}
Span_{i,j} = S T_{i} + E T_{j}
\label{eqn:span_score}
\end{equation}
\subsection{Arabic variants of BERT model}
\label{subsec:models}
The standard BERT model variants are not pre-trained on Arabic text which hinders the development of Arabic NLP. Nevertheless, various researchers working on the Arabic natural language understanding have developed variants of BERT models that were trained on Arabic corpora.
We made use of those models, which are discussed later in this section, to build our ensemble.
\subsubsection{AraBERT}
The work by~\cite{arabert} introduced AraBERT model which inherits the exact same architecture from BERT. However, being pre-trained on a large Arabic corpus of 24GB of text
collected from news articles and Wikipedia dumps.
In this work, we use \textbf{bert-large-arabertv02} and \textbf{bert-base-arabertv02} available on the huggingface community~\cite{hug}.
\subsubsection{QARiB}
QARiB~\cite{qarib} is another Arabic BERT variant pretrained on a mixture of formal and informal Arabic with state-of-the-art support for Arabic dialects and social media text,
~\cite{qarib} released 5 BERT models to the community pre-trained on corpora of different sizes.
\subsubsection{ARBERT and MARBERT}
ARBERT and MARBERT~\cite{arbert} are two Arabic-specific Transformer-based MLM pre-trained on a widely large Modern Standard Arabic (MSA) corpus of 61GB of text for the case of ARBERT,
while MARBERT is pre-trained on 128GB of text focused on both dialectal Arabic (DA) and MSA.
\subsection{Training Details}
\label{subsec:training}
We fine-tune a set of five Arabic BERT models as mentioned in \ref{subsec:models}, namely AraBERT-v02$_\text{Large}$\footnote{A subscript Large and Base refers to the model size.},
AraBERT-v02$_\text{Base}$, QARiB$_\text{Base}$, ARBERT and MARBERT
\footnote{ARBERT and MARBERT uses BERT$_\text{Base}$ architecture.}.
The training objective is to maximize the log-likelihoods of the correct start and end token positions~\cite{bert}.
For the development phase, we train BERT$_\text{Base}$ and BERT$_\text{Large}$ for 50 and 65 epochs respectively, looking for the epoch at which the model performs best on the validation split.
For the test phase, we train BERT$_\text{Base}$ and BERT$_\text{Large}$ for 32 and 40 respectively.
We used a batch size of 8 for BERT$_\text{Large}$ and 16 for BERT$_\text{Base}$ and a learning rate of 2e-5 for all of our models.
\subsection{Span Voting Ensemble}
\label{subsec:ensemble}
In this work, we build an ensemble from several different Arabic BERT models that we discussed earlier in \ref{subsec:training}.
The ensemble approach is effective for cancelling the noise exhibited by individual models through majority voting among experts. i.e. Mixture of Experts (MOE).
We treat the answer spans as discrete entities.
For each sample, we {consider} the top 20 predictions made by each model along {with its correctness probability. For} each candidate prediction,
we {compute the sum of its associated correctness probabilities from all models}. We formulate the voting process as follows.
\vspace{-5pt}$$\alpha_{s,e}=\sum_{j=0}^{M}{\alpha^{j}_{s,e}}$$
Where $\alpha_{s,e}$ represents the summed ensemble correctness probability for the answer span starting at token $s$ and ending at token $e$,
and $\alpha^{j}_{s,e}$ represents the correctness probability for the same answer span for the $j^{th}$ expert of the $M$ experts taken into account.
\\
{
After that, the set of all possible answers considered by the ensemble is sorted according to their summed ensemble correctness probabilities.
Finally, the entire ranked list is post-processed and truncated for only the top 5 answers to be evaluated by \textbf{pRR@5}.
}
\vspace{-3pt} \subsection{Post-processing}
By carefully reviewing the answer spans predicted by the BERT models we fine-tuned, we found some systematic errors causing sub-optimal predictions.
Here we propose some basic post-processing rules to improve the model predictions.
The post-processing pipeline takes a ranked list of answer spans, it typically takes at least 20 answer spans from a single model or the span-voting ensemble.
Figure \ref{fig:post_example} provides an illustrative example of the post-processing pipeline. Due to the limited space, we only consider the top 15 answer spans from the original system outputs.
\subsubsection{Handling Sub-words}
\label{subsec:subword}
Before feeding the input to BERT, it must undergo the tokenization step.
Tokenization is the process of splitting a sentence into tokens.
For BERT, WordPiece tokenizer is commonly used as a subword tokenizer.
This makes the system susceptible to producing an output with incomplete words like "\RL{وفي الرقاب والغارم}" which will be penalized by the evaluation process,
\fontdimen2\font=0.80e
we perform a simple post-processing rule to extend or drop tokens such that we do not have broken words and
this simple rule produces a corresponding output \\
"\RL{وفي الرقاب والغارمين}",
\fontdimen2\font=.6 e
for the previously mentioned example. In Figure \ref{fig:post_example}, we dropped the sub-token "\RL{ون}" at rank 12 which is part of "\RL{ينالون}".
\fontdimen2\font=\origiwsp
\begin{figure*}[!t]
\centering
\includegraphics[page=1,width=1\textwidth]{figures/prr_sample.pdf}
\caption{A comprehensive example for post-processing.
Here we present the outputs of the system before post-processing (original outputs) on the right and after post-processing on the left.
We used green to highlight the ground truth answer or parts of it extracted by the system. Words and sub-words marked by red are dropped according to the rules \ref{subsec:subword} and
\ref{subsec:uninfor}.
Other colours used for highlighting text depict the high overlap among the predictions before post-processing.
}
\label{fig:post_example}
\end{figure*}
\subsubsection{Redundancy Elimination}
\label{subsec:no_overlap_post_process}
We analyzed the predictions of a variety of our fine-tuned models and discovered that most of the answer spans are highly overlapping with each other,
making the ranked list suboptimal with respect to the pRR metric in \ref{subsec:prr_metric}.
The rationale behind this is, the pRR metric \textit{only} considers the (k+1)$^{th}$ prediction
when there is no overlap with any of the ground-truth answer tokens for the k$^{th}$ prediction,
This implies repeating any of the words from the k$^{th}$ prediction in the (k+1)$^{th}$ prediction is suboptimal, which is a common behaviour exhibited by BERT for QA.
Here we present algorithm \ref{alg:no_overlap} which ensures the elimination of span overlap among the answers of a ranked list returned by the system.
An illustrative example showing the predictions before and after the application of this rule is given in Figure \ref{fig:post_example},
the colours used for highlighting text depict the high overlap between unprocessed answers, it clearly shows the span "\RL{ما كان لأهل المدينة}" is common in the first few unprocessed answers. \fontdimen2\font=.70001e
After applying this rule, the ranked list after post-processing better covers the text in the passage and the pRR score increases from $0.048$ to $0.769$ after post-processing.
Figure \ref{fig:histo} shows the distribution of the per-sample pRR score before and after post-processing,
the percentage of development samples of the first two bins after post-processing is reduced, which means we are less observing completely wrong answers after post-processing.
\fontdimen2\font=\origiwsp
\begin{algorithm}[!t]
\caption{Redundancy Elimination Algorithm}\label{alg:no_overlap}
\hspace*{10pt}\textbf{Input}: $P$, passage text; $A$, input answers list. \\
\hspace*{10pt}\textbf{Output}: post-processed answers list.
\begin{algorithmic}
\State $N_{P} \gets$ Number of words in $P$.
\State $M_{seen} \gets$ $0_{N_P}$ \Comment{Initialized to Zero}\\
\Comment{The mask used to track seen words}
\State $A_{post} \gets$: [] \Comment{Output Initialized to an empty list}\\
\For{\textbf{each} $a$ \textbf{in} $A$}
\State $s$ $\gets$ get start-word index of span $a$.
\State $e$ $\gets$ get end-word index of span $a$.
\State $a_{seen}$ $\gets$ $M_{seen}$[$s$:$e$] \\\Comment{Get seen slice of answer span $a$}
\If
{$a_{seen}$ has any zero}\\
{
\Comment{at least a word is not seen,}\\
\Comment{marked by 1 in $a_{seen}$}
\State $a_{\text{ unseen of } P}$ $\gets$ get\_unseen\_seqs($a_{seen}$,$P$)\\
\Comment{brings unseen contiguous sequences of words.}
\For{\textbf{each} $seq_\text{unseen}$ \textbf{in} $a_{\text{ unseen of } P}$}\\
\Comment{$seq_\text{unseen}$ is a subsequence of words }\\
\Comment{with $a_{seen}$ consisting of only zeros }
\fontdimen2\font=0.8ex
\State $s_{unseen}$ $\gets$ start-word index of $seq_\text{unseen}$.
\State $e_{unseen}$ $\gets$ end-word index of $seq_\text{unseen}$.
\State $seq_{text}$ $\gets$ text spanned by $seq_\text{unseen}$.
\fontdimen2\font=1ex
\\ \hspace*{42pt} $M_{seen}$[$s_{unseen}$: $e_{unseen}$] = 1
\hspace*{10.5pt} \\\Comment{Mark tokens as seen }\\
\hspace*{42pt} $A_{post}$ = $A_{post} \smile seq_{text}$
\\ \Comment{Append this unseen part of answer span $a$}
\EndFor \\
}
\EndIf
\EndFor
\end{algorithmic}
\end{algorithm}
\subsubsection{Uninformative Answer Removal}
\label{subsec:uninfor}In this post-processing rule, we remove the uninformative answers from the ranked list, We define an uninformative answer as having one of the following conditions:
\begin{enumerate
\item{
All of the stemmed answer tokens exist in the stemmed question tokens, for example, a question like "\RL{ما هي شجرة الزقوم?}" with a complete answer span predicted by the system "\RL{الزقوم}" is considered an uninformative answer.
}
\item{The whole answer span consists of stop-words, which can never meet the information need of a question in QRCD, for example, answer spans like "\RL{اذا}", "\RL{ليس}", "\RL{ثم}" are considered uninformative answers.}
\end{enumerate}
\vspace{-5pt}
Uninformative answers come from two sources, first, the original output of the BERT model without post-processing
and second, the post-processed outputs after removing redundant tokens as in \ref{subsec:no_overlap_post_process}.
For the example in Figure \ref{fig:post_example}, the answer at rank 1 "\RL{ما}" is rejected due to being uninformative.
\subsubsection{Updating the Ranked List}
After performing the post-processing pipeline described in \ref{subsec:no_overlap_post_process}, \ref{subsec:uninfor} and \ref{subsec:subword} in order,
we may end up with a new ranked list with more than 5 answer spans, we only consider the top 5 answer spans in the post-processed ranked list for the metric evaluation (pRR@5).
\begin{figure}[ht]
\centering
\includegraphics[page=1,width=.5\textwidth]{figures/histo.pdf}
\caption{The post-processing impact on the per-sample pRR score distribution, for this plot, we used the ouputs of the models marked with $\dagger$ in Table \ref{table:eval}.}
\label{fig:histo}
\end{figure}
\section{Experimental Evaluation}
\label{sec:eval}
\vspace{-0pt}
In this section, we report our trained models' results along with the official scores and run details on the Codalab competition.
\begin{table*}[ht]
\begin{center}
\begin{tabular}{|l|P{1.25cm}|P{1.2cm}|P{1.4cm}|}
\hline
\textbf{Single Models} & \textbf{EM} (\%) & \textbf{F1} (\%) & \textbf{pRR} (\%) \\
\hline
$^\dagger$arabertv02$_\text{Large}$ & 37.2 & 59.0 & \textbf{61.7} \\
$^\dagger$arabertv02$_\text{Base} $ & 36.5 & 58.5 & 60.7 \\
$^\dagger$ARBERT & 37.3 & 58.7 & 60.9 \\\Xhline{5\arrayrulewidth}
MARBERT & 32.1 & 51.5 & 53.9 \\
QARiB$_\text{Base}$ & 25.9 & 45.3 & 48.1 \\
\hline \multicolumn{4}{l}{ \vspace{-5pt} } \\
\hline
\textbf{Ensemble} & \textbf{EM} (\%) & \textbf{F1} (\%) & \textbf{pRR} (\%) \\
\hline
{Ensemble$_\textbf{Vanilla}$} & 39.4 & 59.4 & 63.97 \\
{{Ensemble$_\textbf{POST}$}} & 38.5 & 59.4 & \textbf{65.22} \\
\hline
\end{tabular}
\caption{
QRCD development split results, reported metrics for single models are averaged for a number of model checkpoints trained with different seeds,
while for the ensemble case, it is a single instance produced from combining different checkpoints.
\textbf{Ensemble$_\textbf{Vanilla}$} refers to combining 45 checkpoints of models indicated by $\dagger$ (15 for each).
\textbf{Ensemble$_\textbf{POST}$} represents the \textbf{Ensemble$_\textbf{Vanilla}$} output after post-processing.
}
\label{table:eval}
\end{center}
\end{table*}
\begin{table*}[ht]
\begin{center}
\begin{tabular}{|l|P{1.3cm}|P{1.3cm}|P{1.4cm}|}
\hline
\textbf{Run ID} & \textbf{EM} (\%) & \textbf{F1} (\%) & \textbf{pRR} (\%) \\
\hline
Ensemble$_\text{keep}$ & 26.8 & 48.5 & 55.7 \\
Ensemble$_\text{remove}$ & 26.8 & 50.0 & \textbf{56.6} \\
\hline
\end{tabular}
\caption{ Test phase official results on QRCD dataset,
Each ensemble reported is a span-voting ensemble combining all models in Table \ref{table:final_ensem}.
"keep" subscript refers to keeping uninformative answer spans as discussed in \ref{subsec:uninfor},
on the other hand, "remove" subscript points to removing uninformative answer spans.
}
\label{table:test}
\end{center}
\end{table*}
\subsection{Development Phase}
In this phase, we did not have access to the test dataset.
We trained our models on the training set as in \ref{subsec:training} while only saving the best performing model on the validation split.
We observed a large variation (around $\pm3\%$) in the pRR score reported for the same starting checkpoint with different seeds, we relate this to the small size of the validation split.
To enable fair comparison, we average the reported scores for the same model trained multiple times with different seeds as shown in Table \ref{table:eval}.
For the ensemble method, we considered 15 checkpoints with different seeds for each of AraBERT-v02$_\text{Large}$, AraBERT-v02$_\text{Base}$ and ARBERT (marked with $\dagger$ in the table), adding up to 45 experts, labelled as \textbf{Ensemble$_\textbf{Vanilla}$} in Table \ref{table:eval}.
After that, we performed the post-processing step on the ensemble outputs referred to as \textbf{Ensemble$_\textbf{POST}$} in Table \ref{table:eval}.
Also from the table, QARiB$_\text{Base}$ and MARBERT are performing worse on average, because of being primarily targeted for dialectal Arabic and social media text.
\subsection{Competition Final Testing Phase}
During the competition's final testing phase, we had access to the test dataset without labels, and participants were required to submit at most 3 submissions produced by their proposed systems.
We trained our models on both the training and development datasets as in \ref{subsec:training}. The trained models were combined in an ensemble as discussed in \ref{subsec:ensemble},
then we performed the post-processing.
Table \ref{table:final_ensem} shows the number of models used as experts for span-voting ensemble in the test phase.
In Table \ref{table:test}, we outline the official results obtained for our submissions.
All of them are ensemble-based due to the significant variations we observed in the development phase.
Combining \textbf{all} of the models in Table \ref{table:final_ensem} followed by post-processing the output predictions with uninformative span \textbf{removal} performs best,
this is marked in the table as \textbf{Ensemble$_\text{remove}$}.
\fontdimen2\font=.77e
There is a significant gap between the results in the development and test phases as in tables \ref{table:eval} and \ref{table:test} respectively,
we relate this to the small size of the validation split against the test split,
another reason is excluding 36 samples from the test split since their questions were similar to the public splits as indicated by the organizers in the official test phase results.
\fontdimen2\font=\origiwsp
\begin{table}[ht]
\begin{center}
\begin{tabular}{|l|P{1.9cm}|P{1.8cm}|P{1.3cm}|}
\hline
\textbf{Models} & \textbf{Num} \\
\hline
arabertv02$_\text{Large}$ & 16 \\
\hline
arabertv02$_\text{Base}$ & 18 \\
\hline
ARBERT & 17 \\
\hline
\end{tabular}
\caption{Number of models involved in the final ensemble of the test phase.}
\label{table:final_ensem}
\end{center}
\end{table}
\section{Conclusion and Future Work}
\label{sec:conc}
In this work, we leveraged the pre-trained Arabic language models to solve the \quran QA 2022 Shared Task.
We fine-tuned a variety of BERT models optimized for the Arabic language.
We proposed some post-processing operations to enhance the quality of answers aligning with the official measure.
Ensemble-based approaches are effective to produce more robust predictions.
In the future, we will further study how to incorporate a stacking ensemble approach with multiple stages to achieve better performance
rather than a voting ensemble as used in this study.
We will also investigate why we observed huge variations in the reported results
by performing extensive cross-validation.
\section{Acknowledgements}
We appreciate the efforts and assistance of Dr Moustafa Alzantot regarding the paper-writing phase,
and recommendations during the implementation.
\section{Bibliographical References}\label{reference}
\label{main:ref}
\bibliographystyle{lrec2022-bib}
| {'timestamp': '2022-06-06T02:13:38', 'yymm': '2206', 'arxiv_id': '2206.01550', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01550'} | arxiv |
\section{Introduction}
\label{sec:intro}
Neural ordinary differential equations (NODEs) \citep{ChenRBD18}
have opened a new perspective on continuous-time computation with neural networks (NNs) as a practical framework for machine learning based on differential equations.
While the original approach---proposed as a continuous-depth version of deep feed-forward residual NNs \citep{resnet, srivastava2015icml}---only covers autonomous ODEs entirely determined by the initial conditions,
more recent
extensions deal with sequential data (reviewed in Sec.~\ref{sec:back_ode}) in a way similar to what is typically done with standard recurrent NNs (RNNs) in the discrete-time scenario.
This potential for continuous-time (CT) sequence processing (CTSP) is particularly interesting, since there are many applications where datapoints are observed at irregularly spaced time steps,
and CT sequence models might better deal with such data than their discrete-time counterparts.
However, the development of NODEs for CTSP is still at an early stage.
For example, a popular approach of Neural Controlled Differential Equations \citep{KidgerMFL20} (NCDEs; also reviewed in Sec.~\ref{sec:back_ode})
has in practice only one architectural variant corresponding to the ``vanilla'' RNN \citep{elman1990finding}.
Discrete-time processing, however, exploits many different RNN architectures as well as Transformers \citep{trafo}.
While it is not straightforward to transform the standard Transformer into a CT sequence processor,
we'll show that the closely related Fast Weight Programmers (FWPs) \citep{Schmidhuber:91fastweights, schlag2021linear, irie2021going} and linear Transformers \citep{katharopoulos2020transformers} (reviewed in Sec.~\ref{sec:back_fwp}) have direct CT counterparts.
In FWPs, temporal processing of short-term memory (stored in fast weight matrices) uses learnable sequences of \textit{learning rules}. Hence
CT versions of FWPs will require differential equations to model the learning rules.
This relates to an ancient trend of the 1980s/90s.
Among many old connections between NNs and dynamical systems described by ODEs (e.g., \citep{funahashi1993approximation, lapedes1987nonlinear, pineda1987generalization, pearlmutter1989learning, sato1991learning, rico1992discrete}),
the theoretical analysis of NN learning rules in the ODE framework has been particularly fruitful.
Consider the famous example of Oja's rule \citep{oja1982simplified} (briefly reviewed in Sec.~\ref{sec:back_lr}): many results on its stability, convergence, and connection to Principle Component Analysis \citep{pearson1901liii, hotelling1933analysis} were obtained using its ODE counterpart (e.g., \citep{oja1982simplified, oja1985stochastic, oja1989neural, plumbley1995lyapunov, hornik1992convergence, sanger1989optimal, WyattE95, fort1996convergence}).
Here we propose a novel combination of Neural ODEs
and learning rules, to
obtain a new class of sequence processing Neural ODEs which are continuous-time counterparts of Fast Weight Programmers and linear Transformers.
To the best of our knowledge,
there is no previous work on Neural ODE-based Transformer families, despite their dominance in important types of discrete time computations such as Natural Language Processing and beyond.
We also show how our approach solves the fundamental limitation of existing Neural CDEs in terms of model size scalability.
We conduct experiments on three standard
time series classification tasks
covering various scenarios (regularly sampled, irregularly sampled with missing values, and very long time series).
We demonstrate that our novel models outperform existing Neural ODE-based sequence processors, in some cases by a large margin.
\section{Background}
\label{sec:background}
We briefly review the main background concepts this work builds upon: NODEs for sequence processing (Sec.~\ref{sec:back_ode}), NN learning rules and their connection to ODEs (Sec.~\ref{sec:back_lr}), and Fast Weight Programmers whose memory update is based on learning rules controlled by an NN (Sec.~\ref{sec:back_fwp}).
\subsection{Neural ODEs (NODEs) and Their Extensions for Sequence Processing}
\label{sec:back_ode}
Here we review the core idea of NODEs \citep{ChenRBD18}.
In what follows, let $n$, $N$, $d$, $d_\text{in}$ denote positive integers, $T$ be a positive real number, and $\theta$ denote an arbitrary set of real numbers.
The first step is to consider a
residual layer (say, the $n$-th layer with a dimension $d$) in an $N$-layer deep NN
which transforms an input ${\bm{h}}_{n-1} \in \mathbb{R}^{d}$ to an output ${\bm{h}}_{n} \in \mathbb{R}^{d}$ with a parameterised function ${\bm{f}}_\theta: \mathbb{R}^{d} \rightarrow \mathbb{R}^{d}$ as follows:
\begin{eqnarray}
\label{eq:resnet}
{\bm{h}}_n = {\bm{h}}_{n-1} + {\bm{f}}_\theta({\bm{h}}_{n-1})
\end{eqnarray}
This coincides \citep{weinan2017proposal, Haber_2017, HaberRHJ18, ChangMHRBH18, LuZLD18, ChangMHTB18, CicconeGMOG18, ChenRBD18} with the following equation for $\epsilon=1$
\begin{eqnarray}
{\bm{h}}({t_n}) = {\bm{h}}({t_{n-1}}) + \epsilon {\bm{f}}_\theta({\bm{h}}({t_{n-1}}))
\end{eqnarray}
where ${\bm{h}}: [0, T] \rightarrow \mathbb{R}^d$ is a function such that ${\bm{h}}(t_n) = {\bm{h}}_n$ holds for all $n: 0\leq n \leq N$ and $t_n \in [0, T]$ such that $t_n-t_{n-1} = \epsilon > 0$ if $n \geq 1$.
This equation is a forward Euler discretisation of the ordinary differential equation defined for all $t \in (t_0, T]$ as
\begin{eqnarray}
{\bm{h}}'(t) = {\bm{f}}_\theta({\bm{h}}(t)) \quad \text{or} \quad {\bm{h}}(t) = {\bm{h}}(t_0) + \int_{s=t_0}^t {\bm{f}}_\theta({\bm{h}}(s))ds
\end{eqnarray}
where ${\bm{h}}'$ denotes the first order derivative.
This establishes the connection between the ODE and the deep residual net with parameters $\theta$ shared across layers\footnote{Or we make $\theta$ dependent of $t$ such that parameters are ``depth/layer-dependent'' as in standard deep nets.}:
given the initial condition ${\bm{h}}(t_0)={\bm{h}}_0$,
the solution to this equation evaluated at time $T$, i.e., ${\bm{h}}(T)$, corresponds to the output of this deep residual NN, which can be computed by an ODE solver.
We denote it
as a function $\mathrm{ODESolve}$ taking four variables: ${\bm{h}}(T) = \mathrm{ODESolve}({\bm{f}}_\theta, {\bm{h}}_0, t_0, T)$.
During training, instead of backpropagating though the ODE solver's operations,
the \textit{adjoint sensitivity method} \citep{pontryagin1962}
(which essentially solves another ODE but backward in time) can compute gradients with $O(d)$ memory requirement, constant w.r.t.~$T$ \citep{ChenRBD18}.
A natural next step is to extend this formulation for RNNs,
i.e., the index $n$ now denotes the time step,
and we assume an external input ${\bm{x}}_n \in \mathbb{R}^{d_\text{in}}$ at each step $n$ to update the hidden state ${\bm{h}}_{n-1}$ to ${\bm{h}}_n$ as
\begin{eqnarray}
\label{eq:rnn}
{\bm{h}}_n = {\bm{f}}_\theta({\bm{h}}_{n-1}, {\bm{x}}_n)
\end{eqnarray}
Depending on the property of external inputs $({\bm{x}}_n)_{n=1}^N = ({\bm{x}}_1,..., {\bm{x}}_N)$, there are different ways of defining NODEs for sequence processing.
We mainly distinguish three cases.
\textbf{First}, when there is a possibility to construct a \textit{differentiable} control signal ${\bm{x}}:t\mapsto {\bm{x}}(t) \in \mathbb{R}^{d_\text{in}}$ for $t \in [t_0, T]$ from the inputs $({\bm{x}}_n)_{n=1}^N$; an attractive approach by
\citet{KidgerMFL20} handles the corresponding dynamics in a \textit{neural controlled differential equation} (NCDE):
\begin{eqnarray}
\label{eq:cde}
{\bm{h}}(t) = {\bm{h}}(t_0) + \int_{s=t_0}^t {\bm{F}}_\theta({\bm{h}}(s))d{\bm{x}}(s) = {\bm{h}}(t_0) + \int_{s=t_0}^t {\bm{F}}_\theta({\bm{h}}(s)){\bm{x}}'(s)ds
\end{eqnarray}
where ${\bm{F}}_\theta$ is a parameterised function (typically a few-layer NN) which maps a vector ${\bm{h}}(s) \in \mathbb{R}^d$ to a matrix ${\bm{F}}_\theta({\bm{h}}(s)) \in \mathbb{R}^{d \times d_{\text{in}}}$ (we'll discuss how this component already relates to Fast Weight Programmers) and thus, ${\bm{F}}_\theta({\bm{h}}(s))d{\bm{x}}(s)$ denotes a matrix-vector multiplication.
The \textit{control} ${\bm{x}}: [t_0, T] \rightarrow \mathbb{R}^{d_\text{in}}$ is typically \citep{KidgerMFL20} constructed via natural cubic spline over all data points $({\bm{x}}_n)_{n=1}^N$ such that its differentiability is guaranteed (which, however, makes it incompatible with auto-regressive processing \citep{morrill2021neural}).
Since the final equation is again an NODE with a vector field of form ${\bm{g}}_{\theta, {\bm{x}}'}(s, {\bm{h}}(s)) = {\bm{F}}_\theta({\bm{h}}(s)){\bm{x}}'(s)$,
all methods described above are applicable: ODE solver for evaluation and adjoint method for memory efficient training.
A notable extension
of Neural CDEs is the use of \textit{log-signatures} to sub-sample the input sequence \citep{morrillSKF21}.
Resulting NCDEs are called \textit{neural rough differential equations} (NRDEs),
which are relevant for processing long sequences.
On a side note, the NCDE is often referred to as the ``continuous-time analogue'' to RNNs \citep{KidgerMFL20}, but this is a bit misleading:
discrete-time RNN equations corresponding to the continuous-time Eq.~\ref{eq:cde}
do not reflect the standard RNN of Eq.~\ref{eq:rnn}
but:
\begin{align}
\label{eq:cde_discrete_1}
{\bm{h}}_n &= {\bm{h}}_{n-1} + {\bm{W}}_{n-1} ({\bm{x}}_n -{\bm{x}}_{n-1}) \\
\label{eq:cde_discrete_2}
{\bm{W}}_{n} & = {\bm{F}}_\theta({\bm{h}}_{n})
\end{align}
where one network (Eq.~\ref{eq:cde_discrete_1}) learns to translate the variation of inputs $({\bm{x}}_n -{\bm{x}}_{n-1})$ into a change in the state space using a weight matrix ${\bm{W}}_{n-1}$ which itself is generated by another network (${\bm{F}}_\theta : \mathbb{R}^{d} \rightarrow \mathbb{R}^{d \times d_\text{in}}$; Eq.~\ref{eq:cde_discrete_2}) on the fly from the hidden state.
This model is thus a kind of Recurrent FWP \citep{irie2021going, schmidhuber1993reducing, ha2017hypernetworks}.
\textbf{Second}, even if ${\bm{x}}$ is not differentiable, having access to ${\bm{x}}$ defined and bounded over an interval of interest $[t_0, T]$ is enough to define a sequence processing NODE, by making it part of the vector field:
\begin{eqnarray}
\label{eq:direct-ode}
{\bm{h}}(t) = {\bm{h}}(t_0) + \int_{s=t_0}^t {\bm{f}}_\theta({\bm{h}}(s), {\bm{x}}(s))ds
\end{eqnarray}
where the vector field ${\bm{f}}_\theta({\bm{h}}(t), {\bm{x}}(t)) = {\bm{g}}_{\theta, {\bm{x}}}(t, {\bm{h}}(t))$
can effectively be evaluated at any time $t \in [t_0, T]$.
We refer to this second approach as a \textit{direct NODE} method.
While \citet{KidgerMFL20} theoretically and empirically show that this approach is less expressive than the NCDEs above,
we'll show how in our case of learning rules one can derive interesting models within this framework, which empirically perform on par with the CDE variants.
\textbf{Finally}, when no control function is available (i.e., we only have access to ${\bm{x}}_n$ at discrete time steps $(t_n)_{n=1}^N$), a mainstream approach consists in dissociating
the continuous-time hidden state update via ODE for the time between two observations (e.g., Eq.~\ref{eq:ode-rnn-ode} below) from
integration of the new data (Eq.~\ref{eq:ode-rnn-rnn} below).
Notable examples of this category include ODE-RNNs \citep{RubanovaCD19, BrouwerSAM19}
which transform the hidden states ${\bm{h}}_{n-1}$ to ${\bm{h}}_n$ for each observation ${\bm{x}}_n$ available at time $t_n$ as follows:
\begin{eqnarray}
\label{eq:ode-rnn-ode}
{\bm{u}}_n &=& \mathrm{ODESolve}({\bm{f}}_{\theta_1}, {\bm{h}}_{n-1}, t_{n-1}, t_n) \\
\label{eq:ode-rnn-rnn}
{\bm{h}}_n &=& \bm{\phi}_{\theta_2}({\bm{x}}_{n}, {\bm{u}}_{n})
\end{eqnarray}
where Eq.~\ref{eq:ode-rnn-ode} autonomously updates the hidden state between two observations using a function ${\bm{f}}_{\theta_1}$ parameterised by $\theta_1$, while
in Eq.~\ref{eq:ode-rnn-rnn},
function $\bm{\phi}_{\theta_2}$ parameterised by $\theta_2$
integrates the new input ${\bm{x}}_n$ into the hidden state.
In Latent ODE-RNN \citep{RubanovaCD19}, a popular extension of this approach to the variational setting, the initial recurrent state ${\bm{h}}_0$
is sampled from a prior (during training, an additional encoder is trained to map sequences of inputs to parameters of the prior).
While this third case is not our focus, we'll also present how to use FWPs in this scenario in Sec.~\ref{sec:ode_rfwp} for the sake of completeness.
\subsection{Learning Rules and Their Connections to ODEs}
\label{sec:back_lr}
Learning rules of artificial NNs describe the process which modifies their weights in response to some inputs.
This includes the standard backpropagation rule (also known as the reverse mode of automatic differentiation) derived for the case of supervised learning, as well as rules inspired by Hebb's informal rule \citep{hebb1949organization} in ``unsupervised'' settings.
Here we focus on the latter.
Let $n$, $d_\text{in}$ $d_\text{out}$ be positive integers.
Given a linear layer with a weight matrix ${\bm{W}}_{n} \in \mathbb{R}^{d_\text{out} \times d_\text{in}}$ (the single output neuron case $d_\text{out}=1$ is the focus of the classic works) at time $n$ which transforms input ${\bm{x}}_{n} \in \mathbb{R}^{d_\text{in}}$ to output ${\bm{y}}_{n} \in \mathbb{R}^{d_\text{out}}$ as
\begin{eqnarray}
\label{eq:hebb}
{\bm{y}}_{n} &=& {\bm{W}}_{n-1} {\bm{x}}_n
\end{eqnarray}
the pure Hebb-style additive learning rule modifies the weights according to
\begin{eqnarray}
\label{eq:hebb_update}
{\bm{W}}_n &=& {\bm{W}}_{n-1} + \eta_n {\bm{y}}_{n} \otimes {\bm{x}}_n
\end{eqnarray}
where $\otimes$ denotes outer product and $\eta_n \in \mathbb{R}_{+}$ is a learning rate at time $n$.
\citet{oja1982simplified} proposed stability improvements to this rule through a decay term
\begin{eqnarray}
\label{eq:oja_82}
{\bm{W}}_n = {\bm{W}}_{n-1} + \eta_n {\bm{y}}_n \otimes ({\bm{x}}_n - {\bm{W}}_{n-1}^\top {\bm{y}}_n)
\end{eqnarray}
whose theoretical analysis has since the 1980s been a subject of many researchers covering stability, convergence, and relation to Principal Component Analysis \citep{oja1982simplified, oja1985stochastic, oja1989neural, plumbley1995lyapunov, hornik1992convergence, sanger1989optimal, WyattE95, fort1996convergence, ChouW20}.
One key approach for such theoretical analysis is to view the equation above as a discretisation of the following ODE:
\begin{eqnarray}
\label{eq:oja_ode_original}
{\bm{W}}'(t) = \eta(t) {\bm{y}}(t) \otimes ({\bm{x}}(t) - {\bm{W}}(t-1)^\top {\bm{y}}(t))
\end{eqnarray}
On a related note, the study of RNNs has also profited from ODEs \citep{zhang2014comprehensive, fermanian2021framing}.
\subsection{Fast Weight Programmers \& Linear Transformers}
\label{sec:back_fwp}
Fast Weight Programmers (FWP; \citep{Schmidhuber:91fastweights, schlag2021linear, irie2021going}) are general-purpose (auto-regressive) sequence processing NNs.
In general,
an FWP is a system of two NNs: a \textit{slow} NN, the \textit{programmer}, rapidly generates during runtime weight changes of another neural network, the \textit{fast} NN.
The (slow) weights of the slow net are typically trained by gradient descent.
Variants of FWPs whose weight generation is based on outer products between keys and values \citep{Schmidhuber:91fastweights} have been shown \citep{schlag2021linear} to be equivalent to Linear Transformers \citep{katharopoulos2020transformers}
(using the mathematical equivalence known from perceptron/kernel machine duality \citep{aizerman1964theoretical, irie2022dual}).
These FWPs use sequences of learning rules to update short-term memory in form of a fast weight matrix.
A practical example of such FWPs is the DeltaNet \citep{schlag2021linear} which transforms an input ${\bm{x}}_n \in \mathbb{R}^{d_\text{in}}$ into an output ${\bm{y}}_n \in \mathbb{R}^{d_\text{out}}$ at each time step $n$ while updating its fast weight matrix ${\bm{W}}_{n-1} \in \mathbb{R}^{d_\text{out} \times d_\text{key} }$ as follows:
\begin{eqnarray}
\label{eq:proj}
\beta_n, {\bm{q}}_n, {\bm{k}}_n, {\bm{v}}_n &=& {\bm{W}}_\text{slow}{\bm{x}}_n\\
\label{eq:lr}
{\bm{W}}_n &=& {\bm{W}}_{n-1} + \sigma(\beta_n)({\bm{v}}_n - {\bm{W}}_{n-1} \phi({\bm{k}}_n)) \otimes \phi({\bm{k}}_n) \\
{\bm{y}}_n &=& {\bm{W}}_n \phi({\bm{q}}_n) \label{eq:fw_get}
\end{eqnarray}
where the slow net (Eq.~\ref{eq:proj}; with weights ${\bm{W}}_\text{slow} \in \mathbb{R}^{(1 + 2 *d_\text{key} + d_\text{out}) \times d_\text{in}}$) generates vectors key ${\bm{k}}_n \in \mathbb{R}^{d_\text{key}}$ and value ${\bm{v}}_n \in \mathbb{R}^{d_\text{out}}$ as well as a scalar $\beta_n \in \mathbb{R}$ to obtain a dynamic learning rate by applying a sigmoid function $\sigma$, and $\phi$ is an element-wise activation function
whose output elements are positive and sum up to one (typically softmax).
These fast dynamic variables generated by a slow NN are used in
a learning rule (Eq.~\ref{eq:lr}) akin to the classic delta rule \citep{widrow1960adaptive}
to update the fast weight matrix.
The output is finally produced by the forward computation of the fast NN, i.e., by
\textit{querying} the fast weight matrix by the generated query vector ${\bm{q}}_n \in \mathbb{R}^{d_\text{key}}$ (Eq.~\ref{eq:fw_get}).
An intuitive interpretation of the fast weight matrix is a key-value associative memory with
write and read operations defined by Eq.~\ref{eq:lr} and \ref{eq:fw_get}, respectively.
This encourages intuitive thoughts about memory capacity (limited by the number of ``keys'' we can store without interference) \citep{schlag2021linear}.
For instance, if we replace the learning rule (i.e., memory writing operation) of Eq.~\ref{eq:lr} by a pure additive Hebb-style rule (and a fixed learning rate of 1.0): ${\bm{W}}_n = {\bm{W}}_{n-1} + {\bm{v}}_n \otimes \phi({\bm{k}}_n)$, we obtain the Linear Transformer \citep{katharopoulos2020transformers} (we refer to prior work \citep{schlag2021linear} for further explanations of the omission of attention normalisation).
Such a purely additive learning rule often suffers from long term dependencies, unlike the delta rule \citep{schlag2021linear}.
We'll confirm this trend also in the CT models (using the EigenWorms dataset).
For later convenience, we introduce a function $\mathrm{FWP}$ which denotes generic FWP operations:
${\bm{y}}_n, {\bm{W}}_n = \mathrm{FWP}({\bm{x}}_n, {\bm{W}}_{n-1}; {\bm{W}}_\text{slow})$.
\section{Continuous-Time Fast Weight Programmers}
\label{sec:ct_fwp}
We propose continuous-time counterparts of Fast Weight Programmers (Sec.~\ref{sec:back_fwp})
which naturally combine ODEs for learning rules (Sec.~\ref{sec:back_lr}) and existing approaches for sequence processing with NODEs (Sec.~\ref{sec:back_ode}).
We present three types of these CT FWP models in line with
the categorisation of Sec.~\ref{sec:back_ode} while the main focus of this work is on the two first cases.
\subsection{Direct NODE-based FWPs}
\label{sec:sub_direct_ode}
In the \textit{direct NODE} approach (reviewed in Sec.~\ref{sec:back_ode}),
we assume a (bounded) control signal ${\bm{x}}: t\mapsto {\bm{x}}(t)$ defined over an interval $[t_0, T]$.
We make it part of the vector field to define an ODE describing a \textit{continuous-time learning rule} for a fast weight matrix ${\bm{W}}(t)$:
\begin{eqnarray}
\label{eq:ode-lr}
{\bm{W}}(t) = {\bm{W}}(t_0) + \int_{s=t_0}^t {\bm{F}}_\theta({\bm{W}}(s), {\bm{x}}(s))ds
\end{eqnarray}
where ${\bm{W}}: t\mapsto {\bm{W}}(t) \in \mathbb{R}^{d_\text{out} \times d_\text{key}}$ is a function defined on $[t_0, T]$,
and ${\bm{F}}_\theta$ is an NN parameterised by $\theta$ which maps onto $\mathbb{R}^{d_\text{out} \times d_\text{key}}$.
This is a neural differential equation for
learning to train a neural net through continuous learning rules, that is,
to train a fast weight matrix ${\bm{W}}(t)$ of a fast NN (Eq.~\ref{eq:querying_2} below) for each sequential control ${\bm{x}}$.
Like in the discrete-time FWPs (Sec.~\ref{sec:back_fwp}), the output ${\bm{y}}(T) \in \mathbb{R}^{d_\text{out}}$ is obtained by \textit{querying} this fast weight matrix\footnote{In practice, we also apply element-wise activation functions to query/key/value vectors where appropriate, which we omit here for readability. We refer to Appendix \ref{app:model} for further details.} (e.g., at the last time step $T$):
\begin{align}
\label{eq:querying_1}
{\bm{q}}(T) &= {\bm{W}}_q {\bm{x}}(T) \\
\label{eq:querying_2}
{\bm{y}}(T) &= {\bm{W}}(T) {\bm{q}}(T)
\end{align}
where ${\bm{W}}_q \in \mathbb{R}^{d_\text{key} \times d_\text{in}}$ is a slow weight matrix used to generate the query ${\bm{q}}(T) \in \mathbb{R}^{d_\text{key}}$ (Eq.~\ref{eq:querying_1}).
Now we need to specify ${\bm{F}}_\theta$ in Eq.~\ref{eq:ode-lr} to fully define the learning rule.
We focus on three variants:
\begin{align}
\label{eq:direct_ode}
{\bm{F}}_\theta({\bm{W}}(s), {\bm{x}}(s))
&= \sigma(\beta(s))
\begin{cases}
{\bm{k}}(s) \otimes {\bm{v}}(s) & \text{Hebb-style}\\
{\bm{v}}(s) \otimes \big({\bm{k}}(s) - {\bm{W}}(s)^\top {\bm{v}}(s) \big) & \text{Oja-style}\\
\big({\bm{v}}(s) - {\bm{W}}(s){\bm{k}}(s)\big) \otimes {\bm{k}}(s)& \text{Delta-style}
\end{cases}
\end{align}
where $[\beta(s), {\bm{k}}(s), {\bm{v}}(s)] = {\bm{W}}_\text{slow} {\bm{x}}(s)$ with a slow weight matrix ${\bm{W}}_\text{slow} \in \mathbb{R}^{(1 + d_\text{key} + d_\text{out}) \times d_\text{in}}$.
As in the discrete-time FWP (Sec.~\ref{sec:back_fwp}), the slow NN generates
$\beta(s) \in \mathbb{R}$ (to which we apply the sigmoid function $\sigma$ to obtain a learning rate),
key ${\bm{k}}(s) \in \mathbb{R}^{d_\text{key}}$ and value ${\bm{v}}(s) \in \mathbb{R}^{d_\text{out}}$ vectors from input ${\bm{x}}(s)$.
These variants are inspired by the respective classic learning rules of the same name, while they are crucially different from the classic ones in the sense that all variables involved (key, value, learning rate)
are continually generated by the slow NN.
In the experimental section, we'll comment on how some of these design choices can result in task-dependent performance gaps.
In practice, we use the \textit{multi-head} version of the operations above (i.e., by letting $H \in \mathbb{N}$ denote the number of heads, query/key/value vectors are split into $H$ sub-vectors and Eqs.~\ref{eq:querying_2}-\ref{eq:direct_ode} are conducted independently for each head). The output is followed by the standard feed-forward block like in Transformers \citep{trafo}.
Possible extensions for deeper models are discussed in Appendix \ref{app:deeper}.
\subsection{NCDE based FWPs}
\label{sec:cde-lr}
Here we present models based on NCDEs (reviewed in Sec.~\ref{sec:back_ode}).
We assume availability of a differentiable control signal ${\bm{x}}(t)$, whose first order derivative is denoted by ${\bm{x}}'(t)$.
Given the NCDE formulation of Eq.~\ref{eq:cde},
the most straight-forward approach to obtain a CT Fast Weight Programmer is to extend the dimensionality of the recurrent hidden state, i.e., we introduce
a parameterised function ${\tens{F}}_\theta$ which maps a matrix ${\bm{W}}(t) \in \mathbb{R}^{d_\text{out} \times d_\text{key}}$
to a third-order tensor ${\tens{F}}_\theta({\bm{W}}(t)) \in \mathbb{R}^{d_\text{out} \times d_\text{key} \times d_\text{in}}$:
\begin{eqnarray}
\label{eq:cde-lr}
{\bm{W}}(t) = {\bm{W}}(t_0) + \int_{s=t_0}^t {\tens{F}}_\theta({\bm{W}}(s))d{\bm{x}}(s) = {\bm{W}}(t_0) + \int_{s=t_0}^t {\tens{F}}_\theta({\bm{W}}(s)){\bm{x}}'(s)ds
\end{eqnarray}
However, this approach is obviously not scalable since the input and output dimensions ($d_\text{out} \times d_\text{key}$ and $d_\text{out} \times d_\text{key} \times d_\text{in}$) of ${\tens{F}}_\theta$ can be too large in practice.
A more tractable CDE-based approach can be obtained by providing ${\bm{x}}$ and/or ${\bm{x}}'$ to the vector field:
\begin{eqnarray}
\label{eq:cde-lr-x-dx}
{\bm{W}}(t) = {\bm{W}}(t_0) + \int_{s=t_0}^t {\tens{F}}_\theta({\bm{W}}(s), {\bm{x}}(s), {\bm{x}}'(s)){\bm{x}}'(s)ds
\end{eqnarray}
While this equation still remains a CDE because of the multiplication from the right by $d{\bm{x}}={\bm{x}}'(s)ds$,
the additional inputs to the vector field offer a way of making use of various learning rules, as in the case of direct NODE approach above (Sec.~\ref{sec:sub_direct_ode}).
To be specific, either ${\bm{x}}$ and ${\bm{x}}'$ or only ${\bm{x}}'$ is required in the vector field to obtain these tractable CDEs.
Here we present the version which uses both ${\bm{x}}$ and ${\bm{x}}'$ \footnote{
The equations for the version using only ${\bm{x}}'$ can be obtained by replacing ${\bm{x}}$ by ${\bm{x}}'$ in Eq.~\ref{eq:cde_lr}.
We provide an ablation in Appendix \ref{app:cde_variants}.
As a side note, we also obtain the equation for the CDE using only ${\bm{x}}'$ by replacing ${\bm{x}}$ by ${\bm{x}}'$ in Eq.~\ref{eq:ode-lr} for the direct NODE case.}.
The resulting vector fields for different cases are:
\begin{align}
\label{eq:cde_lr}
{\tens{F}}_\theta\big({\bm{W}}(s), {\bm{x}}(s), {\bm{x}}'(s)\big){\bm{x}}'(s)
&= \sigma(\beta(s))
\begin{cases}
{\bm{W}}_k {\bm{x}}(s) \otimes {\bm{W}}_v {\bm{x}}'(s) & \text{Hebb}\\
\big({\bm{W}}_k {\bm{x}}(s) - {\bm{W}}(s)^\top {\bm{W}}_v {\bm{x}}'(s) \big) \otimes {\bm{W}}_v {\bm{x}}'(s) & \text{Oja} \\
\big({\bm{W}}_v {\bm{x}}(s) - {\bm{W}}(s){\bm{W}}_k {\bm{x}}'(s)\big) \otimes {\bm{W}}_k {\bm{x}}'(s) & \text{Delta}
\end{cases}
\end{align}
As can be seen above, the use of CDEs to describe a continuous fast weight learning rule thus naturally results in a key/value memory where ${\bm{x}}'$ is used to generate either key or value vectors.
Because of the multiplication from the right by ${\bm{x}}'$, the role of ${\bm{x}}'$ changes
depending on the choice of learning rule: ${\bm{x}}'$ is used to generate the key in the Delta case but the value vector in the case of Oja.
In the case of Hebb, the choice made in Eq.~\ref{eq:cde_lr} of using ${\bm{x}}$ for keys and ${\bm{x}}'$ for values is arbitrary since Eq.~\ref{eq:cde_lr} is symmetric in terms of roles of keys and values (see an ablation study in Appendix \ref{app:cde_variants} for the other case where we use ${\bm{x}}'$ to generate the key and ${\bm{x}}$ for the value).
The querying operation (analogous to Eqs.~\ref{eq:querying_1}-\ref{eq:querying_2} for the direct NODE case) is also modified accordingly, depending on the choice of learning rule, such that the same input (${\bm{x}}$ or ${\bm{x}}'$) is used to generate both key and query:
\begin{align}
\label{eq:cde_fwp_query}
{\bm{y}}(T) &=
\begin{cases}
{\bm{W}}(T)^\top {\bm{W}}_q {\bm{x}}(T)& \text{Hebb and Oja}\\
{\bm{W}}(T) {\bm{W}}_q {\bm{x}}'(T) & \text{Delta}
\end{cases}
\end{align}
Note that since the proposed vector field ${\tens{F}}_\theta\big({\bm{W}}(s), {\bm{x}}(s), {\bm{x}}'(s)\big){\bm{x}}'(s)$ is more general than the one used in the original NCDE ${\tens{F}}_\theta\big({\bm{W}}(s)\big){\bm{x}}'(s)$,
any theoretical results on the CDE remain valid (which, however, does not tell us anything about the best choice for its exact parameterisation).
\subsection{ODE-RFWP and Latent ODE-RFWP}
\label{sec:ode_rfwp}
The main focus of this work is the setting of \citet{KidgerMFL20} where we assume the existence of some control signal ${\bm{x}}$.
However, here we also show a way of using FWPs in the third case where
no control ${\bm{x}}(t)$ is available, i.e., we only have access to discrete observations $({\bm{x}}_n)_{n=0}^N$.
Here we cannot directly define the vector field involving continuous transformations using the inputs.
We follow the existing approaches (ODE-RNN or Latent ODE; Sec.~\ref{sec:back_ode}) which use two separate update functions:
A discrete recurrent state update is executed every time a new observation is available to the model, while a continuous update using an autonomous ODE is conducted in between observations.
Unlike with standard recurrent state vectors, however, it is not practical to autonomously evolve high-dimensional fast weight matrices (which would require an expressive matrix to matrix transformation).
We therefore opt for using a Recurrent FWP (RFWP) \citep{irie2021going} and combine it with an ODE:
\begin{eqnarray}
\label{eq:ode-rfwp-ode}
{\bm{u}}_n &=& \mathrm{ODESolve}({\bm{f}}_{\theta_1}, {\bm{h}}_{n-1}, t_{n-1}, t_n) \\
\label{eq:ode-rfwp-rnn}
{\bm{h}}_n, {\bm{W}}_{n} &=& \mathrm{FWP}([{\bm{x}}_{n}, {\bm{u}}_{n}], {\bm{W}}_{n-1}; \theta_2)
\end{eqnarray}
where we keep the fast weight learning rule itself discrete (Eq.~\ref{eq:ode-rfwp-rnn}), but evolve the recurrent state vector ${\bm{u}}_n$ using an ODE (Eq.~\ref{eq:ode-rfwp-ode}) such that the information to be read/written to the fast weight matrix is controlled by a variable which is continuously updated between observations.
We refer to this model as ODE-RFWP and its variational variant as Latent ODE-RFWP.
While this case is not of central interest to the present work, as the learning rule remains discrete (Eq.~\ref{eq:ode-rfwp-rnn}), we also provide some experimental results (for model-based reinforcement learning settings) in Appendix \ref{app:rl}.
\section{Experiments}
\label{sec:exp}
We consider three datasets covering three types of time series which are
regularly sampled (Speech Commands \citep{warden2018speech}),
irregularly sampled with partially missing features (PhysioNet Sepsis \citep{ReynaJSJSWSNC19}),
or very long (EigenWorms \citep{bagnall2018uea}).
We compare the proposed direct NODE and CDE based FWP models (Sec.~\ref{sec:sub_direct_ode} \& \ref{sec:cde-lr}) to NODE baselines
previously reported on the same datasets \citep{KidgerMFL20, morrill2021neural}.
Appendix \ref{app:exp_detail} provides further experimental details.
\begin{table}[t]
\caption{\textbf{Accuracy (\%) on the Speech Commands classification task} and \textbf{AUR ($\times 10^2$) on the PhysioNet Sepsis prediction task}.
PhysioNet has two cases: with (OI) or without (no-OI) observational intensity (see text for details).
Numbers marked by * are taken from \citet{KidgerMFL20}.
Mean and standard deviation (std) are computed over 5 runs.
}
\label{tab:speech}
\begin{center}
\begin{tabular}{llcrr}
\toprule
\multirow{2}{*}{Type} & \multirow{2}{*}{Model} & \multicolumn{1}{c}{\multirow{2}{*}{Speech Commands}} & \multicolumn{2}{c}{PhysioNet Sepsis} \\ \cmidrule(r){4-5}
& & & \multicolumn{1}{c}{OI} & \multicolumn{1}{c}{no-OI} \\ \midrule
\multirow{1}{*}{Direct NODE}
& GRU-ODE \citep{KidgerMFL20}* & 47.9 (2.9) & 85.2 (1.0) & 77.1 (2.4) \\ \cmidrule(r){2-5}
& Hebb & 82.8 (1.1) & 88.1 (3.5) & 81.2 (2.5) \\
& Oja & \textbf{85.4 (0.9)} & \textbf{88.8 (0.9)} & 82.5 (1.1) \\
& Delta & 81.5 (3.8) & 87.9 (3.0) & \textbf{83.8 (3.7)} \\ \midrule
\multirow{1}{*}{CDE} & NCDE \citep{KidgerMFL20}* & 89.8 (2.5) & 88.0 (0.6) & 77.6 (0.9) \\ \cmidrule(r){2-5}
& Hebb & 89.5 (0.3) & 89.7 (0.3) & \textbf{84.5 (1.9)}\\
& Oja & 90.0 (0.7) & 89.8 (2.5) & 79.6 (4.7) \\
& Delta & \textbf{90.2 (0.2)} & \textbf{90.4 (0.6)} & 83.5 (5.4) \\
\bottomrule
\end{tabular}
\end{center}
\end{table}
\paragraph{Speech Commands.}
The Speech Commands \citep{warden2018speech} is a single word speech recognition task.
The datapoints are regularly sampled, and the sequence lengths are relatively short ($\leq$ 160 frames), which makes this task a popular sanity check.
Following prior work on neural CDEs \citep{KidgerMFL20},
we use 20 mel frequency cepstral coefficients as speech features and
classify the resulting sequence to one out of ten keywords.
The middle column of Table \ref{tab:speech} shows the results.
The table is split into the direct NODE (top) and CDE (bottom) based approaches.
We first observe that among the direct NODE approaches, all our FWPs largely outperform ($\geq$ 80\% accuracy) the baseline GRU-ODE performance of 47.9\% (the best direct NODE baseline from \citet{KidgerMFL20}).
This demonstrates that with a good parameterisation of the vector field, the direct NODE approach can achieve competitive performance.
On the other hand, all CDE-based approaches yield similar performance.
We also only see slight differences in terms of performance among different learning rules, without a clear winner for this task.
This may indicate that
the ordinary nature of this task (regularly sampled; short sequences) does not allow for differentiating among these CDE models, including the baseline.
\paragraph{PhysioNet Sepsis.}
The next dataset we experiment with is the PhysioNet Sepsis dataset of the sepsis prediction task from the PhysioNet challenge 2019 \citep{ReynaJSJSWSNC19}. This is again a dataset used by \citet{KidgerMFL20} to evaluate NCDEs.
The task is a binary prediction of sepsis from a time series consisting of measurements of 34 medical features (e.g., respiration rate) of patients' stays at an ICU.
Each sequence is additionally labelled by five static features of the patient (e.g., age)
which are fed to the model to generate the initial state of the ODE.
Sequences are relatively short ($\leq$ 72 frames) but datapoints are irregularly sampled and many entries are missing,
which makes this task challenging.
It comes in two versions: with and without the so-called \textit{observation intensity} information (denoted as ``OI'' and ``no-OI'') which is one extra input feature indicating each observation's time stamp (providing the models with information on measurement frequency).
This distinction is important since the prior work \citep{KidgerMFL20} has reported that existing ODE/CDE-based approaches struggle with the no-OI case of this task.
Following the previous work, we report the performance in terms of Area Under the ROC Curve (AUC).
The right part of Table \ref{tab:speech} shows the results.
We obtain large improvements in the no-IO case (from 77.6 to 84.5\% for the CDEs and from 77.1 to 83.8\% for the direct NODEs),
while also obtaining
small improvements in the OI case (from 85.2 to 88.8\% for direct NODEs, and from 88.0 to 90.4\% for CDEs).
This demonstrates the efficacy of
CT FWP model variants for handling irregularly sampled data with partially missing features even in the case without frequency information.
Differences between various learning rules are rather small again.
The best no-OI single-seed performance is achieved by the Delta rule (87.6\%) whose variance across seeds is, however, high (std of 5.4).
\begin{table}[t]
\caption{\textbf{Classification Accuracy (\%) on the EigenWorms task.}
Numbers marked by * are taken from \citet{morrillSKF21}.
Mean and standard deviation (std) are computed over 5 runs.
``Sig-Depth'' indicates the depth of the signature (with this number equal to 1, an RDE is reduced to a CDE.).
To facilitate comparisons to prior work \citep{morrillSKF21},
we also add the column ``Step'' indicating the sequence down-sampling factor (even if we fix it to the best value \citep{morrillSKF21} of 4).}
\label{tab:eigenworms}
\begin{center}
\begin{tabular}{lccr}
\toprule
Model & Sig-Depth & Step & \multicolumn{1}{c}{Test Acc.~[\%]} \\ \midrule
NRDE \citep{morrillSKF21}* & 2 & 4 & 83.8 $\;$ (3.0) \\ \midrule
Hebb & 2 & 4 & 45.6 $\;$ (5.9) \\
Oja & & & 46.7 $\;$ (7.5) \\
Delta & & & 87.7 $\;$ (1.9) \\
\midrule \midrule
NCDE \citep{morrillSKF21}* & 1 & 4 & 66.7 (11.8) \\ \midrule
Hebb & 1 & 4 & 41.0 $\;$ (6.5) \\
Oja & & & 49.7 $\;$ (9.9) \\
Delta & & & \textbf{91.8} $\;$ (3.4)\\
\bottomrule
\end{tabular}
\end{center}
\end{table}
\paragraph{EigenWorms.}
The EigenWorms dataset (which is part of the UEA benchmark \citep{bagnall2018uea}) is a 5-way classification of roundworm types based on time series tracking their movements.
To be more specific, motions of a worm are represented by six features corresponding to its projections to six template movement shapes, called ``eigenworms''.
While this dataset contains only 259 examples, it is notable for its very long sequences (raw sequence lengths exceed 17\,K)
and long-span temporal dependencies \citep{morrillSKF21, rusch2021unicornn, rusch2021long}.
We use the same train/validation/test split ratio as the prior work \citep{morrillSKF21} which reports neural RDEs (NRDEs) as achieving the best NODE model performance on this dataset.
The equations of our CT FWPs for the RDE case can be straightforwardly obtained by replacing the input ${\bm{x}}$ in Eqs.~\ref{eq:ode-lr} and \ref{eq:querying_1} of the direct NODE formulation by the corresponding log-signatures.
Table \ref{tab:eigenworms} shows the results, where
``Step'' denotes the time sub-sampling rate which is fixed to 4 for which the prior work \citep{morrillSKF21} reports the best NRDE and NCDE performance.
``Sig-Depth'' denotes the depth of the log-signature (the deeper, the more log-signature terms we take into account, thus ending up with a larger input feature vector; we refer to the original paper \citep{morrillSKF21} for further details).
We consider two values for this parameter: 1 and 2.
When set to 1, the input feature contains only the first derivative ${\bm{x}}'(s)$ and thus the NRDE is reduced to a NCDE.
We take the best NCDE performance from
\citet{morrillSKF21} as the depth-1 baseline.
\citet{morrillSKF21} report the best overall performance for the depth-2 NRDE (depth-2 baseline in our table).
In both cases, we first note a large performance gap between models with different learning rules.
While the naive Hebb and Oja based models struggle with this very long sequence processing (sequence length still exceeds 4\,K with a down-sampling step size of 4), the Delta rule performs very well.
This confirms the prior result in the discrete-time domain \citep{schlag2021linear}
which motivated the Delta rule design by its potential for
handling long sequences
(we refer to prior work \citep{schlag2021linear} for further explanations).
Since its performance on other tasks is comparable to the one of Hebb and Oja variants, the Delta rule is a natural default choice for parameterising the CT FWPs.
In both the depth-1 and depth-2 cases, we obtain large improvements compared to the respective baselines.
It is counter-intuitive to find
certain depth-2 models underperforming their depth-1 counterparts, but this trend has also been observed in the original NRDEs \citep{morrill2021neural}.
Our best overall performance is obtained in the depth-1 case: 91.8 \% (3.4) exceeds the previous best NRDE based model performance of 83.8 \% (3.0) \citep{morrill2021neural}.
This almost matches the state-of-the-art accuracy of 92.8 \% (1.8) reported by \citet{rusch2021long} (using an ODE-inspired discrete-time model).
Our model's performance variance is high (best single seed performance is 97.4\% while the standard deviation is 3.4).
This calls for future investigations to improve stability of ODE-based models across random initialisations.
The wall clock time
is similar for our best model (last row in Table \ref{tab:eigenworms}) and the NRDE baseline (36s/epoch on a GeForce RTX 2080 Ti) and their sizes are comparable (87\,K vs.~65\,K parameters respectively).\looseness=-1
\section{Discussions}
\label{sec:diss}
\paragraph{Scalability Advantage Compared to Standard NCDEs.}
Apart from our primary motivation, our FWP approach also addresses an important limitation of existing NCDEs \citep{KidgerMFL20}: their scalability in terms of model size.
The vector field in standard NCDEs (Eq.~\ref{eq:cde}) requires an NN ${\bm{F}}_\theta$ which takes a vector ${\bm{h}}(s) \in \mathbb{R}^d$ as an input to produce a matrix of size $\mathbb{R}^{d \times d_{\text{in}}}$.
This can be very challenging when $d_{\text{in}}$ or/and $d$ is large.
Actually, the same bottleneck is present in the weight generation of FWPs \citep{Schmidhuber:91fastweights}.
The use of outer products can remediate this issue in discrete FWPs as well as in CT FWPs:
the computations in our FWP-based NODE/NCDEs
only involve ``first-order'' dimensions (i.e., no multiplication between different dimensions, such as $d \times d_{\text{in}}$) for NN outputs.
This can scale well with increased model size, making feasible larger scale tasks infeasible for existing NCDEs.
On the other hand, \citet{KidgerMFL20} report that using outer products (in their ``Sec.~6.1 on limitations'') in standard NCDEs does not perform well.
Why do outer products work in FWPs but not in the original NCDEs?
The answer may be simple.
In the original NCDEs (Eq.~\ref{eq:cde}), multiplications occur at each (infinitesimal) time step between the generated rank-one weight matrix ${\bm{F}}_\theta({\bm{h}}(s))$ and ${\bm{x}}'(s)$ before the sum.
All these transformations are thus of rank one while we expect expressive transformations to be necessary to translate ${\bm{x}}'(s)$ into changes in the state space.
In contrast, in FWPs, the ODE only parameterises the weight generation process of another net, and thus the rank-one matrices are never used in isolation: they are summed up over time (Eq.~\ref{eq:ode-lr} or \ref{eq:cde-lr-x-dx}) to form an expressive weight matrix which is only then used for matrix multiplication (Eq. \ref{eq:querying_2} or \ref{eq:cde_fwp_query}.
The proposed FWP-NODE/NCDEs thus offer scalable alternatives to existing NCDEs, also yielding good empirical performance (Sec.~\ref{sec:exp}).
\paragraph{Memory Efficient Backpropagation for FWPs}
Memory efficiency of adjoint backpropagation
may be not so important for standard NCDEs of state size $O(d)$, but is crucial for FWPs of state size $O(d^2)$ which can quickly become prohibitive for long sequences, as naive backpropagation stores all states used in the forward pass.
Prior works on discrete FWPs \citep{schlag2021linear, irie2021training, irie2021going} solve this problem by a custom memory-efficient implementation. Here, the adjoint method naturally addresses this problem.\looseness=-1
\paragraph{Related Work on Parameter/Weight ODEs.}
There are other works which use ODEs to parameterise time-evolving weights of some model.
However, they are limited to autonomous ODEs (i.e., no external control ${\bm{x}}$ is involved).
\citet{ZhangYGGKMB19} and \citet{ChoromanskiDLSS20}
study coupled ODEs where one ODE is used for temporal evolution of parameters of the main neural ODE.
The scope of these two works is limited to autonomous ODEs corresponding to continuous-depth residual NNs with different parameters per depth.
\citet{deleu2022continuous} consider an ODE version of a gradient descent learning process for adaptation, but also formulated as an autonomous ODE.
In contrast, our focus is really on \textit{sequence processing} where the model continuously receives external controls ${\bm{x}}$ and translates them into weight changes of another network.
\section{Conclusion}
\label{sec:ccl}
We introduced novel continuous-time sequence processing neural networks that learn to use sequences of ODE-based continuous learning rules as elementary programming instructions to manipulate short-term memory in rapidly changing synaptic connections of another network.
The proposed models are continuous-time counterparts of Fast Weight Programmers and linear Transformers.
Our new models experimentally outperform by a large margin existing Neural ODE based sequence processors on very long or irregularly sampled time series.
Our Neural ODE/CDE based FWPs also address the fundamental scalability problem of the original Neural CDEs, which is highly promising for future applications of ODE based sequence processors to large scale problems.
\section{Acknowledgements}
We would like to thank \citet{KidgerMFL20}, \citet{morrillSKF21} and \citet{du2020model} for their public code.
This research was partially funded by ERC Advanced grant no: 742870, project AlgoRNN,
and by Swiss National Science Foundation grant no: 200021\_192356, project NEUSYM.
We are thankful for hardware donations from NVIDIA and IBM.
The resources used for this work were partially provided by Swiss National Supercomputing Centre (CSCS) project s1145 and s1154.
| {'timestamp': '2022-06-06T02:16:45', 'yymm': '2206', 'arxiv_id': '2206.01649', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01649'} | arxiv |
\section{INTRODUCTION}
\noindent Trust has been identified as a key factor for effective human-robot interaction. Consequently, substantial research efforts have been devoted to identifying factors that influence humans' trust in robots \cite{Hancock2020}, developing computational models for trust estimation \cite{Optimo, BetaDistPaper}, and developing trust-aware robots \cite{trustPomdpLong, ReversePsychologyModel}.
Previous computational models of trust\cite{Optimo, BetaDistPaper} require binary performance measures of the autonomy. However, such measures cannot be directly applied in scenarios wherein the robotic agent needs to perform complex trade off decisions to maximize the cumulative reward and hence the autonomy performance is more difficult to quantify. In addition, although previous studies have revealed the existence of different types of trust dynamics \cite{BetaDistPaper, ClusteringTrustDynamics}, no research has tried to associate personal characteristics with the type of trust dynamics.
To fill these research gaps, we develop a novel reward-based performance metric to drive the trust estimation algorithm in a Markov Decision Process (MDP). The proposed performance metric is a binary surrogate of the autonomous agent's reward function, which allows our autonomous agent to utilize the trust update model developed in \cite{BetaDistPaper} for trust-aware decision-making. Moreover, from the data collected through human-subject experiments, we analyze how human trust evolves with their earned reward over repeated interactions with the autonomy. We find three distinct types of trust dynamics through $k-$means clustering analysis and examine associations between personal characteristics and type of trust dynamics.
\section{RELATED WORK}
\label{sec:relatedWork}
Extensive work has been done in identifying factors that affect trust in automation. However, most of these studies provide a snapshot view of trust, and failed to characterize the dynamics of trust \cite{Yang2021}. More recently, dynamic models of trust has been proposed, including the auto-regressive moving average vector (ARMAV) model \cite{armav-trust-model}, the Online Probabilistic Trust Inference Model (OPTIMo) model \cite{Optimo}, and the experience-based model \cite{BetaDistPaper}. These models enable a robot to estimate a human's trust in real time and has led to the development of trust-aware robots, allowing robots to reason upon human trust in their planning \cite{trustSeekingRobots, trustPomdpLong, trustWorkloadPomdpII, ReversePsychologyModel}.
Most existing research investigating individual differences aims to find associations between (snapshot) trust and individual characteristics, including propensity to trust automation \cite{merritt-ilgen-propensity}, personality trait of neuroticism \cite{Szalma2011IndividualDI}, and dispositional expectations of technology \cite{MerrittPASscale, LyonsGuznovPAS}. It is possible that these individual differences will be differentially represented within trust profiles related to trust dynamics. Recent research \cite{BetaDistPaper} reveal the existence of different types of trust dynamics, namely, rational decision maker, oscillator, and disbeliever. It is reasonable to investigate the association between a human agent's trust dynamics and factors that are shown to affect a human agent's (snapshot) trust.
\section{PROBLEM FORMULATION}
\label{sec:model}
In this section, we propose a finite horizon Markov Decision Process (MDP) for modeling and incorporating trust in the decision-making system of a robotic agent. The robot provides recommendations to its human partner about the action that they should take, but the final decision lies with the human. The specific scenario we target is an 'Intelligence, Surveillance, and Reconnaissance' (ISR) mission in which a human soldier teams up with an \emph{intelligent} drone to search through a town for threats. The drone guides the soldier on whether s/he should breach a site directly or deploy a Robotic Armored Rescue Vehicle (RARV). Using the RARV prevents any health loss to the soldier in the presence of a threat but takes additional time to the team; on the contrary, breaching a site directly is faster, but the soldier will be harmed if s/he encounters a threat. Here, two natural (but conflicting) goals that arise are to minimize any damage to the soldier and minimize the time to search through all the sites.
The key components of the MDP model of the ISR mission are given below.
\subsubsection{\bf States}
We use the estimated trust of the human on the robot as the state. Specifically, we use the trust model in \cite{BetaDistPaper}, wherein trust level at the $i^\text{th}$ stage, $t_i$, follows a Beta distribution, i.e.,
$
t_i \sim Beta(\alpha_i, \beta_i),
$
where $\alpha_i$ and $\beta_i$ are the positive experience and negative experience at time $i$. And, the state at stage $i$ is specified by the tuple $(\alpha_i, \beta_i)$.
\subsubsection{\bf Actions}
The drone has two actions: Recommend to use or not use the RARV.
\subsubsection{\bf Human behavior model}
We assume that human will accept the recommendation given by the robotic agent with probability $t_i$; and the human chooses the opposite action of the one that was recommended with probability $1- t_i$.
\subsubsection{\bf Reward function}
We use the weighted sum of the health loss cost and the time cost to define the cost of choosing an action. Similar to \cite{ReversePsychologyModel}, we add a trust-gaining term to incentivize the autonomous agent to gain trust. As a result, the reward $R_i$ at the $i^\text{th}$ stage is defined as
\begin{equation}
\label{eq::reward-function}
R_i(a) = -w_h h(a) - w_c c(a) + \gamma_i\cdot \mathbb{1}(A),
\end{equation}
where $w_h$ and $w_c$ are the weights for the health loss cost and time loss cost respectively. We define $A$ as the event when trust increases, i.e., $\mathbb{1}(A) = 1$ if the performance of the autonomous agent is a success and $\mathbb{1}(A) = 0$ otherwise. $\gamma_i (=w_t \sqrt{N-i})$ is a weight given to the trust gain reward that decreases with the stage number. The idea behind this is to support trust-gaining behavior near the current stage, and task performance optimizing behavior towards the later stages of planning.
\subsubsection{\bf Transition function}
\label{sec::TransitionFunction}
The state $(\alpha_i, \beta_i)$ is updated by
\begin{equation}
\label{eq::alpha-update}
( \alpha _{i} ,\beta _{i}) =\begin{cases}
\left( \alpha _{i-1} +w^{s} ,\beta _{i-1}\right) & \text{if } p_{i} =1,\\
\left( \alpha _{i-1} ,\beta _{i-1} +w^{f}\right) & \text{if } p_{i} =0.
\end{cases}
\end{equation}
Here, $p_{i}$ is the autonomous agent's performance at the $i^\text{th}$ stage.
Since the team's goal is to maximize earned reward, we define $p_i=1$ if at the $i^\text{th}$ site, the immediate reward for following the recommendation by the drone was greater than that for not following the recommendation and $p_i=0$ otherwise.
We fit the parameters $(\alpha_0, \beta_0, w^s, w^f)$ for each participant to model their trust dynamics. We use gradient descent to estimate the parameters in real time after each feedback from the participant.
We use value iteration to solve the MDP.
\section{Experiment}
\label{sec:case}
This section describes details of the human-subject experiment. The experiment complied with the American Psychological Association code of ethics and was approved by the Institutional Review Board at the University of Michigan.
\subsection{Participants}
A total of 46 adults participated in the study. One participant's data was discarded as the participant failed the attention check. The remaining 45 participants consisted of 21 females and 24 males (Age: Mean = 22.8 years, \textit{SD} = 3.6 years). Each participant was reimbursed with a base pay of \$20 with a bonus of up to \$10 based on their performance, which was measured by the time taken by the participants to complete the task and the final health level of the soldier.
\subsection{Testbed}
We developed a 3D testbed in Unreal Engine. A screenshot of the testbed is shown in Fig. \ref{fig::Background}. Fig. \ref{fig::Recommendation} shows the recommendation dialog box where the participant was recommended to not use the RARV. After choosing an action, the four possibilities depending on the presence of threat and participant's selected actions are shown in Fig. \ref{fig::Outcomes}. The participants are told that if they encounter a threat without the RARV, they will lose $5$ points of health. They were told that deploying the RARV takes about $10$ seconds. They were told to choose an action based on their interaction history and the recommendation. Their goal was to minimize the time taken for the mission, while maintaining the soldier's health.
\begin{figure}[h]
\centering
\subfigure[A view of the testbed]{
\includegraphics[width=0.46\linewidth]{images/background.png}
\label{fig::Background}}
\subfigure[An example of the GUI]{
\includegraphics[width=0.46\linewidth]{GUI.png}
\label{fig::Recommendation}}
\caption{The testbed developed in the Unreal Engine 4 game engine}
\label{fig::Testbed}
\end{figure}
\begin{figure}[h]
\centering
\subfigure[No Threat, RARV Not Used]{
\includegraphics[width=0.46\linewidth]{images/outcomes/noRARVnoThreat.png}
\label{fig::Outcomes1}}
\hfil
\subfigure[No Threat, RARV Used]{
\includegraphics[width=0.46\linewidth]{images/outcomes/RARVnoThreat.png}
\label{fig::Outcomes2}}
\subfigure[Threat, RARV Not Used]{
\includegraphics[width=0.46\linewidth]{images/outcomes/noRARVThreat.png}
\label{fig::Outcomes3}}
\hfil
\subfigure[Threat, RARV Used]{
\includegraphics[width=0.46\linewidth]{images/outcomes/RARVThreat.png}
\label{fig::Outcomes4}}
\caption{The outcomes based on threat presence and action chosen.}
\label{fig::Outcomes}
\end{figure}
\subsection{Measures}
\subsubsection{Personality}
The big 5 factors of personality (Extraversion, Conscientiousness, Agreeableness, Neuroticism, and Imagination) were measured using the 20-item mini-IPIP scale \cite{miniIPIPscale}. This 5-point Likert scale has widely been used in human-robot trust research \cite{miniIPIPusage}.
\subsubsection{Propensity to Trust}
Propensity to trust autonomous systems was assessed using a 6-item scale developed in \cite{MerrittPropensityScale}. This was also a 5-point Likert scale
\subsubsection{Perfect Automation Schema}
Perfect Automation Schema (PAS) was measured using the 7-item scale developed by \cite{MerrittPASscale}. Of these, 4 items measure high expectations from the autonomy and the other 3 items measure All-or-none thinking. This was a 7-point Likert scale.
\subsubsection{Moment-to-Moment Trust}
During the task, the participants were asked to rate their moment-to-moment trust on the drone by adjusting a slider on a 100-point scale.
\subsubsection{Post-experiment trust}
After the experiment, we used two scales \cite{TrustMMScale, miniIPIPusage} for assessing trust. The first one was a 9-item questionnaire with sliders while we used 6-items from the second scale all of which were 7-point Likert type questions.
\subsubsection{Workload}
Workload was measured using the NASA Task Load Index \cite{NASATLXscale}. We only used 5 of the 6 items as there was no physical demand from the participants in our experiment. All the items had the participants rate their feelings on a slider with values ranging from Very low to Very high.
\subsection{Experimental procedure}
Prior to the experiment, participants provided informed consent and completed the pre-experiment surveys. They were oriented to the steps of the experiment and walked through each of the screens they would see during the experiment. The two-fold objective of minimizing time and maximizing health was emphasized. They were informed about the performance-based bonus pay. They were told that the drone was imperfect, but they were not informed of the exact reliability level. They were also told that the robotic agent's recommendations would help them achieve the two-fold objective. Participants then proceeded to the experimental trials, wherein they had to search through 100 houses sequentially. After searching each house, the participants were asked to report their level of trust on the autonomous agent's recommendations. The participants took on average 51.5 minutes to complete the task. At the end of the experiment, participants completed the post-experiment surveys.
\section{RESULTS \& DISCUSSION}
\label{sec:result}
\subsection{Using Immediate Actual Reward as a performance metric}
Since the participants are explicitly told to consider both the soldier's health and the time to complete the search as their objectives, we expect their trust to be correlated with the immediate reward that they receive upon choosing an action. We expect that a participant's trust would be likely to increase if following the recommendation by the drone gets them a higher reward than doing the opposite and vice versa. Fig. \ref{fig::ImmediateRewardAndTrust} shows a representative example. In the figure, a green triangle represents the site at which following the recommendation would result in a better immediate reward gain ($p_i=1$) and the red triangles represent the opposite. It is quite clear that a red triangle is often followed by a decrease in trust and a green triangle is followed by an increase in trust. Thus, our reward-based performance metric is able to capture moment-to-moment trust changes of the participant. Using this metric in our trust update model, we get a prediction root mean squared error of $0.1266$ $(SD=0.078)$.
\begin{figure}
\centering
\includegraphics[width=0.7\linewidth]{images/ExpectedVsImmediate/Immediate.png}
\caption{Trust feedback with overlay of red and green triangles representing the rewards.}
\label{fig::ImmediateRewardAndTrust}
\end{figure}
\subsection{Clustering of Trust Dynamics}
\begin{figure}[h]
\centering
\includegraphics[width=0.7\linewidth]{images/Figure_3.png}
\caption{Clustering of participants according to their trust dynamics.}
\label{fig::Clustering-clusters}
\end{figure}
We employ k-means clustering to group participants with similar trust dynamics. We use the root mean squared error ($E_{RMS}$) between the predicted trust and the trust feedback and the average logarithm of trust as the clustering features. For computing $E_{RMS}$, we consider the feedback at the first $20$ sites as a training set to fit the personalized parameters $(\alpha_0, \beta_0, w^s, w^f)$. Thereafter, we use the feedback after every 5 sites to update the parameters. Fig. \ref{fig::Clustering-clusters} shows the results. We choose $k=3$ as the optimum number of clusters because it is a turning point of both the within-cluster variance and the silhouette score. We call the cluster with small $E_{RMS}$ and generally higher values of trust \emph{Bayesian Decision Makers}. The second cluster, called \emph{Disbelievers}, consists of participants whose $E_{RMS}$ values are small but whose trust is generally low. The third significant group is the \emph{Oscillators}, whose trust changes rapidly, making it harder to predict.
\subsection{Personal Characteristics and Type of Trust Dynamics}
We performed one-way ANOVA between the data of the clustered participants. Results showed significant difference between the three types of trust dynamics in Extraversion ($F(2,42)=4.991, p=0.011$), Agreeableness ($F(2,42)=3.276, p=0.048)$, and the High Expectations facet of the Perfect Automation Schema $(F(2,42)=5.752, p=0.006)$. Further, propensity to trust automation $(F(2,42)=3.002, p=0.06)$ and intellect/imagination $(F(2,42)=2.687,p=0.08)$ had marginally significant differences.
Post-hoc analysis with Bonferroni adjustment shows that the disbelievers are significantly less extroverted than the oscillators $(p=0.009)$. Disbelievers were only marginally less extroverted than Bayesian Decision Makers $(p=0.061)$. Disbelievers were marginally less agreeable than the Bayesian Decision Makers ($p=0.068$) and Oscillators ($p=0.06$). Disbelievers had significantly lower expectations from automation compared to both Bayesian Decision Makers $(p=0.005)$ and Oscillators $(p=0.023)$.
One way ANOVA on the post-experiment measures show significant difference between the three clusters in their post-experiment trust reports (Trust questionnaire by Muir and Moray $F(2,42)=22.167, p<0.001$, Trust questionnaire by Lyons and Guznov $F(2,42)=15.183, p<0.001$) and their frustration levels ($F(2,42)=4.136, p=0.023)$).
Post-hoc analysis with Bonferroni adjustment shows that there are significant differences between each of the three groups' trust reports according to the trust questionnaire by Muir and Moray ($p<0.001$ between Bayesian Decision Makers and Disbelievers, $p=0.006$ between Bayesian Decision Makers and Oscillators, and $p=0.009$ between Oscillators and Disbelievers with the highest trust for Bayesian Decision Makers and lowest for Disbelievers). Trust reported with the questionnaire by Lyons and Guznov only showed significant difference between Disbelievers and Bayesian Decision Makers $(p<0.001)$, and between Oscillators and Bayesian Decision Makers $(p=0.002)$. Oscillators were significantly more frustrated than Bayesian Decision Makers $(p=0.025)$.
\section{CONCLUSIONS}
\label{sec:discussion}
In this study, we formulated the human-robot sequential decision-making problem as an MDP and proposed an innovative reward-based performance metric for trust-aware decision-making. Through a human-subject experiment, we found three distinct types of trust dynamics, namely, Bayesian Decision Makers, Oscillators, and Disbelievers. Our model achieved different accuracies on different types on trust dynamics, which points to a requirement to use different models for people in different categories.
Analyses suggest that those individuals classified as Bayesian Decision makers evidenced high expectations of automation. When combined with other state measures such as trust and frustration, one might be able to identify a profile of the Bayesian Decision makers as the combination of individual differences and state measures could be used to parse the sample into the three categories of trust dynamics. Knowing that an individual might fall into one of the categories could influence whether or not a machine partner that is equipped with a dynamic trust model is a feasible solution for that individual.
In future studies, besides the reverse-psychology model, different human trust-behavior models should be considered. In addition, techniques such as inverse reinforcement learning can be employed to learn the preference of the human teammate to improve the team performance.
\bibliographystyle{IEEEtran}
| {'timestamp': '2022-06-06T02:16:39', 'yymm': '2206', 'arxiv_id': '2206.01645', 'language': 'en', 'url': 'https://arxiv.org/abs/2206.01645'} | arxiv |
\section{ Acknowledgments}
We thank the AAAI 2023 reviewers for their
feedback.
This research has been partially supported by the Israel Science Foundation under grant 1958/20, the
EU Project TAILOR under grant952215,
University of Virginia Strategic
Investment Fund award number SIF160,
and the US National Science Foundation grant
OAC-1916805 (CINES).
\section{Maximizing Total Benefit}
\label{sec:rmmrm_poly}
\subsection{An Efficient algorithm for \mbox{\textsc{MaxTB-MRM}}{}}
In this section, we present our algorithm for the
\mbox{\textsc{MaxTB-MRM}}{} problem that finds a $k$-round matching that
maximizes the total benefit over all the agents.
This algorithm requires the benefit function for each agent
to satisfy some properties. We now specify these
properties.
\smallskip
\noindent
\textbf{Valid benefit functions:}~
For each agent $x_i$, $1 \leq i \leq n$,
let~$\mu_i(\ell)$ denote the
non-negative \emph{benefit} that the agent~$x_i$ receives if matched in~$\ell$ rounds, for~$\ell=0,1,2,\ldots,\rho_i$.
Let~$\delta_i(\ell)=\mu_i(\ell)-
\mu_i(\ell-1)$ for~$\ell=1,2,\ldots,\rho_i$.
We say that the benefit function $\mu_i$
is \textbf{valid} if satisfies
\emph{all} of the following four properties:
(P1) $\mu_i(0)=0$;
(P2) $\mu_i$ is monotone non-decreasing in~$\ell$;
(P3) $\mu_i$ has the \emph{diminishing returns property}, that is,
$\mu_i(\ell)-\mu_i(\ell-1)\le\mu_i(\ell-1)-\mu_i(\ell-2)$
for~$2\le\ell\le\rho_i$; and
(P4) $\delta_i(\ell) \leq 1$, for~$\ell=1,2,\ldots,\rho_i$.
Note that~$\mu_i(\cdot)$ satisfies
property~P3
iff~$\delta_i(\cdot)$ is monotone non-increasing in~$\ell$.
Property~P4 can be satisfied by normalizing
the increments in the benefit values.
\smallskip
\noindent
\textbf{Algorithm for \mbox{\textsc{MaxTB-MRM}}{}:}~ Recall that the goal of this problem is to find a multi-round matching that maximizes the total benefit over all the agents.
The basic idea behind our algorithm is to reduce the problem to the maximum weighted matching
problem on a larger graph.
The steps of this construction are shown in
Figure~\ref{fig:alg_rmmrm}. Given a multi-round solution~$\mathcal{M}$ that assigns $\ell_i$ rounds to agent $x_i$,
$1 \leq i \leq n$,
let~$\mathbb{B}(\mathcal{M})=\sum_{i=1}^n\mu_i(\ell_i)$ denote the total benefit due to $\mathcal{M}$.
\begin{figure}[ht]
\rule{\columnwidth}{0.01in}
\small
\begin{enumerate}[leftmargin=*]
\item Given compatibility graph $G(X, Y, E)$, and for each agent~$x_i$,
permissible rounds~$K_i$, the maximum number of rounds~$\rho_i$, and benefit
function~$\mu_i(\cdot)$, create a new edge-weighted bipartite graph
$G'(X', Y', E', w(\cdot))$ as follows.
(The sets $X'$, $Y'$, and $E'$ are all initially empty.)
\begin{description}
\item[Node set $X'$.] For each agent $x_i \in X$ and each $h \in K_i$, add
a node denoted by $x_i^h$ to $X'$.
\item[Node set $Y'$.] For each resource $y_j \in Y$, add~$k$ nodes denoted
by $y_j^h$, where $h = 1, 2, \ldots, k$, to $Y'$. These are called \emph{type-1} resource nodes.
For every agent~$x_i$, add $\rho_i$ nodes, denoted by~$y^2_{i,p}$, where $p=1, 2, \ldots,\rho_i$; these are called \emph{type-2} resource nodes.
For every agent~$x_i$, add $|K_i|-\rho_i$ nodes, denoted by
let~$y^3_{i,p}$, where $p=1, 2, \ldots,|K_i|-\rho_i$; these are called \emph{type-3} resource nodes.
\item[Edge set $E'$ and weight~$w$.] For every edge $\{x_i, y_j\} \in E$
and each $h \in K_i$, add edge $\{x_i^h, y_j^h\}$ to $E'$ with
weight~$w(x_i^h,y_j^h)=1$. For each~$h \in K_i$ and~$p=1,\ldots,\rho_i$, add
edge $\{x_i^h, y^2_{i,p}\}$ with
weight~$w(x_i^h,y^2_{i,p})=1-\delta_i(p)$.
For each~$h\in K_i$
and~$p=1,\ldots,|K_i|-\rho_i$, add edge $\{x_i^h, y^3_{i,p}\}$~with
weight~$w(x_i^h,y^3_{i,p})=k+1$.
\end{description}
\item Find a maximum weighted matching $M^*$ in $G'$.
\item Compute a collection of matchings $\mathcal{M}^*=\{M_1, M_2, \ldots,
M_k\}$ for $G$ as follows.
The sets $M_1$, $M_2$, $\ldots$, $M_k$ are initially empty.
For each edge $e=\{x_i^{h},y_j^{h}\} \in M^*$
where~$y_j^h$ is a type-1 resource, add the edge $\{x_i, y_j\}$ to $M_{h}$.
\end{enumerate}
\caption{Steps of \mbox{\textsc{Alg-MaxTB-MRM}}{}.}
\label{fig:alg_rmmrm}
\rule{\columnwidth}{0.01in}
\end{figure}
Now, we establish the following result.
\begin{theorem}\label{thm:alg-correctness}
Algorithm \mbox{\textsc{Alg-MaxTB-MRM}}{} (Figure~\ref{fig:alg_rmmrm})
produces an optimal solution if every
benefit function~$\mu_i(\cdot)$ is valid.
\end{theorem}
We prove the above theorem through a sequence of
definitions and lemmas.
\begin{definition}
A matching $M$ of $G'$ is \textbf{saturated} if~$M$ includes (i)~every node
of $X'$ and (ii)~every node of $Y'$ that represents a type-3 resource.
\end{definition}
\begin{lemma}\label{lem:saturated_matching}
Given any maximum weight matching $M$ for $G'$, a saturated
maximum weight matching $M'$ for $G'$ with the same weight
as $M$ can be constructed.
\end{lemma}
\noindent
\textbf{Proof sketch:}~ We first argue that every maximum
weight matching of $G'$ includes all type-3 resource nodes
(since each edge incident on those nodes has a large weight).
We then argue that other unmatched nodes of $X'$ can be added
suitably.
\iftoggle{arxiv}
{
For details, see Section~\ref{sup:sec:rmmrm_poly} of
the supplement.
}
{}
\smallskip
Let the quantity $\lambda$ be defined by
{\small
\begin{center}
$\lambda ~=~ \sum_{i=1}^{n} k(|K_i|-\rho_i) +
\sum_{i=1}^{n} \sum_{\ell=1}^{\rho_i}(1-\delta_i(\ell))$.
\end{center}
}
\noindent
We use $\lambda$ throughout the remainder
of this section.
Note that $\lambda$ depends only on the parameters of the problem;
it does not depend on the algorithm.
\begin{lemma}\label{lem:matching-to-benefit}
Suppose there is a saturated maximum weight matching~$M$ for~$G'$ with
weight~$W$. Then, a solution to the \mbox{\textsc{MaxTB-MRM}}{} problem instance
with benefit~$W-\lambda$ can be constructed if every benefit function~$\mu_i(\cdot)$ is valid.
\end{lemma}
\begin{proof}
Given~$M$, we compute a collection of matchings $\mathcal{M}=\{M_1, M_2, \ldots,
M_k\}$ for $G$ as follows. For each edge $e=\{x_i^{h},y_j^{h}\} \in M$
where~$y_j^h$ is a type-1 resource, add the edge $\{x_i, y_j\}$ to $M_{h}$.
First, we will show that each~$M_h\in\mathcal{M}$ is a matching in~$G$.
Suppose~$M_h$ is not a matching, then, there exists some~$x_i$
or~$y_j$ with a degree of at least two in~$M_h$. We will prove it for the first
case. The second case is similar.
Suppose
agent~$x_i$ is adjacent to two resources~$y_{j'}$ and~$y_{j''}$. This
implies that in~$M$,~$x_i^h$ is adjacent to both~$y_{j'}^h$
and~$y_{j''}^h$, contradicting the fact that~$M$ is a matching in~$G'$.
Hence,~$\mathcal{M}$ is a valid solution to the \mbox{\textsc{MaxTB-MRM}}{} problem.
We now derive an expression for the weight $W$ of $M$.
Since every type-3 resource is matched in~$M$, the corresponding edges
contribute $\sum_{i=1}^nk(|K_i|-\rho_i)$ to $W$.
For an
agent~$x_i$, let the number of edges to type-1 resources
be~$\gamma_i\le\rho_i$. Each such edge is of weight $1$. The
remaining~$\rho_i-\gamma_i$ edges correspond to type-2 resources. Since each
benefit function, $\mu_i$ satisfies the diminishing returns property, the incremental benefits
$\delta_i(\cdot)$ are monotone non-increasing in the number of matchings.
Thus, we may assume without loss of generality that the top~$\rho_i-\gamma_i$
edges in terms of weight are in
the maximum weighted matching~$M$.
This contributes
$\sum_{\ell=1}^{\rho_i-\gamma_i}\big(1-\delta_i(\rho_i-\ell+1)\big)$ to $W$.
Combining the terms corresponding to type-1 and type-2
resources, the contribution of agent $x_i$ to $W$ is
\(
\gamma_i +
\sum_{\ell=1}^{\rho_i-\gamma_i}\big(1-\delta_i(\rho_i-\ell+1)\big) =
\sum_{\ell=1}^{\gamma_i}1 +
\sum_{\ell=\gamma_i}^{\rho_i}\big(1-\delta_i(\ell)\big)
= \sum_{\ell=1}^{\rho_i}\big(1-\delta_i(\ell)\big) +
\sum_{\ell=1}^{\gamma_i}\delta_i(\ell)
\)\,.
Summing this over all the agents, we get $W$ = $\sum_{i=1}^nk(|K_i|-\rho_i) +
\sum_{i=1}^n\sum_{\ell=1}^{\rho_i}\big(1-\delta_i(\ell)\big) +
\sum_{i=1}^n\sum_{\ell=1}^{\gamma_i}\delta_i(\ell)=\lambda+
\sum_{i=1}^n\mu_i(\gamma_i)$.
Since $\sum_{i=1}^n\mu_i(\gamma_i)$ =
~$\mathbb{B}(\mathcal{M})$, the lemma follows.
\end{proof}
\begin{lemma}\label{lem:benefit-to-matching}
Suppose there is a solution to the \mbox{\textsc{MaxTB-MRM}}{} problem instance with
benefit $Q$. Then, there a saturated matching $M$ for $G'$ with weight $Q + \lambda$ can be constructed.
\end{lemma}
\noindent
\textbf{Proof idea:}~ This proof uses an analysis
similar to the one used in the proof of
Lemma~\ref{lem:matching-to-benefit}.
\iftoggle{arxiv}
{
For details, see Section~\ref{sup:sec:rmmrm_poly}
of the supplement.
}
{}
\begin{lemma}\label{lem:opt-benefit-matching}
There is an optimal solution to the MaxTB-MRM problem instance with benefit $Q^*$
if and only if there is a maximum weight saturated matching $M^*$
for $G'$ with weight $Q^* + \lambda$.
\end{lemma}
\noindent
\textbf{Proof idea:}~ This is a consequence of
Lemmas~\ref{lem:matching-to-benefit} and \ref{lem:benefit-to-matching}.
\iftoggle{arxiv}
{
For details see Section~\ref{sup:sec:rmmrm_poly} of the supplement.
}
{}
\smallskip
\noindent
Theorem~\ref{thm:alg-correctness} is a direct consequence of
Lemma~\ref{lem:opt-benefit-matching}.
\smallskip
\noindent
We now estimate the running time of \mbox{\textsc{Alg-MaxTB-MRM}}{}.
\begin{proposition}\label{pro:time-algmaxtbmrm}
Algorithm \mbox{\textsc{Alg-MaxTB-MRM}}{} runs in time
$O(k^{3/2} (n+|E|)\sqrt{n+m}))$, where $n$ is the
number of agents, $m$ is the number of resources,
$k$ is the number of rounds and $E$ is the number of
edges in the compatibility graph $G(X, Y, E)$.
\end{proposition}
\iftoggle{arxiv}
{
\noindent
{\it Proof:} See Section~\ref{sup:sec:rmmrm_poly}
of the supplement.
}
{}
\subsection{Maximizing Utilitarian Social Welfare}
\label{sse:max_utilitarian}
Here, we present a valid benefit function that models
utilitarian social welfare.
For each agent $x_i$, let $\mu_i(\ell) = \ell$,
for $\ell{} = 0, 1, \ldots \rho_i$.
It is easy to verify that this is a valid benefit
function.
Hence, the algorithm in Figure~\ref{fig:alg_rmmrm}
can be used to solve the \mbox{\textsc{MaxTB-MRM}}{} problem with these benefit
functions.
An optimal solution in this
case maximizes the total number of rounds
assigned to all the agents, with agent $x_i$ assigned at
most $\rho_i$ rounds, $1 \leq i \leq n$.
This benefit function can also be used
to show that the \textsc{MRM}{} problem (where the goal is to
check whether there is a solution that satisfies all the
agents) can be solved efficiently.
\begin{proposition}\label{pro:mrm_solution}
\textsc{MRM}{} problem can be solved in polynomial time.
\end{proposition}
\noindent
\begin{proof}
For each agent $x_i$, let the benefit function $\mu_i$
be defined by $\mu_i(\ell) = \ell$,
for $0 \leq \ell{} \leq \rho_i$.
We will show that for this benefit function, the
algorithm in Figure~\ref{fig:alg_rmmrm} produces a
solution with total benefit $\sum_{i=1}^{n} \rho_i$
iff there is a solution to the \textsc{MRM}{} instance.
Suppose there is a solution to the \textsc{MRM}{} instance. We can
assume (by deleting, if necessary, some rounds in which agents are matched) that
each agent $x_i$ is assigned exactly $\rho_i$ rounds.
Therefore, the total benefit over all the agents
is $\sum_{i=1}^{n} \rho_i$.
Since the maximum benefit that agent $x_i$ can get is
$\rho_i$, this sum also represents the maximum possible total benefit. So, the total benefit of the solution
produced by the algorithm in Figure~\ref{fig:alg_rmmrm}
is $\sum_{i=1}^{n} \rho_i$.
For the converse, suppose the
maximum benefit produced by the algorithm
is equal to $\sum_{i=1}^{n} \rho_i$.
It can be seen from Figure~\ref{fig:alg_rmmrm} that
for any agent $x_i$, the algorithm assigns at most
$\rho_i$ rounds. (This is due to the type-3
resource nodes for which all the incident edges have large
weights.)
Since the total benefit is $\sum_{i=1}^{n} \rho_i$,
each agent $x_i$ must be assigned exactly $\rho_i$ rounds.
Thus, the \textsc{MRM}{} instance has a solution.
\end{proof}
In subsequent sections, we will refer to the algorithm
for \textsc{MRM}{} mentioned in the above proof as
\mbox{\textsc{Alg-MRM}}.
\newcommand{\pi}{\pi}
\newcommand{F^>}{F^>}
\subsection{Maximizing Rawlsian Social Welfare}
\label{sec:rawlsian}
Let~$\gamma_i(\mathcal{M})$ denote the number of rounds assigned to agent~$x_i$
in a multi-round solution~$\mathcal{M}$.
The minimum satisfaction ratio
for~$\mathcal{M}$ is defined as~$\min_{i}\{\gamma_i(\mathcal{M})/\rho_i\}$.
Consider the problem of finding a multi-round matching that
\emph{maximizes} the minimum satisfaction ratio.
While the maximization objective of this problem
seems different from the utilitarian welfare function,
we have the following result.
\begin{theorem}\label{thm:rawlsian}
There exists a reward function $\mu_i$ for each agent $x_i$ such that maximizing the total benefit under this function
maximizes the Rawlsian social welfare function,
i.e., it maximizes the minimum
satisfaction ratio over all agents.
Further, this reward function is valid
and therefore, an optimal solution to the \mbox{\textsc{MaxTB-MRM}}{}
problem under this benefit function can
be computed in polynomial time.
\end{theorem}
\noindent
To prove the theorem, we first show how
the benefit function is constructed.
\begin{enumerate}[leftmargin=*]
\item Let~$F=\big\{k_1/k_2\mid k_1,k_2\in\{1,\ldots,k\} ~\mathrm{and}~ k_1 \leq k_2\big\}\cup\{0\}$.
\item Let~$\pi: F\rightarrow\{1,\ldots,|F|\}$ give the index of
each element in~$F$ when sorted in descending order.
\item For each~$q\in F$, let $\xi(q)=(nk)^{\pi(q)}/(nk)^{|F|}$, where~$n$ is
the number of agents and~$k$ is the number of rounds. Note that
each~$\xi(q)\in(0,1]$.
\item The incremental benefit~$\delta_i(\ell)$ for an agent~$x_i$ for
the~$\ell$th matching is defined
as~$\delta_i(\ell)=\xi\big((\ell-1)/\rho_i\big)$.
Thus, the benefit function $\mu_i$ for agent $x_i$ is
given by $\mu_i(0) = 0$ and
$\mu_i(\ell) = \mu_i(\ell-1) + \delta_i(\ell)$ for
$1 \leq \ell \leq \rho_i$.
\end{enumerate}
It can be seen that $\mu_i$ satisfies
properties P1, P2, and P4 of a valid benefit
function. We now show that it also satisfies P3,
the diminishing returns property.
\begin{lemma}
For each agent~$x_i$, the incremental benefit~$\delta_i(\ell)$ is monotone
non-increasing in~$\ell$. Therefore,~$\mu_i(\cdot)$ satisfies
the diminishing returns property.
\end{lemma}
\begin{proof}
By definition, for~$\ell=1,\ldots,\rho_i-1$,~$\delta_i(\ell)/\delta_i(\ell+1)=
\xi\big((\ell-1)/\rho_i\big)/\xi\big(\ell/\rho_i\big)\ge nk > 1$, by noting
that~$\pi(\ell/\rho_i)-\pi((\ell+1)/\rho_i)\ge1$. Hence, the lemma holds.
\end{proof}
To complete the proof of Theorem~\ref{thm:rawlsian},
we must show that any solution that maximizes the
total benefit for the above benefit function also maximizes
the minimum satisfaction ratio.
\iftoggle{arxiv}
{
This proof appears in Section~\ref{sup:sec:rmmrm_poly}
of the supplement.
}
{
This proof appears in~\cite{mround-arxiv}.
}
\subsection{Hardness of \mbox{\textsc{MaxSA-MRM}}{}}
\label{sse:maxsa-mrm}
Here we consider the \mbox{\textsc{MaxSA-MRM}}{} problem, where the goal
is to find a $k$-round matching to maximize the number of satisfied agents.
A benefit function that models this problem is as follows.
For each agent $x_i$, let $\mu_i(\ell) = 0$ for
$0 \leq \ell{} \leq \rho_i -1$ and $\mu_i(\rho_i) = 1$.
This function can be seen to satisfy properties P1, P2, and P4 of
a valid benefit function.
However, it does \emph{not} satisfy P3, the diminishing returns property, since $\delta(\rho_i-1) = 0$ while
$\delta(\rho_i) = 1$.
Thus, this is not a valid benefit function.
This difference is enough to
change the complexity of the problem.
\begin{theorem}\label{thm:max_sat_agents_npc}
\mbox{\textsc{MaxSA-MRM}}{} is \textbf{NP}-hard even when the number of rounds ($k$) is 3.
\end{theorem}
\noindent
\textbf{Proof idea:}~
We use a reduction from the Minimum Vertex Cover
Problem for Cubic graphs which is known to
be \textbf{NP}-complete~\cite{GareyJohnson79}.
\iftoggle{arxiv}
{
For details, see
Section~\ref{sup:sec:rmmrm_poly} of the supplement.
}
{}
\section{Algorithms for \textsc{MS-AG-MRM}}
\section{Advice Generation Problems}
\label{sec:algmsagmrm}
\newcommand{\mathcal{Z}}{\mathcal{Z}}
Here, we first point out that the \textsc{AG-MRM}{} and \mbox{\textsc{AG-MaxSA-MRM}}{} problems are \textbf{NP}-hard.
We present two solution approaches for the \mbox{\textsc{AG-MaxSA-MRM}}{} problem, namely an
integer linear program
(ILP) formulation and a pruned-search-based optimization using \mbox{\textsc{Alg-MRM}}{}.
\smallskip
\noindent
\subsection{Complexity Results}
\label{sse:ag_complexity}
\begin{theorem}\label{thm:hardness}
The \textsc{AG-MRM}{} problem is NP-hard when there is just one
agent~$x_i$ for which~$\rho_i > 1$.
\end{theorem}
\noindent
\textbf{Proof idea.}~We use a reduction
from the Minimum Set Cover (MSC) problem
which is known to be \textbf{NP}-complete
\cite{GareyJohnson79}.
\iftoggle{arxiv}
{
For details, see
Section~\ref{sup:sec:algmsagmrm} of the supplement.
}
{}
Any solution to the \textsc{AG-MRM}{} problem must
satisfy \emph{all} the agents.
Thus, the hardness of \textsc{AG-MRM}{} also yields
the following:
\begin{corollary}\label{cor:agmaxsa-mrm-hard}
\mbox{\textsc{AG-MaxSA-MRM}}{} is \textbf{NP}-hard.
\end{corollary}
\smallskip
\noindent
\subsection{Solution Approaches for
\mbox{\textsc{AG-MaxSA-MRM}}{}}
\noindent
\textbf{(a) ILP Formulation for \mbox{\textsc{AG-MaxSA-MRM}}{}:}~
\iftoggle{arxiv}
{
This ILP formulation is presented in section~\ref{sup:sec:algmsagmrm} of
the supplement.
}
{
A complete ILP formulation for solving the problem \mbox{\textsc{AG-MaxSA-MRM}}{} can be found at~\cite{mround-arxiv}.
}
\smallskip
\noindent
\textbf{(b) \mbox{\textsc{Alg-MRM}}{} guided optimization:}~
We describe a local search heuristic \textsc{PS-Max-AG-MRM}{} for the \textsc{MS-AG-MRM}{} problem. It consists of
three parts: (1)~identification of relevant candidate sets of relaxations
for each agent and edges in the restrictions graph (and hence the name
\textbf{pruned-search}), (2)~the valuation of an
identified set of relaxations for all agents and (3)~a local search algorithm.
In part~(1), for each agent $x_i$, we first identify the sets
of restrictions
$\Gamma_i=\{\mbox{$\mathcal{C}$}'_i \subseteq \mbox{$\mathcal{C}$}_i ~|~$ Cost of removing all the
labels in $\mbox{$\mathcal{C}$}'_i$ for agent $x_i$ is $\leq$ $\beta_i\}$
to be considered for removal during the search. We choose a subcollection
$\Gamma_i^s\subseteq\Gamma_i$ of sets based on the following criteria:
(a)~only Pareto optimal sets of constraints with respect to the budget are
considered, i.e., if $\mbox{$\mathcal{C}$}'_i \in \Gamma_i^s$, then there is no $c_{i}^t
\in \mbox{$\mathcal{C}$}_i$ such that the cost of relaxation of $\mbox{$\mathcal{C}$}'_i \cup \{c_i^t\}$
is less than or equal to $\beta_i$; (b)~each $\mbox{$\mathcal{C}$}'_i \in \Gamma_i^s$ is associated
with a set of edges~$E_i'$ that will be added
to the compatibility graph
if~$\mbox{$\mathcal{C}$}'_i$ is relaxed; if~$\mbox{$\mathcal{C}$}'_i$ and~$\mbox{$\mathcal{C}$}''_i$ are such
that~$E_i''\subseteq E_i'$, then, we retain only~$\mbox{$\mathcal{C}$}'_i$;
(c)~if two sets of constraints cause the addition of the same
set of edges to the compatibility graph, only one of them is considered.
In part~(2), given a collection of relaxation sets, one for each
unsatisfied agent, we apply \mbox{\textsc{Alg-MRM}}{} from Section~\ref{sec:rmmrm_poly} on
the induced compatibility graph. The number of agents that are satisfied in
the $k$-round solution obtained serves as the valuation for the collection
of relaxation sets. In part~(3), we use simulated annealing local search
algorithm \cite{AK-1989} for the actual search.
\iftoggle{arxiv}
{
The details of this implementation are in Section~\ref{sup:sec:experiments}
of the supplement.
}
{}
\section{Directions for Future Work}
\label{sec:concl}
We conclude by mentioning a few directions for future work. One direction
is to consider other models for producing compatibility graphs from
restrictions graphs. (For example, an edge may be added to the
compatibility graph if at least one label on that edge is removed.) It will
also be interesting to consider the multi-round matching problems in an
online setting, where the set of agents varies over time and compatibility
is round-dependent. Finally, it is of interest to investigate
approximation algorithms with provable performance guarantees for
\mbox{\textsc{MaxSA-MRM}}{} and \mbox{\textsc{AG-MaxSA-MRM}}{}.
\section{Definitions and Problem Formulation}
\label{sec:definitions}
\subsection{Preliminaries}
\label{sse:prelims}
\paragraph{Agents, resources and matching rounds}
Let $\mbox{$\agset$}{} = \{x_1, x_2, \ldots, x_n\}$ be a set of~$n$ \emph{agents} and
$\mbox{$\rset$}{} = \{y_1, y_2, \ldots, y_m\}$ a set of $m$ \emph{resources}. The
objective of the system or the \mbox{\textsc{Principal}}{} is to generate~$k$ matchings $M_1,\ldots,M_k$ of agents to
resources, which we henceforth refer to as a
{\bfseries $\mathbf k$-round matching}. However, each agent has certain
requirements that need to be satisfied.
Firstly, each agent~$x_i$ specifies a set~$K_i\subseteq\{1,2,\ldots,k\}$
and wants to be matched in~$\rho_i$ rounds from $K_i$.
\paragraph{Restrictions and Restrictions Graph}
In addition to round preferences, agents may have restrictions
due to which they cannot be matched to certain (or all) resources. We model
this using an~$\agset\rset$ bipartite graph with multiple labels on edges, with
each label representing a restriction. We refer to this graph as the
\textbf{restrictions graph} and denote it as~$G_R(\agset,\rset,E_R)$, where
$E_R$ is the edge set. Each edge $e\in E_R$ is associated with a set $\Gamma_e$ of
agent-specific labels representing restrictions.
\paragraph{Compatibility Graph}
Let~$\mbox{$\mathcal{C}$}_i$
denote the set of edge labels or
restrictions associated with agent~$x_i$. Suppose a set $C \subseteq
\mbox{$\mathcal{C}$}_i$ of restrictions makes resource~$y_j$ \emph{incompatible}
with~$x_i$, we draw a labeled edge $\{x_i,y_j\}$ with labels in~$C$. We say
that $C$ is the \textbf{restrictions set} for the edge $\{x_i, y_j\}$. To
make~$x_i$ compatible with~$y_j$, \emph{all} the restrictions in~$C$ must be removed. There can be hard constraints due to which~$y_j$ can never
be compatible with~$x_i$ even if all the restrictions are removed, in which
case,~$x_i$ and~$y_j$ are not adjacent in~$G_R$. Let~$E\subseteq E_R$ be
the set of all edges for which the restrictions set is empty. The
corresponding subgraph~$\mbox{$G(\agset,\,\rset,\,E)$}$ is called the \textbf{compatibility
graph}.
An example showing a restrictions graph, a compatibility
graph and multi-round matching appears as Figure~\ref{fig:example1}. This example (Figure~\ref{fig:example1}) is motivated by the \mbox{\emph{Lab-Space}}{} application
considered in this work. There are lab
members (agents) who need to be assigned rooms (resources) -- one person
per room -- on five days (i.e., $k=5$) with some preferences for space and
days. Restrictions on each edge are induced by the mismatch between agent
preferences and resource properties. For example,~$x_1$ requires a big
room, while~$y_2$ is small. Therefore, we add a restriction (or
label)~$\mathtt{big}_1$ to the edge~$\{x_1,y_2\}$. The restrictions graph for
this problem is shown followed by a multi-round matching solution.
\begin{figure}[ht]
\centering
\includegraphics[scale=.40]{figures/example1.pdf}
\caption{An example: A restrictions
graph~$G_R$ is induced by agent preferences and resource attributes. The
first multi-round matching solution corresponds to the compatibility
without the advice generation component. Not all agents are satisfied. The
second solution
satisfies all agents.
\label{fig:example1}}
\end{figure}
\paragraph{Costs for restrictions removal}
For each restriction~$c_i^t$, there is a positive cost $\psi_i^t$
associated with removing $c_i^t$. To remove any set of labels, we use an
additive cost model, i.e., for any~$C \subseteq \mbox{$\mathcal{C}$}_i$, the cost incurred
by agent~$x_i$ for removing all the restrictions in $C$ is~$\sum_{c_i^t\in C}\psi_i^t$. An agent~$x_i$ is
\textbf{satisfied} if it is matched in~$\rho_i$ rounds belonging to the
set~$K_i$. Now, we formally define the multi-round matching and
advice generation problems.
\iffalse
\paragraph{Costs for restrictions removal}
For each restriction~$c_i^t$, there is a positive cost $\psi_i^t$
associated with removing $c_i^t$. To remove any set of labels, we use an
additive cost model, i.e., for any~$C \subseteq \mbox{$\mathcal{C}$}_i$, the cost incurred
by~$x_i$ for removing all the restrictions in $C$ is~$\sum_{c_i^t\in C}\psi_i^t$. An agent~$x_i$ is
\textbf{satisfied} if it is matched in~$\rho_i$ rounds belonging to the
set~$K_i$. Now, we formally define the multi-round matching and
advice generation problems.
\fi
\subsection{Multi-round Matching}
\label{sse:mrm}
We begin with a definition of the basic multi-round matching problem (\textsc{MRM}{}) and discuss other versions.
\smallskip
\noindent
\textbf{Multi-Round Matching} (\textsc{MRM}{})
\noindent
\underline{Instance:}~A compatibility graph $\mbox{$G(\agset,\,\rset,\,E)$}$, number of
rounds of matching~$k$; for each agent $x_i$, the set of permissible
rounds~$K_i\subseteq\{1,\ldots,k\}$, the number of rounds
$\rho_i\le|K_i|$ in which $x_i$
wants to be matched.
\noindent
\underline{Requirement:}~Find a $k$-round matching
that satisfies all the agents
(i.e., one that meets the requirements of
all the agents), if one exists.
Since a solution may not exist for a given instance of the $\textsc{MRM}$ problem,
we consider an extension that uses a \textbf{benefit} (or utility)
function for each agent. For each agent $x_i$, the benefit function
$\mu_i : \{0, 1, \ldots, \rho_i\} \rightarrow \mathbb{R}^+$, where
$\mathbb{R}^+$ is the set of nonnegative real numbers, gives a benefit
value $\mu_i(\ell)$ when the number of rounds assigned to $x_i$ is $\ell$,
$0 \leq \ell \leq \rho_i$. If a $k$-round matching assigns $\ell_i \leq
\rho_i$ rounds to agent $x_i$, then the total benefit to all the agents is
given by $\sum_{i=1}^{n} \mu_i(\ell_i)$. We can now define a more general
version of \textsc{MRM}{}.
\smallskip
\noindent
\textbf{Multi-Round Matching to Maximize Total Benefit}
(\mbox{\textsc{MaxTB-MRM}})
\noindent
\textbf{\underline{Instance:}}~A compatibility graph $\mbox{$G(\agset,\,\rset,\,E)$}$, number of
rounds of matching~$k$; for each agent $x_i$, the set of permissible
rounds~$K_i\subseteq\{1,\ldots,k\}$,
the number of rounds $\rho_i\le|K_i|$ in which
$x_i$ wants to be matched and
the benefit function $\mu_i$.
\noindent
\textbf{\underline{Requirement:}}~Find a $k$-round matching that maximizes the total benefit over all the agents.
As will be shown in Section~\ref{sec:rmmrm_poly}, when the benefit functions satisfy some properties (including monotonicity and diminishing returns), the \mbox{\textsc{MaxTB-MRM}}{} problem can be solved efficiently.
One such benefit function allows us to obtain an efficient
algorithm for the \textsc{MRM}{} problem.
Another benefit function allows us to define the problem
of finding a $k$-round matching that maximizes the number of satisfied
agents (abbreviated as \mbox{\textsc{MaxSA-MRM}}{}).
However, this benefit function does not satisfy
the diminishing returns property and so our efficient
algorithm for \mbox{\textsc{MaxTB-MRM}}{} cannot be used for this problem.
In fact, we show in Section~\ref{sec:rmmrm_poly}
that the \mbox{\textsc{MaxSA-MRM}}{} problem is \textbf{NP}-hard.
\subsection{Advice Generation}
\label{sec:agmrm}
We define the multi-round matching advice generation problems, namely $\textsc{AG-MRM}$ and
$\mbox{\textsc{AG-MaxSA-MRM}}$.
\smallskip
\noindent
\textbf{Advice Generation for Multi-Round Matching}\newline (\textsc{AG-MRM}{})
\smallskip
\noindent
\textbf{\underline{Instance:}}~A restrictions graph $G_R(\agset, \rset,
E_R)$, number of rounds of matching~$k$; for each agent $x_i$, the set of
permissible rounds~$K_i\subseteq\{1,\ldots,k\}$, the number of times
$x_i$ wants to be matched $\rho_i\le|K_i|$, and budget $\beta_i$; for each
label
$c_i^t \in \mbox{$\mathcal{C}$}_i$, a cost $\psi_i^t$ of removing
that label. (Recall that $\mbox{$\mathcal{C}$}_i$ is the set of labels
on the edges incident on agent $x_i$ in $G_R$.)
\noindent
\textbf{\underline{Requirement}:}~For each agent $x_i$, is there a subset $\mbox{$\mathcal{C}$}'_i \subseteq
\mbox{$\mathcal{C}$}_i$ such that the following conditions hold? (i)~The cost of removing
all the labels in $\mbox{$\mathcal{C}$}'_i$ for agent $x_i$ is at most $\beta_i$, and (ii)~in the resulting compatibility graph, there exists a
$k$-round matching such that all agents are satisfied.
If so, find such a $k$-round matching.
In Figure~\ref{fig:example1}, the advice generation component is
illustrated in the bottom-most panel.
In this case, we note that there is a
solution to the $\textsc{AG-MRM}$ problem.
In general, since a solution may not exist for a
given $\textsc{AG-MRM}$ instance, it is natural to consider the version where the
goal is to maximize the number of satisfied agents. We denote this version
by \mbox{\textsc{AG-MaxSA-MRM}}{}.
\paragraph{Note:} For convenience, we defined optimization versions of
problems \mbox{\textsc{MaxSA-MRM}}{}, \textsc{AG-MRM}{} and \mbox{\textsc{AG-MaxSA-MRM}}{} above.
In subsequent sections, we show that these problems are \textbf{NP}-hard.
It can be seen that the decision versions of these three problems are in \textbf{NP}; hence, these versions are \textbf{NP}-complete.
\section{Experimental Results}
\label{sec:experiments}
We applied the algorithms developed in this work to several datasets.
Evaluations were based on relevant benefit
functions and computing time. We used at least~10 replicates for each
experiment when needed (e.g., random assignment of attributes and while
using \textsc{PS-Max-AG-MRM}{}, which is a stochastic optimization algorithm).
Error bars are provided in such instances.
\iftoggle{arxiv}
{
Implementation details are in Section~\ref{sup:sec:experiments} of the
supplement.
}
{}
We considered two novel real-world applications
(discussed below). Here, we
describe the attributes of the datasets; the data itself and the code for running the experiments are
available at \url{https://github.com/yohayt/Resource-Sharing-Through-Multi-Round-Matchings}.
\paragraph{\mbox{\emph{Lab-Space}}{} application.} We conducted a back-to-the-lab desk sharing
study in the AI lab at a university\footnote{\label{note1}Bar-Ilan University, Ramat Gan, Israel.} to facilitate lab
personnel intending to return to in-person work
during the COVID-19 epidemic. A
survey was used to collect the preferences of lab members. The lab
has 14 offices and 31 members.
Six of the offices can accommodate two students each and the remaining eight can accommodate one student each.
The agent restrictions are as follows:
vicinity to the advisor's room, presence of cabinet, WiFi
connectivity, ambient noise, vicinity to the kitchen, room size, and vicinity
to the bathroom. All agent preferences are generated from the survey as a
function of the affinity (from 1~(low) to 5~(high)) they provide for each
attribute. These affinities are also used as costs for attribute removal.
\paragraph{\mbox{\emph{Course-Classroom}}{} dataset.} This dataset comes from a university\textsuperscript{\ref{note1}} for the
year~2018--2019. There are~$144$ classrooms and~$153$ courses. In the
experiments, we focused on two hours on Tuesday and used all the courses
that are scheduled in this time slot and all available classes. There were
142 courses and all the 144 classrooms were available for them. Each
classroom has two attributes: its \emph{capacity} and the \emph{region} to
which it belongs. Although the problem of assigning classrooms to courses
is quite common~\cite{phillips2015integer}, we did not find any publicly
available dataset that could be used here. The number of rounds of
participation is chosen randomly between~$1$ and~$3$ as this data was not
available. Also, to generate~$K_i$,~$\rho_i$ rounds are sampled uniformly
followed by choosing the remaining days with probability~$0.5$.
We used~10 replicates for each experiment.
The generation of the restrictions and compatibility graphs from the agent
preferences and resource attributes is described in
detail in
\iftoggle{arxiv}
{Section~\ref{sec:experiments} of the supplement.}
{~\cite{mround-arxiv}.}
\begin{figure}[htb]
\centering
\includegraphics[width=.5\columnwidth]{figures/StudMnPref.pdf}
\includegraphics[width=.48\columnwidth]{figures/StudPrb.pdf}
\includegraphics[width=.5\columnwidth]{figures/stdRatioBar3.pdf}
\includegraphics[width=.49\columnwidth]{figures/fig_num_shared_14.pdf}
\caption{\mbox{\emph{Lab-Space}}{} experiment results: (a)~Average assignment ratio for
different preference affinity thresholds; (b)~Average assignment ratio when
the number of resources is restricted; (c)~Comparison of different welfare
functions for resource probability~$0.5$, and preference affinity
and day affinity thresholds of~$5$ and~$2$ respectively; and (d)~Evaluation
of the advice generation algorithm for increasing budget.
\iftoggle{arxiv}
{
(See figure~\ref{fig:ag2students} for the case with two
people per big room.)
}
{(Plots for the case with two
people per big room are in~\cite{mround-arxiv}.)
}
\label{fig:ls_total}
}
\end{figure}
\paragraph{\mbox{\emph{Lab-Space}}{} multi-round matching.} Through this study, the head of the lab
(\mbox{\textsc{Principal}}{}) wanted answers to the following questions: Is it possible to
accommodate only one person per office? Is it possible to maximize the
number of relevant assignments? Is it possible to achieve
all this by satisfying as many preferences of lab members as possible? The
number of rounds is~$5$ (one for each weekday). We defined a preference
affinity threshold. If the agent's survey score for affinity (1-5) is
at least as much as the threshold, then we add this preference as a constraint.
Note that the compatibility graph generated for threshold~$\tau$ is a
subgraph of the one generated for~$\tau+1$. The permissible sets of rounds~$K_i$ are
generated the same way. A day affinity threshold is set. If the agent's
preference for a weekday is lower than this threshold, then we do not add
it to~$K_i$. In Figure~\ref{fig:ls_total}(a), we have results for maximizing the
utilitarian social welfare for
various compatibility graphs generated by adding constraints based on the
agent's affinity to each preference. We see that adhering strictly to the
preferences of agents gives a very low average assignment ratio
$\gamma_i/\rho_i$, where $\gamma_i$ is the number of
rounds assigned to agent $x_i$ (who requested $\rho_i$ rounds). We considered two scenarios for large rooms: one or
two students. We note that accommodating two students significantly
improves the average assignment ratio. Adhering to the preferred days of
students does not seem to have many costs, particularly when the preference
affinity threshold is high. In Figure~\ref{fig:ls_total}(b), we
demonstrate how critical the current set of resources is for the functioning of
the lab. We withheld only a portion of the resources (by sampling)
to satisfy agent preferences. However, with just 60\% of the resources, it is
possible to get an average assignment ratio of~$0.6$, albeit by ignoring
most of the agent preferences. In Figure~\ref{fig:ls_total}(c), we compare
utilitarian social welfare with Rawlsian social welfare. We note that in
the utilitarian welfare, many agents end up with a lower assignment ratio
compared to Rawlsian, while the total number of matchings across rounds is
the same.
\iftoggle{arxiv}
{
(A theorem in this regard is presented in
Section~\ref{sup:sec:gen_util_theorem}
of the supplement; it states
that for valid and monotone strictly increasing benefit functions, an optimal solution for total benefit also optimizes the total
number of rounds assigned to agents.)
}
{
(A theorem in this regard is presented in
~\cite{mround-arxiv}.
It states
that for valid and monotone strictly increasing benefit functions, an optimal solution for total benefit also optimizes the total
number of rounds assigned to agents.)
}
Hence, from the perspective
of fairness in agent satisfaction, the Rawlsian reward function performs
better.
\begin{figure}[htb]
\centering
\includegraphics[width=.47\columnwidth]{figures/ClsRho.pdf}
\includegraphics[width=.47\columnwidth]{figures/ClsRatioBar3.pdf}
\includegraphics[width=.47\columnwidth]{figures/fig_num_courses.pdf}
\includegraphics[width=.47\columnwidth]{figures/ClsBar.pdf}
\caption{\mbox{\emph{Course-Classroom}}{} experimental results: (a)~Average assignment ratio vs. number
of rounds required per agent; (b)~Comparison of different welfare
functions. (c)~Evaluation of advice generation algorithm for increasing
budget. (d)~Importance of attributes.
\label{fig:cc}}
\end{figure}
\paragraph{\mbox{\emph{Lab-Space}}{} advice generation.}
From the results in Figure~\ref{fig:ls_total}(d), we observe
that there is a sharp increase in the number of agents satisfied for a
budget of~4. In the data, there is a strong preference for WiFi (an average
score of~4.3 out of~5), while more than~40\% of the rooms have poor
connectivity. When most of the agents relax this preference, they have
access to many rooms. This partially explains the sharp increase in the
number of matchings. We also observe that the performance of
\textsc{PS-Max-AG-MRM}{} is close to that of optimum (given by \textsc{ILP-Max-AG-MRM}).
\paragraph{\mbox{\emph{Course-Classroom}}{} multi-round matching.} Here, we considered two scenarios:
having classes (i)~five days a week and (ii)~six days a week. A six-day
week can accommodate more courses while on the other hand, facilities have
to be kept open for an additional day. The results of maximizing the utilitarian
multi-round matching
are in Figure~\ref{fig:cc}(a). We observe that as~$\rho_i$ is increased,
the average assignment ratio decreases slowly. The difference between five and six days a week is not
significant. Figure~\ref{fig:cc}(b) compares utilitarian and Rawlsian reward
functions. Unlike the \mbox{\emph{Lab-Space}}{} results, here we clearly see that the minimum
assignment ratio is higher in the former case.
\paragraph{\mbox{\emph{Course-Classroom}}{} advice generation} In Figure~\ref{fig:cc}(c) we
observe that only for low budgets, the difference between five-day
week and six-day week solutions is significant. In the same regime, we see
a significant difference between \textsc{PS-Max-AG-MRM}{} and \textsc{ILP-Max-AG-MRM}. By
inspecting the solution sets, we observed that relaxing the region
attribute is most effective in increasing the number of satisfied agents, while
minimum capacity is least effective. To study the importance of different
attributes, we conducted experiments where a single chosen attribute was
omitted from the restrictions list. Figure~\ref{fig:cc}(d) indicates that
the region attribute has the most impact on the assignments
ratio.
\paragraph{Scaling to larger networks.}
To analyze the performance of the of the advice generation algorithms with
respect to the size of the network, we experimented with complete bipartite
graphs of various sizes.
\iftoggle{arxiv}
{The results are in Section~\ref{sup:sec:experiments} of the
supplement.}
{The results are in~\cite{mround-arxiv}.}
In these experiments, we note that
not only is the solution obtained using the \textsc{PS-Max-AG-MRM}{} close to
\textsc{ILP-Max-AG-MRM}, it is orders of magnitude faster.
\section{Complexity of \textsc{MS-MRM}{} and \textsc{AG-MRM}}
\section{Complexity of Max Versions}
\label{sec:complexity}
Our hardness results for \textsc{AG-MRM}{} and \textsc{MS-MRM}{} follow.
\iffalse
\begin{theorem}\label{thm:hardness}
The \textsc{AG-MRM}{} problem is NP-hard when there is just one
agent~$x_i$ such that~$\rho_i > 1$.
\end{theorem}
\noindent
\textbf{Proof outline.}~We use a reduction
from the Minimum Set Cover (MSC) problem
which is known to be \textbf{NP}-complete
\cite{GareyJohnson79}.
Consider an instance of MSC consisting of a
set~$U=\{z_1,z_2,\ldots, z_t\}$, a collection~$\mathcal{Z}=\{A_1,A_2,\ldots,
A_q\}$ of $q$ subsets of~$U$, and an integer~$\alpha\le|\mathcal{Z}|$.
We will construct an instance of \textsc{AG-MRM}{} as
follows. Let~$t =|U|$. Let degree of an element~$z\in U$, denoted
by~$\deg(z)$, be the number of sets in~$\mathcal{Z}$ which contain $z$. For
each~$z_j\in U$, we create~$\deg(z_j)$ resources~$\rset_j=\{y_j^h\mid
z_j\in A_h\}$. Thus, the resource set is~$\rset = \bigcup_{z_j\in
U}\rset_j$. For each~$\rset_j$, we create a set of agents~$\agset_j =
\{x_j^1,x_j^2,\ldots\}$, where~$|\agset_j| = t\cdot\deg(z_j)-1$. For
each~$z_j\in U$, we have an edge for every~$x\in \agset_j$ and~$y\in
\rset_j$. Finally, we add a special agent~$x^*$ with edges to all
resources. The set of agents is~$\agset=\bigcup_{z_j\in
U}\agset_j\cup\{x^*\}$. For each~$x\ne x^*$, there are no labels on the
edges that are incident on $x$. For each edge~$\{x^*,y_j^h\}$, we assign a
single label~$c_h$. Each label has cost~$1$. This completes the
construction of~$G_R$. For~$x^*$, the budget $\beta^*=\alpha$, which is the
budget for the MSC instance, and for all other agents, the budget is~$0$.
The number of rounds for~$x^*$,~$\rho^*=t$ and for the rest of the
agents~$x_i\ne x^*$,~$\rho_i=1$. For all agents~$x_i$,
$K_i=\{1,\ldots,t\}$.
This completes the construction of a
\textsc{MS-AG-MRM}{} instance.
A correctness proof for this reduction appears in the supplement. \qed
\fi
\iffalse
\begin{theorem}\label{thm:max_sat_agents_npc}
\textsc{MS-MRM}{} is \textbf{NP}-hard even when the number of rounds ($k$) is 3.
\end{theorem}
\noindent
\textbf{Proof outline:}~
To prove \textbf{NP}-hardness, we use a reduction from the Minimum Vertex Cover
Problem for Cubic graphs, which we denote as \mbox{\textsc{MVC-Cubic}}{}.
A definition of this problem is as follows: given
an undirected graph $H(V_H, E_H)$ where the degree of each node is 3
and an integer $h \leq |V_H|$, is there a vertex cover of size at most $h$ for $H$?
It is known that \mbox{\textsc{MVC-Cubic}}{} is \textbf{NP}-complete \cite{GareyJohnson79}.
Given an instance $I$ of \mbox{\textsc{MVC-Cubic}}{} consisting of graph $H(V_H, E_H)$
and integer $h \leq |V_H|$, we produce an instance $I'$ of \textsc{MS-MRM}{}
where the number of rounds = 3, with some agents requiring just one
round while others need three rounds.
The details of the reduction and its proof of correctness appear in the supplement. \hfill$\Box$
\fi
\section{Introduction}
\label{sec:intro}
We consider resource allocation problems that arise in practical
applications such as
hot desking or shared work spaces~\cite{varone2019dataset,cai2010common},
classroom scheduling~\cite{phillips2015integer},
matching customers with
taxicabs~\cite{karamanis2020assignment,kucharski2020exact},
and matching agricultural equipment
with farms~\cite{Gilbert-2018,RS-2020}.
In such
scenarios, many agents (individuals, cohorts, farms, or in general, entities) are
competing for a limited number of time-shared resources.
In our formulation, an agent can be matched to at most
one resource in any time slot, but might want to be
matched in more than one time slot. Agents may have some \emph{restrictions}
that limit the set of resources to which they can be matched or
possible time slots in which they can be matched. Any resource whose
specifications do not meet an agent's restrictions is \emph{incompatible} with that agent.
In light of the COVID-19 pandemic, such resource allocation problems have
become as important as ever. For example, social-distancing requirements
(such as maintaining a six-foot separation between individuals) led to
a dramatic decrease in the number of individuals who can occupy an enclosed
space, whether it is a classroom~\cite{dmg2020,enriching2020},
workspace~\cite{parker2020covid} or visitation room~\cite{wong2021self}.
We model this resource allocation problem as a $k$-round matching problem
on a bipartite graph, where the two node sets represent the agents and
resources respectively.
We assume that the rounds are numbered 1 through $k$,
and each round matches a subset of agents with a subset of
resources.
Each agent specifies the set of permissible
rounds in which it can participate and the
desired number of rounds (or matchings) in which it needs to be assigned a resource.
Consider for example a classroom scheduling for a
workweek ($k=5$). Each lecturer who wants to schedule class sessions for her courses
specifies the number of sessions she would like to schedule and the possible weekdays. There may also be additional requirements for classrooms (e.g., room size, location,
computer lab).
\iffalse
Each agent will have certain minimum matching requirements to be
satisfied, such as at least two gym sessions per week, one science lab,
etc. Resources have restrictions (e.g., room size, building floor or
level, support for hearing-impaired students).
\fi
As a result, some
agent-resource pairs become incompatible.
The \mbox{\textsc{Principal}}{}'s objective is to
find a set of at most $k$ matchings satisfying all
the requirements, if one exists.
In the classroom scheduling example, the existence of such a set means that there exists a solution where each lecturer receives the desired number of sessions on the desired days.
We refer to this as the \textbf{multi-round matching problem} (\textsc{MRM}).
We consider two additional problem formulations to cope with the situation when a solution satisfying all the requirements does not exist.
In the first formulation,
an agent receives a benefit (or reward) that depends
on the number of rounds where it is matched, and
the objective is to find a solution that maximizes
the sum of the benefits
over all agents.
We refer to this as the \textbf{multi-round matching
for total benefit maximization} problem
(abbreviated as \mbox{\textsc{MaxTB-MRM}}{}).
When applying this formulation to the classroom scheduling example, it is possible to find a solution in which the number of assigned sessions is maximized (by maximizing the corresponding utility function). Alternatively, we can also find a solution in which the minimal assignment ratio for a lecturer (i.e., the number of assigned sessions divided by the number requested) is maximized.
In the second formulation, the objective is to generate suitable advice to
each agent to relax its resource requirements so that it
becomes compatible with previously incompatible resources.
However, the agent incurs a cost to
relax its restrictions (e.g., social distancing requirements not met,
increase in travel time).
So, the suggested advice must satisfy the budget
constraints that are chosen by the agents.
In other words, the goal of this problem is to suggest
relaxations to agents' requirements, subject to budget constraints, so that in the new bipartite graph
(obtained after relaxing the requirements), all the
agents' requirements are satisfied.
In scheduling classrooms, for example, the~\mbox{\textsc{Principal}}{} may require that some lecturers waive a subset of their restrictions (e.g., having a far-away room) so that they can get the number of sessions requested.
We refer to this
to as the \textbf{advice generation for multi-round matching} problem (abbreviated as \textsc{AG-MRM}{}).
\smallskip
\noindent
\textbf{Summary of contributions:}
\smallskip
\iffalse
\noindent
\textbf{(a) An efficient algorithm for \textsc{MRM}.}
We show that \textsc{MRM}{} can be solved in polynomial time; i.e., one can find a
solution satisfying all the agents (if one exists) efficiently using a
known algorithm for the maximum matching problem \cite{Hopcroft-Karp-1973}.
\smallskip
\fi
\noindent
\underline{(a) An efficient algorithm for \mbox{\textsc{MaxTB-MRM}}{}.}
For a general class of benefit functions that satisfy
certain properties including monotonicity (i.e., the function is
non-decreasing with increase in the number of rounds)
and diminishing returns (i.e., increase in the value of the
function becomes smaller as the number of rounds is increased),
we show that the \mbox{\textsc{MaxTB-MRM}}{} problem can be
solved efficiently by a reduction to the maximum weighted matching problem.
A simple example of such a function (where each agent receives a benefit of 1 for each round in which it is
matched) represents a \textbf{utilitarian social welfare}
function \cite{viner1949bentham}.
Our efficient algorithm for this problem yields
as a corollary an efficient algorithm for the \textsc{MRM}{}
problem mentioned above.
Our algorithm can also be used for a more complex benefit function that models a \textbf{Rawlsian social welfare function}
\cite{rawls1999theory,Stark-2020},
where the goal is to maximize the minimum satisfaction
ratio (i.e., the ratio of the number of rounds assigned to an agent to the requested number of rounds) over all
the agents.
\iffalse
For each agent $x_i$, let~$\mu_i(\ell)$ denote the reward gained by
agent~$x_i$ for the~$\ell$th matching in a multi-round matching solution.
In the \textsc{RM-MRM}{} problem, the objective is to find a solution that maximizes
the total reward: $\sum_{x_i\in X}\sum_{\ell=1}^{\gamma_i}\mu_i(\ell)$,
where~$\gamma_i$ is the number of times~$x_i$ is matched. We show that
\textsc{RM-MRM}{} can be solved in polynomial time if for all agents,~$\mu_i$ is
a monotone non-increasing function of~$\ell$. The total participation
problem \textsc{TP-MRM}{} belongs to this class of problems, while the problem of
maximizing the number of satisfied agents \textsc{MS-MRM}{} does not. We show that
the latter is \textbf{NP}-hard even when every agent needs to be matched in at
most three rounds.
\fi
\smallskip
\noindent
\underline{(b) Maximizing the number of satisfied agents.}
Given a multi-round matching, we say that an agent is \textbf{satisfied} if the matching satisfies all
the requirements of the agent.
The objective of finding a multi-round matching that satisfies the largest number of agents can be modeled as the problem of maximizing
the total benefit by specifying a simple benefit
function for each agent. However, such a benefit function
\emph{doesn't} have the diminishing returns property.
We show that this optimization problem
(denoted by \mbox{\textsc{MaxSA-MRM}}{}) is \textbf{NP}-hard,
even when each agent needs to be matched in at most three
rounds.
This result points out the importance of the
diminishing returns property in obtaining an efficient
algorithm for maximizing the total benefit.
\noindent
\underline{(c) Advice generation.}
We show that \textsc{AG-MRM}{} is \textbf{NP}-hard even when
there is only one agent who needs to be matched
in two or more rounds.
Recall that the \textsc{AG-MRM}{} problem requires
that each agent must be satisfied (i.e., assigned the desired
number of rounds) in the new
compatibility graph (obtained by relaxing the suggested
restrictions).
It is interesting to note that the hardness of \textsc{AG-MRM}{}
is due to the advice generation part and not the computation of matching.
(Without the advice generation part, the \textsc{AG-MRM}{} problem
corresponds to \textsc{MRM}{} on a given compatibility graph,
which is efficiently solvable as mentioned above.)
The hardness of \textsc{AG-MRM}{} directly implies
the hardness of the problem (denoted by \mbox{\textsc{AG-MaxSA-MRM}}{})
where the generated advice must lead to a matching
that satisfies the maximum number of agents.
We present two solution
approaches for the \mbox{\textsc{AG-MaxSA-MRM}}{} problem:
(i)~an integer linear
program (\ilpagmaxsamrm{})
to find an optimal solution and
(ii)~a pruned local search heuristic (\textsc{PS-Max-AG-MRM}{}) that uses our algorithm for \textsc{MRM}{} to
generate solutions of good quality.
\smallskip
\noindent
\underline{(d) Experimental results.}
We present a back-to-the-lab desk-sharing study that has been conducted in
the AI lab at a university to facilitate lab personnel
intending to return to
the work place during the COVID-19 epidemic.
This study applies our algorithms to guide policies
for returning to work.
In addition, we present an experimental evaluation
of our algorithms on several synthetic data sets as well as
on a data set for matching courses to classrooms.
Table~\ref{tab:prob_considered} shows the list of problems
considered in our work and our main results.
\iftoggle{arxiv}
{
}
{
Due to space limitations, many proofs are omitted;
they can be founded in an expanded version~\cite{mround-arxiv}.
}
\begin{table}
{\small
\begin{tabular}{|p{0.35\columnwidth}|p{0.55\columnwidth}|}\hline
\textbf{Problem} & \textbf{Results} \\ \hline\hline
\mbox{\textsc{MaxTB-MRM}}{} & {Efficient algorithm for a general\newline class of benefit functions. An efficient algorithm for the~\textsc{MRM}{}
problem is a corollary.} \\ \hline
\mbox{\textsc{MaxSA-MRM}}{} & {\textbf{NP}-hard (reduction from
Minimum Vertex Cover for cubic graphs)} \\ \hline
\textsc{AG-MRM}{} & {\textbf{NP}-hard (reduction from Minimum Set Cover)}\\
\mbox{\textsc{AG-MaxSA-MRM}}{} & {ILP and a local search heuristic for
\mbox{\textsc{AG-MaxSA-MRM}}{}}
\\ \hline
\end{tabular}
}
\caption{Overview of problems and main results}
\label{tab:prob_considered}
\end{table}
\iffalse
\begin{table}
\begin{tabular}{|p{0.3\columnwidth}|p{0.6\columnwidth}|}\hline
\textbf{Problem} & \textbf{Results} \\ \hline\hline
\textsc{MRM}{} & Efficient algorithm \\ \hline
\textsc{RM-MRM}{} & Efficient algorithm in certain case\\
\textsc{TP-MRM}{} & Efficient algorithm \\
\textsc{MS-MRM}{} & {\textbf{NP}-hard (reduction from
Minimum Vertex Cover)} \\ \hline
\textsc{AG-MRM}{} & {\textbf{NP}-hard; ILP and heuristics} for\\
\textsc{MS-AG-MRM}{} & {two versions of \textsc{MS-AG-MRM}{}}
\\ \hline
\end{tabular}
\caption{Overview of problems considered and results}
\label{tab:prob_considered}
\end{table}
\ycomment{}{I modified table \ref{tab:prob_considered}. Please check.}
\fi
\section{An Efficient algorithm for \textsc{MRM}{}}
\label{sec:mrm_poly}
We now present a polynomial time algorithm for \textsc{MRM}.
The basic idea is to reduce the problem to the maximum
matching problem on a larger graph.
The steps of our algorithm \mbox{\textsc{Alg-MRM}}{} for \textsc{MRM}{} are shown
in Figure~\ref{fig:alg-mrma-prb}.
An example to illustrate the construction used in the algorithm
is given in the supplement.
\begin{figure}[ht]
\rule{\columnwidth}{0.01in}
{\small
\begin{enumerate}[leftmargin=*]
\item Given compatibility graph $G(X, Y, E)$,
create a new bipartite graph $G'(V', W', E')$ as follows.
To begin with, the sets $V'$, $W'$ and $E'$ are all empty.
\begin{enumerate}[leftmargin=*]
\item For each resource node $y_j \in Y$, add $k$ nodes denoted
by $y_j^t$, where $t = 1, 2, \ldots, k$, to $W'$.
\item For each agent $x_i \in X$ with $\rho_i = 1$:
(i) Add a new node $x_i^1$ to $V'$.
(ii) For each edge $\{x_i, y_j\} \in E$ and $t \in K_i$, add the edge
$\{x_i^1, y_j^t\}$ to $E'$.
\item For each agent $x_i \in X$ with $\rho_i \geq 2$:
(i) For each $t \in K_i$, add a node denoted by $x_i^t$ to $V'$.
(ii) Add $q_i = |K_i|- \rho_i$ ``dummy-resource" nodes, denoted
by $z_i^{\ell}$, where $\ell = 1, 2, \ldots, q_i$, to $W'$.
(iii) For each edge $\{x_i, y_j\} \in E$ and each $t \in K_i$,
add the edge $\{x_i^t, y_j^t\}$ to $E'$.
(iv) For each node $x_i^t$, add the
$|K_i|- \rho_i$ edges $\{x_i^t, z_i^{\ell}\}$,
$1 \leq \ell \leq |K_i|-\rho_i$, to $E'$.
\end{enumerate}
\item Find a maximum matching $M'$ in $G'(V', W', E')$.
\item If $M'$ does \emph{not} include all the nodes in $V'$, then
print ``No Solution" and \textbf{stop}.
\item Compute a collection of matchings $M_1$, $M_2$, $\ldots$, $M_k$, for
$G$ as follows. These matchings are initially empty.
For each edge $e \in M'$ that does \emph{not} use a
dummy resource, do the following:
(a) Let $x_i^{t}$ and $y_j^{\ell}$ denote the
end points of $e$.
(b) Add the edge $\{x_i, y_j\}$ to $M_{\ell}$.
\end{enumerate}
}
\caption{Steps of \mbox{\textsc{Alg-MRM}}{} for \textsc{MRM}{}}
\label{fig:alg-mrma-prb}
\rule{\columnwidth}{0.01in}
\end{figure}
The following result establishes the correctness
and running time of \mbox{\textsc{Alg-MRM}}.
\begin{theorem}\label{thm:alg_mmra_prb_correct}
(i) There is a solution to the \textsc{MRM}{} instance iff the graph
$G'$ constructed in Step~1 of Algorithm
\mbox{\textsc{Alg-MRM}}{} has a matching of size $|V'|$.
(ii) The running time of the algorithm is
$O(k^{3/2}|E| \sqrt{|X|+|Y|})$.
\end{theorem}
\noindent
\textbf{Proof outline:} Our proof of Part~(i) involves showing
that there is a solution to an \textsc{MRM}{} instance
(consisting of matchings $M_1$, $M_2$, $\ldots$, $M_k$)
iff there is a matching $M'$ of $G'$ that matches all the nodes in $V'$.
To prove Part~(ii), we show that graph $G'$ has
$O(k(|X|+|Y|)$ nodes and $O(k|E|)$ edges and
use the fact that for any bipartite graph $H(V_H, E_H)$,
a maximum matching can be found in
$O(|E_H| \sqrt{|V_H|})$ time \cite{CLRS-2009}.
See the supplement for details.\hfill$\Box$
\section{Rawlsian social welfare}
\label{sec:rawlsian}
Let~$\gamma_i(\mathcal{M})$ denote the number of rounds in which agent~$x_i$ is
matched in a multi-round solution~$\mathcal{M}$. The minimum satisfaction ratio
for~$\mathcal{M}$ is defined as~$\min_{i}\gamma_i(\mathcal{M})/\rho_i$. We show the
following result.
\begin{theorem}\label{thm:rawlsian}
There exists a reward function for which the optimal multi-round solution
satisfies Rawlsian social welfare, i.e., it maximizes the minimum
satisfaction ratio over all agents. Further, this reward function satisfies
the diminishing rewards property, and therefore, the optimal solution can
be computed in polynomial time.
\end{theorem}
\noindent
The reward function is constructed as follows:
\begin{enumerate}[leftmargin=*]
\item Let~$F=\big\{k_1/k_2\mid k_1,k_2\in\{1,\ldots,k\}\big\}\cup\{0\}$.
\item Let~$\pi: F\rightarrow\{1,\ldots,|F|\}$ correspond to the index of
each element in~$F$ when sorted in descending order.
\item For each~$q\in F$, $\xi(q)=(nk)^{\pi(q)}/(nk)^{|F|}$, where~$n$ is
the number of agents and~$k$ is the number of rounds. Note that
each~$\xi(q)\in(0,1]$.
\item The incremental reward~$\delta_i(\ell)$ for an agent~$x_i$ for
the~$\ell$th matching is defined
as~$\delta_i(\ell)=\xi\big((l-1)/\rho_i\big)$.
\end{enumerate}
\begin{lemma}
For each agent~$x_i$, the incremental reward~$\delta_i(\ell)$ is monotone
non-increasing in~$\ell$, and therefore,~$\mu_i(\cdot)$ satisfies
diminishing returns property.
\end{lemma}
\begin{proof}
By definition, for~$\ell=1,\ldots,\rho_i-1$,~$\delta_i(\ell)/\delta_i(\ell+1)=
\xi\big((\ell-1)/\rho_i\big)/\xi\big(\ell/\rho_i\big)\ge nk > 1$, by noting
that~$\pi(\ell/\rho_i)-\pi((\ell+1)/\rho_i)\ge1$. Hence proved.
\end{proof}
\noindent
For an agent~$x_i$ and~$q\in F$, let~$F^>_i(q)=\{\ell\mid 0\le\ell\le\rho_i
\text{ and } \ell/\rho_i>q\}$. We will now show that the incremental
reward~$\delta_i(\ell)$ obtained by agent~$x_i$ for matching~$\ell$ is
greater than the sum of all incremental rewards~$\delta_{i'}(\ell')$, for
all agents~$x_{i'}$, $i'\ne i$ and for all~$\ell'$
satisfying~$\ell'/\rho_{i'}>\ell/\rho_i$.
\begin{lemma}\label{lem:cost}
For any agent~$x_i$ and non-negative
integer~$\ell\le\rho_i$,~$\delta_i(\ell)>\sum_{i'=i}\sum_{\ell'\in
F^>_{i'}(\ell/\rho_i)}\delta_{i'}(\ell')$.
\end{lemma}
\begin{proof}
For any~$\ell'\in F^>_{i'}(\ell/\rho_i)$, note that
$\ell/\rho_i<\ell'/\rho_{i'}$.
Hence,~$\pi(\ell/\rho_i)-\pi(\ell'/\rho_{i'})\ge1$. This implies
that~$\delta_i(\ell)/\delta_{i'}(\ell') =
\xi\big((\ell-1)/\rho_i\big)/\xi\big((\ell'-1)/\rho_{i'}\big)\ge nk$.
Since~$\rho_{i'}\le k$, there are at most~$k$~$\delta_{i'}(\ell')$ terms
per~$i'$. Since there are at most~$n-1$ agents~$x_{i'}$,~$i'\ne i$, it
follows that there are at most~$(n-1)k$ terms~$\delta_{i'}(\ell')$ in
total. Therefore,~$\sum_{i'=i}\sum_{\ell'\in
F^>_{i'}(\ell/\rho_i)}\frac{\delta_{i'}(\ell')}{\delta_{i}(\ell)}<1$.
\end{proof}
\noindent
\textbf{Proof of Theorem~\ref{thm:rawlsian}.}
The proof is by contradiction. Suppose~$\mathcal{M}^*$ is an optimal solution
given the reward function defined above. We will show that if there exists
a solution~$\mathcal{M}$ with minimum satisfaction ratio greater than that
of~$\mathcal{M}^*$, then, the
benefit~$\mathbb{B}(\mathcal{M})>\mathbb{B}(\mathcal{M}^*)$, contradicting the fact
that~$\mathcal{M}^*$ is an optimal solution. Let~$q(\mathcal{M}^*)$
and~$q(\mathcal{M})$ denote the minimum satisfaction ratio in~$\mathcal{M}^*$
and~$\mathcal{M}$.
We recall that the benefit function for~$\mathcal{M}$ can be written
as~$\mathbb{B}(\mathcal{M})=\sum_{i=1}^n\sum_{\ell=1}^{\gamma_i(\mathcal{M})}
\delta_i(\ell)$. For each~$i$, the~$\delta_i(\ell)$ terms can be
partitioned into three blocks: (i)~$D_1(\mathcal{M})=\{(i,\ell)\mid \forall
i,~\ell/\rho_i\le q(\mathcal{M}^*)\}$, (ii)~$D_2(\mathcal{M})=\{(i,\ell)\mid
\forall i,~q(\mathcal{M}^*)<\ell/\rho_i\le q(\mathcal{M})\}$ and
(ii)~$D_3(\mathcal{M})=\{(i,\ell)\mid \forall i,~\ell>q(\mathcal{M})\}$. We can
partition the terms corresponding to~$\mathbb{B}(\mathcal{M}^*)$ in the same
way, denoted by~$D_1(\mathcal{M}^*)$ and~$D_2(\mathcal{M}^*)$. Note that since
every~$x_i$ has a satisfaction ratio of at least~$q(\mathcal{M}^*)$ in
both~$\mathcal{M}^*$ and~$\mathcal{M}$, all the terms with~$\ell/\rho_i\le
q(\mathcal{M}^*)$ will be present. Therefore,~$D_1(\mathcal{M}^*)=D_1(\mathcal{M})$.
In~$\mathcal{M}^*$, let~$x_{i'}$ be the agent for which the satisfaction ratio
is~$q(\mathcal{M}^*)$. There are no~$(i',\ell)$ terms in~$D_2(\mathcal{M}^*)$ while
for every agent~$x_i$, all~$(i,\ell)$ terms
satisfying~$q(\mathcal{M}^*)<\delta_i(\ell)\le q(\mathcal{M})$ are present
in~$D_2(\mathcal{M})$. Therefore,~$D_2(\mathcal{M}^*)\subset D_2(\mathcal{M})$.
\begin{align*}
\mathbb{B}(\mathcal{M})-\mathbb{B}(\mathcal{M}^*) = &
\sum_{(i,\ell)\in D_2(\mathcal{M})}\delta_i(\ell) +
\sum_{(i,\ell)\in D_3(\mathcal{M})}\delta_i(\ell) -
\sum_{(i,\ell)\in D_2(\mathcal{M}^*)}\delta_i(\ell) -
\sum_{(i,\ell)\in D_3(\mathcal{M}^*)}\delta_i(\ell) \\
& >
\sum_{(i,\ell)\in D_2(\mathcal{M})}\delta_i(\ell) -
\sum_{(i,\ell)\in D_2(\mathcal{M}^*)}\delta_i(\ell) -
\sum_{(i,\ell)\in D_3(\mathcal{M}^*)}\delta_i(\ell) \\
\end{align*}
Now, let~$(i',\ell')=\argmin_{(i,\ell)\in D_2(\mathcal{M})\setminus
D_2(\mathcal{M}^*)} \ell/\rho_i$. Also, recalling that~$D_2(\mathcal{M}^*)\subset
D_2(\mathcal{M})$,
\begin{align*}
\mathbb{B}(\mathcal{M})-\mathbb{B}(\mathcal{M}^*) & >
\sum_{(i,\ell)\in D_2(\mathcal{M})}\delta_i(\ell) -
\sum_{(i,\ell)\in D_2(\mathcal{M}^*)}\delta_i(\ell) -
\sum_{(i,\ell)\in D_3(\mathcal{M}^*)}\delta_i(\ell) \\
& > \delta_{i'}(\ell') -
\sum_{(i,\ell)\in D_3(\mathcal{M}^*)}\delta_i(\ell) > 0\\
\end{align*}
The inequality follows from Lemma~\ref{lem:cost}.
\qed
\section{Related Work}
\label{sse:related}
Resource allocation in multi-agent systems
is a well-studied area (e.g.,
\cite{Chevaleyre-etal-2006,Gorodetski-etal-2003,Dolgov-etal-2006}). The
general focus of this work is on topics such as how agents express
their requirements, algorithms for allocating resources and evaluating the quality of the
resulting allocations. Some complexity and approximability issues
in this context are discussed in Nguyen~et~al. (\citeyear{nguyen2013survey}). Zahedi
et al. (\citeyear{Zahedi-etal-2020}) study the allocation of
tasks to agents so that the task allocator can answer
queries on counterfactual allocations.
Babaei et al.~(\citeyear{babaei2015survey}) presented a survey of approaches to solving timetabling problems that assign university courses to spaces and time slots, avoiding the violation of hard constraints and trying to satisfy soft constraints as much as possible. A few papers proposed approaches to exam timetabling (e.g., Leite et al.~(\citeyear{leite2019fast}), Elley~(\citeyear{eley2006ant})).
Other work addressed timetabling for high schools (e.g., Fonseca et al.~(\citeyear{fonseca2016integrating}) and Tan et al.~(\citeyear{tan2021survey})).
However, the constraints allowed in the various timetabling problem variations are much more complex than in our setting.
Variants of multi-round matching have been considered in game
theoretic settings. Anshelevich~et al.~(\citeyear{anshelevich2013social})
consider an online matching algorithm where incoming agents are matched in
batches.
Liu~(\citeyear{liu2020stability}) considers matching a set of long-lived players (akin
to resources in our setting) to short-lived players
in time-slots. These two works focus on mechanism design to achieve stability and maximize social welfare.
Gollapudi et al. (\citeyear{gollapudi2020almost}) and also Caragiannis and Narang (\citeyear{caragiannis2022repeatedly}) consider repeated matching
with the objective of achieving envy-freeness. However, the latter only considers the case of perfect matching, where agents are matched exactly once in each round. S{\"u}hr~et al.~(\citeyear{suhr2019two}) considered optimizing fairness in repeated matchings motivated by applications to the ride-hailing problem.
Zanker~et~al. (\citeyear{Zanker-etal-2010}) discuss the design and evaluation of
recommendation systems that allow users to specify
soft constraints regarding products of interest.
A good discussion on the design of constraint-based recommendation systems
appears in Felfernig~et~al. (\citeyear{Felfernig-etal-2011}).
Zhou and Han (\citeyear{Zhou-Han-2019}) propose an
approach for a graph-based recommendation system that forms groups of
agents with similar preferences to allocate resources.
Trabelsi et al.~(\citeyear{trabelsi2022maximizing}, \citeyear{trabelsi2022maximizing2}) discussed the problem of advising an agent to modify its preferences so that it can be assigned
a resource in a maximum matching. In this work, however, the advice is given to a single agent and only one matching is generated.
To our knowledge, the problems studied in our paper,
namely finding multi-round matchings that optimize general benefit
functions and advising
agents to modify their preferences so that they can be
assigned resources in such matchings,
have not been addressed in the literature.
\section{Additional Material for Section~\ref{sec:experiments}}
\label{sup:sec:experiments}
Due to space limitation, we could not include the results of our experiments
with the \mbox{\emph{Passeport Vacances}}{} dataset in the context of \textsc{MRMA-R1}{} (\textsc{AG-MRM}{} with
requirement at least one) in the main paper. Those results are in
Figure~\ref{mrmar1_pv}. The experiment design is same as that explained
for Figure~\ref{mrmar1} (first three plots) with regard to \mbox{\emph{Course-Classroom}}{}
experiments. We note that the results indicate that among all
restrictions, activity preferences of children is the one that leads to the
most reduction in the number of rounds required when relaxed. Also, we note
that, unlike in the \mbox{\emph{Course-Classroom}}{} case, relaxation of combinations of attributes
does not have much effect compared to relaxation of the activity preference
alone..
\begin{figure}[!htb]
\centering
\includegraphics[width=.32\columnwidth]{figures/mrmar1_pv_1.pdf}
\includegraphics[width=.32\columnwidth]{figures/mrmar1_pv_2.pdf}
\includegraphics[width=.32\columnwidth]{figures/mrmar1_pv_3.pdf}
\caption{\textsc{MRMA-R1}{} results for \mbox{\emph{Passeport Vacances}}{}. In
the \mbox{\emph{Passeport Vacances}}{} plots, for relaxations beyond the values on the $x$-axes,
the results are unchanged.}
\label{mrmar1_pv}
\end{figure}
\begin{figure}[!htb]
\centering
\includegraphics[width=.5\columnwidth]{figures/mrma_heuristic_pv.pdf}
\caption{\textsc{SimAnn-MRMA}{} results for \mbox{\emph{Passeport Vacances}}{}. The graph that compares \textsc{SimAnn-MRMA}{} to \textsc{ILP-MRMA}{} is not presented since the runtime of \textsc{ILP-MRMA}{} on the \mbox{\emph{Passeport Vacances}}{} dataset is too long and not practical. }
\label{mrmar1_pv_2}
\end{figure}
\iffalse
\includegraphics[scale=0.5]{figures/school_k.png}
\begin{itemize}
\item Based on School vacations graph
\item x axis is the agents with demand in {5,10,15,20} rest are with demand of 2 matchings.
\item different values of k for ilp and greed heuristics.
\item 10 datapoints for different percents.
\item high requirement agents are chosen randomly 100 times and average is calculated.
\item graph is after relaxation with budget of 2.
\end{itemize}
\includegraphics[scale=0.5]{figures/school_time.png}
\begin{itemize}
\item runtimes for greedy and ilp
\item using cbc solver. tried also gurobi which considered as state of the art.
\end{itemize}
\includegraphics[scale=0.5]{figures/class_k.png}
\begin{itemize}
\item Same definitions but for courses and classes
\end{itemize}
\includegraphics[scale=0.5]{figures/class_times.png}
\begin{itemize}
\item Same definitions but for courses and classes
\end{itemize}
\includegraphics[scale=0.5]{figures/relax_course_k_1.png}
\begin{itemize}
\item Previous graph for comparison, please ignore.
\end{itemize}
\includegraphics[scale=0.5]{figures/relax_course_k_1_2.png}
\begin{itemize}
\item Relaxing 0.0,0.2,0.4,0.6,0.8 or 1.0 of the constraints for each relevant attribute.
\item Remove agents with no edges in the beginning.
\item save runtimes as well
\item choose k by using algorithm of at least one.
\end{itemize}
\includegraphics[scale=0.5]{figures/random_k.png}
\begin{itemize}
\item Random graphs. agents are chosen among large initial set such that they will have at least 1 edge.
\item No requirement from the resources.
\item 4 data points, 100,0.75,0.5,0.25
\item run massively in parallel, 1000 times per option.
\end{itemize}
\includegraphics[scale=0.5]{figures/local_search.png}
\fi
\iffalse
\section{Additional Material for
Section~\ref{sec:methods_per_round_budget}}
\medskip
\subsection{A Simpler ILP for \maxmrm{}}
\label{sup:sse:simpler_ilp}
Section~\ref{sec:general_ilp} presented an ILP for \maxagmrm{}.
Here, we present a simpler ILP for \maxmrm{} where
the compatibility graph $G(X, Y, E)$ is given.
\smallskip
\noindent
\textbf{ILP Formulation:}~
\smallskip
\noindent
\underline{\textsf{Variables:}}
\begin{itemize}
\item For each agent $x_i$, let $A_i$ denote the
set of resources with which $x_i$ is compatible;
that is, $A_i = \{y_j ~:~ \{x_i, y_j\} \in E\}$, $1 \leq i \leq n$.
For each agent $x_i$ and each resource $y_j \in A_i$,
we have $k$ \{0,1\}-variables
denoted by $a_{ijr}$, where $1 \leq i \leq n$, $1 \leq j \leq m$ and
$1 \leq r \leq k$.
The interpretation is that $a_{ijr}$ is 1 iff agent $x_i$ is matched
to resource $y_j$ in round $r$.
\item For each agent $x_i$, we have a non-negative integer
variable $\eta_i$ which gives the number of rounds
in which $x_i$ is matched.
\item For each agent $x_i$, we have a \{0,1\}-variable $s_i$
that is 1 iff agent $x_i$'s requirement is satisfied.
\end{itemize}
\smallskip
\noindent
\underline{\textsf{Objective:}}~ Maximize~~
$\sum_{i=1}^{n} s_i$.
\smallskip
\noindent
\underline{\textsf{Constraints:}}
\begin{itemize} [leftmargin=*,noitemsep,topsep=0pt]
\item For each agent $x_i$, the number of rounds
in which $x_i$ is matched should equal $\eta_i$.
This constraint can be expressed as
\begin{equation}
\sum_{r=1}^{k}\: \sum_{y_j \in A_i} a_{ijr} ~=~ \eta_i, ~~1 \leq i \leq n
\end{equation}
\item Each agent $x_i$ is matched to a resource \emph{at most once}
in each round. This constraint can be expressed as
\begin{equation}
\sum_{y_j \in A_i}\: a_{ijr} ~\leq~ 1, ~~1 \leq i \leq n,~~ 1 \leq r \leq k
\end{equation}
\item For each resource $y_j$, let $B_j$ denote the set of agents
with which $y_j$ is compatible, $1 \leq j \leq m$;
that is, $B_j = \{x_i ~:~ \{x_i, y_j\} \in E\}$, $1 \leq j \leq m$.
In each round, each resource must be matched to an agent
\emph{at most} once.
This constraint can be expressed as
\begin{equation}
\sum_{x_i \in B_j} a_{ijr} ~\leq~ 1, ~~
1 \leq j \leq m,~~ 1 \leq r \leq k
\end{equation}
\item The rounds in which an agent $x_i$ is matched
must be in $K_i$. The corresponding constraint is:
\begin{align}
a_{ijr} ~=~ 0, ~~ r \not\in K_i,~ 1 \leq j \leq m,~
1 \leq i \leq n
\end{align}
\item Variable $s_i$ to be 1
iff agent $x_i$ was matched
in at least $\rho_i$ rounds. The following constraints,
which must hold for each $i$, $1 \leq i \leq n$, ensure this
condition.
\begin{eqnarray*}
k\,s_i ~\leq~ \eta_i - \rho_i + k \\
k\,s_i ~\geq~ \eta_i - \rho_i + 1
\end{eqnarray*}
\item $a_{ijr} \in \{0,1\}$,
$1 \leq i \leq n$,~ $1 \leq j \leq m$,~ $1 \leq r \leq k$.
\end{itemize}
\medskip
\noindent
\underline{\textsf{Obtaining a Solution:}} After solving
the ILP, for each variable $a_{ijr}$ which is set to 1 in the
solution, we match agent $x_i$ with resource $y_j$ in round $r$.
\fi
\iffalse
\medskip
We now present an example to illustrate the above ILP
formulation.
\noindent
\textbf{Example:} In the compatibility graph shown below,
we have an agent $x_3$ which must appear in at least two rounds
of matching.
(Recall from Section~\ref{sec:general_ilp} that for each agent
$x_i$, $A_i$ is the set of resources to which $x_i$
can be matched. Likewise, for each resource
$y_j$, $B_j$ is the set of agents to which $y_j$
can be matched.)
\bigskip
\begin{center}
\begin{minipage}{0.3\textwidth}
\input{graph_one.pdf_t}
\end{minipage}
\hspace*{0.1in}
\begin{minipage}{0.4\textwidth}
\begin{itemize}
\item Let $k = 2$.
\item Let $\rho_1 = 1$, $\rho_2 = 1$ and $\rho_3 = 2$.
\item $A_1 = \{y_1\}$, $A_2 = A_3 = \{y_1, y_2\}$.
\item $B_1 = \{x_1, x_2, x_3\}$ and $B_2 = \{x_2, x_3\}$.
\end{itemize}
\end{minipage}
\end{center}
\medskip
\noindent
The ILP for the above problem instance is as follows.
\bigskip
\noindent
\underline{\textsf{Variables:}}~
$a_{1,1,1}$, $a_{1,1,2}$,
$a_{2,1,1}$, $a_{2,1,2}$,
$a_{2,2,1}$, $a_{2,2,2}$,
$a_{3,1,1}$, $a_{3,1,2}$,
$a_{3,2,1}$ and $a_{3,2,2}$.
(Each of these variables takes on a value from $\{0,1\}$.
The significance of variable $a_{ijr}$ is that it takes on the
value 1 iff agent $x_i$ is assigned resource $y_j$ in round $r$.)
\bigskip
\noindent
\underline{\textsf{Constraints:}}
\begin{itemize}
\item For Agent $x_1$: (i) $a_{1,1,1} + a_{1,1,2} ~\geq~ 1$,~
(ii) $a_{1,1,1} \leq 1$~ and (iii) $a_{1,1,2} \leq 1$.
(The last two constraints can be omitted since the fact
that each variable takes on a value from $\{0,1\}$
implies each of the last two constraints.)
\item For Agent $x_2$: (i) $a_{2,1,1} + a_{2,2,1}
+a_{2,1,2} + a_{2,2,2} ~\geq~ 1$,~
(ii) $a_{2,1,1} + a_{2,2,1} ~\leq~ 1$~ and
(iii) $a_{2,1,2} + a_{2,2,2} ~\leq~ 1$.
\item For Agent $x_3$: (i) $a_{3,1,1} + a_{3,2,1}
+a_{3,1,2} + a_{3,2,2} ~\geq~ 2$,~
(ii) $a_{3,1,1} + a_{3,2,1} ~\leq~ 1$ and
(iii) $a_{3,1,2} + a_{3,2,2} ~\leq~ 2$.
\item For Resource $y_1$:
\begin{description}
\item{(a)} $a_{1,1,1} + a_{2,1,1} + a_{3,1,1} ~\leq~ 1$
\item{(b)} $a_{1,1,2} + a_{2,1,2} + a_{3,1,2} ~\leq~ 1$
\end{description}
\item For Resource $y_2$:
\begin{description}
\item{(a)} $a_{2,2,1} + a_{3,2,1} ~\leq~ 1$
\item{(b)} $a_{2,2,2} + a_{3,2,2} ~\leq~ 1$
\end{description}
\end{itemize}
\bigskip
\noindent
\underline{\textsf{A solution:}} One solution that satisfies
all the above constraints is obtained by setting $a_{2,1,1}$, $a_{3,2,1}$,
$a_{1,1,2}$ and $a_{3,2,2}$ to 1 and all the other variables to 0.
This leads to the following matching in two rounds.
In Round 1, $x_2$ and $x_3$ are matched to $y_1$ and $y_2$
respectively; in Round 2, $x_1$ and $x_3$ are matched
to $y_1$ and $y_2$ respectively.
\iffalse
\section{Additional Information for Section~\ref{sec:min_round_req_one}}
\medskip
\subsection{An Example to Illustrate the Construction in
Figure~\ref{fig:alg_problemrone}}
\begin{figure}[h]
\rule{\columnwidth}{0.01in}
\begin{minipage}{0.45\columnwidth}
\centering
\input{graph_one.pdf_t}
\end{minipage}
\quad
\begin{minipage}{0.45\columnwidth}
\centering
\input{graph_two.pdf_t}
\end{minipage}
\caption{An example to illustrate the algorithm in Figure~\ref{fig:alg_problemrone}.
The graph on the left is the original compatibility graph.
The graph on the right is the new graph produced by the Algorithm
in Step~1 with $k = 2$.
(The new edges are shown as dashes.)
The graph on the left has a two round matching $M_1$, $M_2$ that
matches each agent once: $M_1 = \{(x_1, y_1), (x_2, y_2)\}$ and
$M_2 = \{(x_3, y_1)\}$.
The corresponding maximum matching in the graph on the right
is $\mbox{$\mathbb{M}$}' ~=~ \{(x_1, y_{1,1}), (x_2, y_{2,1}), (x_3, y_{1,2})\}$.
}
\label{fig:example_alg_problemrone}
\rule{\columnwidth}{0.01in}
\end{figure}
\bigskip
\subsection{Statement and Proof of Lemma~\ref{lem:alg_problemrone}}
\medskip
\noindent
\textbf{Statement of Lemma~\ref{lem:alg_problemrone}:}~
Algorithm \textsc{Alg-MRMA-R1}{} (a) produces a solution iff the compatibility
graph \mbox{$G(\agset{}, \rset{}, E)$}{} has a $k$-round matching such that each
agent appears in one of the $k$ matchings, and
(b) runs in polynomial time.
\smallskip
\noindent
\textbf{Proof:}
\textbf{Part (a):}~\textsf{If part:} Suppose \mbox{$G(\agset{}, \rset{}, E)$}{} contains a $k$-round matching
$M_1$, $M_2$, $\ldots$, $M_k$ such that each agent $x_i$ appears
in one of the $k$ matchings.
We may assume without loss of generality that each
agent $x_i$ appears in exactly one matching.
(If an agent occurs in two or more matchings, we can remove all
but one of the occurrences.)
We will show that $G'$ has a matching that contains each node of \agset.
To see this,
consider the following set $\mbox{$\mathbb{M}$}'$ of edges in $G'$: for each edge
$(x_i, y_j)$ that appears in matching $M_p$ for some $p$
($1 \leq p \leq k$), add the edge
$(x_i, y_{j,p})$ to $\mbox{$\mathbb{M}$}'$.
Since each agent $x_i$ appears in one of the $k$ matchings
of \mbox{$G(\agset{}, \rset{}, E)$}, the agent also appears in one of the edges in $\mbox{$\mathbb{M}$}'$.
To show that $\mbox{$\mathbb{M}$}'$ is a matching, we will show by contradiction
that no node in \mbox{$\mathbb{R}$}{} appears in two or more edges of $\mbox{$\mathbb{M}$}'$.
So, assume that some node $y_{j,p}$ appears in two edges, say
$(x_a, y_{j,p})$ and $(x_b, y_{j,p})$, of $\mbox{$\mathbb{M}$}'$.
By our construction of $\mbox{$\mathbb{M}$}'$, this happened because matching $M_p$
contains both the edges $(x_a, y_j)$ and $(x_b, y_j)$.
This contradicts the assumption that $M_p$ is a matching and
shows that $\mbox{$\mathbb{M}$}'$ is a matching that contains all the agents.
\smallskip
\noindent
\textsf{Only If part:} Suppose $G'$ contains
a matching $\mbox{$\mathbb{M}$}'$ that includes all the agents.
We need to show that there is a set of at most $k$ matchings
$M_1$, $M_2$, $\ldots$, $M_k$ of \mbox{$G(\agset{}, \rset{}, E)$}{} such that
each agent appears in one of these matchings.
This can be done as follows.
Initially, each $M_p$ is empty, $1 \leq p \leq k$.
For each edge $(x_i, y_{j,p})$ in $\mbox{$\mathbb{M}$}'$, add the edge $(x_i, y_j)$
to $M_p$.
Since $\mbox{$\mathbb{M}$}'$ contains each agent $x_i$ once, by our construction,
$x_i$ appears as an end point of just one edge
in some set $M_p$.
We will show by contradiction that each nonempty $M_p$ is a matching
in \mbox{$G(\agset{}, \rset{}, E)$}.
So, suppose for some $p$, $M_p$ is not a matching.
Since each $x_i$ appears in just one edge of $\mbox{$\mathbb{M}$}'$,
if $M_p$ is not a matching, then some node $y_j$ appears
in two edges $(x_a, y_j)$ and $(x_b, y_j)$ in $M_p$.
By our construction, this happened because the edges $(x_a, y_{j,p})$
and $(x_b, y_{j,p})$ appear in $\mbox{$\mathbb{M}$}'$.
This contradicts the assumption that $\mbox{$\mathbb{M}$}'$ is matching in $G'$.
This completes our proof of the Only If part and also that of
Part~(a) of Lemma~\ref{lem:alg_problemrone}.
\smallskip
\noindent
\textbf{Part (b):}~ We now consider the running time of
\textsc{Alg-MRMA-R1}{}.
Step~1 which constructs the graph $G'$
can be carried out in time $O(n + km + k|E|)$ time.
Step~2 finds a maximum matching in $G'$.
Since $G'$ has $n + km$ nodes and $k|E|$ edges,
a maximum matching in $G'$ can be found in
$O(k|E|\,\sqrt{n + km})$
time using well known algorithms for maximum matching \cite{Hopcroft-Karp-1973}.
Since the matching $\mbox{$\mathbb{M}$}'$ has $n$ edges (i.e., exactly one
edge per agent), we can find the corresponding $k$ matchings of $G$
in $O(n)$ time.
Thus, the running time of the algorithm is dominated by Step~2.
In other words, the running time of the algorithm is
$O(k|E|\,\sqrt{n + km})$. \hfill\rule{2mm}{2mm}
\fi
\iffalse
To prove the approximation result, we note that for a universe $U$
with $t$ elements, the MSC problem cannot be approximated to within
the factor $o(\log{t})$ in polynomial time, unless \textbf{P} = \textbf{NP}{}
\cite{Vaz-2001}.
The above construction produces an instance of \textsc{AG-MRM}{}{}{} such that
if the number of rounds must beat most $t$,
for any solution to MSC of cost $\alpha$ corresponds to a solution
for the \textsc{AG-MRM}{} instance where the
budget of agent $x^*$ is equal to $\alpha$ and vice versa.
(In other words, when the number of rounds must be at most $t$,
the above reduction from MSC to \textsc{AG-MRM}{} is approximation
preserving.)
Thus, the approximation hardness of \textsc{AG-MRM}{} directly follows from that
of MSC. \qed
\fi
\iffalse
To prove the approximation result, we note that for a universe $U$
with $t$ elements, the MSC problem cannot be approximated to within
the factor $o(\log{t})$ in polynomial time, unless \textbf{P} = \textbf{NP}{}
\cite{Vaz-2001}.
The above construction produces an instance of \textsc{AG-MRM}{}{}{} such that
if the number of rounds must beat most $t$,
for any solution to MSC of cost $\alpha$ corresponds to a solution
for the \textsc{AG-MRM}{} instance where the
budget of agent $x^*$ is equal to $\alpha$ and vice versa.
(In other words, when the number of rounds must be at most $t$,
the above reduction from MSC to \textsc{AG-MRM}{} is approximation
preserving.)
Thus, the approximation hardness of \textsc{AG-MRM}{} directly follows from that
of MSC. \qed
\fi
\iffalse
\section{Additional Information for Section~\ref{sec:min_round_req_one}}
\medskip
\subsection{An Example to Illustrate the Construction in
Figure~\ref{fig:alg_problemrone}}
\begin{figure}[h]
\rule{\columnwidth}{0.01in}
\begin{minipage}{0.45\columnwidth}
\centering
\input{graph_one.pdf_t}
\end{minipage}
\quad
\begin{minipage}{0.45\columnwidth}
\centering
\input{graph_two.pdf_t}
\end{minipage}
\caption{An example to illustrate the algorithm in Figure~\ref{fig:alg_problemrone}.
The graph on the left is the original compatibility graph.
The graph on the right is the new graph produced by the Algorithm
in Step~1 with $k = 2$.
(The new edges are shown as dashes.)
The graph on the left has a two round matching $M_1$, $M_2$ that
matches each agent once: $M_1 = \{(x_1, y_1), (x_2, y_2)\}$ and
$M_2 = \{(x_3, y_1)\}$.
The corresponding maximum matching in the graph on the right
is $\mbox{$\mathbb{M}$}' ~=~ \{(x_1, y_{1,1}), (x_2, y_{2,1}), (x_3, y_{1,2})\}$.
}
\label{fig:example_alg_problemrone}
\rule{\columnwidth}{0.01in}
\end{figure}
\bigskip
\subsection{Statement and Proof of Lemma~\ref{lem:alg_problemrone}}
\medskip
\noindent
\textbf{Statement of Lemma~\ref{lem:alg_problemrone}:}~
Algorithm \textsc{Alg-MRMA-R1}{} (a) produces a solution iff the compatibility
graph \mbox{$G(\agset{}, \rset{}, E)$}{} has a $k$-round matching such that each
agent appears in one of the $k$ matchings, and
(b) runs in polynomial time.
\smallskip
\noindent
\textbf{Proof:}
\textbf{Part (a):}~\textsf{If part:} Suppose \mbox{$G(\agset{}, \rset{}, E)$}{} contains a $k$-round matching
$M_1$, $M_2$, $\ldots$, $M_k$ such that each agent $x_i$ appears
in one of the $k$ matchings.
We may assume without loss of generality that each
agent $x_i$ appears in exactly one matching.
(If an agent occurs in two or more matchings, we can remove all
but one of the occurrences.)
We will show that $G'$ has a matching that contains each node of \agset.
To see this,
consider the following set $\mbox{$\mathbb{M}$}'$ of edges in $G'$: for each edge
$(x_i, y_j)$ that appears in matching $M_p$ for some $p$
($1 \leq p \leq k$), add the edge
$(x_i, y_{j,p})$ to $\mbox{$\mathbb{M}$}'$.
Since each agent $x_i$ appears in one of the $k$ matchings
of \mbox{$G(\agset{}, \rset{}, E)$}, the agent also appears in one of the edges in $\mbox{$\mathbb{M}$}'$.
To show that $\mbox{$\mathbb{M}$}'$ is a matching, we will show by contradiction
that no node in \mbox{$\mathbb{R}$}{} appears in two or more edges of $\mbox{$\mathbb{M}$}'$.
So, assume that some node $y_{j,p}$ appears in two edges, say
$(x_a, y_{j,p})$ and $(x_b, y_{j,p})$, of $\mbox{$\mathbb{M}$}'$.
By our construction of $\mbox{$\mathbb{M}$}'$, this happened because matching $M_p$
contains both the edges $(x_a, y_j)$ and $(x_b, y_j)$.
This contradicts the assumption that $M_p$ is a matching and
shows that $\mbox{$\mathbb{M}$}'$ is a matching that contains all the agents.
\smallskip
\noindent
\textsf{Only If part:} Suppose $G'$ contains
a matching $\mbox{$\mathbb{M}$}'$ that includes all the agents.
We need to show that there is a set of at most $k$ matchings
$M_1$, $M_2$, $\ldots$, $M_k$ of \mbox{$G(\agset{}, \rset{}, E)$}{} such that
each agent appears in one of these matchings.
This can be done as follows.
Initially, each $M_p$ is empty, $1 \leq p \leq k$.
For each edge $(x_i, y_{j,p})$ in $\mbox{$\mathbb{M}$}'$, add the edge $(x_i, y_j)$
to $M_p$.
Since $\mbox{$\mathbb{M}$}'$ contains each agent $x_i$ once, by our construction,
$x_i$ appears as an end point of just one edge
in some set $M_p$.
We will show by contradiction that each nonempty $M_p$ is a matching
in \mbox{$G(\agset{}, \rset{}, E)$}.
So, suppose for some $p$, $M_p$ is not a matching.
Since each $x_i$ appears in just one edge of $\mbox{$\mathbb{M}$}'$,
if $M_p$ is not a matching, then some node $y_j$ appears
in two edges $(x_a, y_j)$ and $(x_b, y_j)$ in $M_p$.
By our construction, this happened because the edges $(x_a, y_{j,p})$
and $(x_b, y_{j,p})$ appear in $\mbox{$\mathbb{M}$}'$.
This contradicts the assumption that $\mbox{$\mathbb{M}$}'$ is matching in $G'$.
This completes our proof of the Only If part and also that of
Part~(a) of Lemma~\ref{lem:alg_problemrone}.
\smallskip
\noindent
\textbf{Part (b):}~ We now consider the running time of
\textsc{Alg-MRMA-R1}{}.
Step~1 which constructs the graph $G'$
can be carried out in time $O(n + km + k|E|)$ time.
Step~2 finds a maximum matching in $G'$.
Since $G'$ has $n + km$ nodes and $k|E|$ edges,
a maximum matching in $G'$ can be found in
$O(k|E|\,\sqrt{n + km})$
time using well known algorithms for maximum matching \cite{Hopcroft-Karp-1973}.
Since the matching $\mbox{$\mathbb{M}$}'$ has $n$ edges (i.e., exactly one
edge per agent), we can find the corresponding $k$ matchings of $G$
in $O(n)$ time.
Thus, the running time of the algorithm is dominated by Step~2.
In other words, the running time of the algorithm is
$O(k|E|\,\sqrt{n + km})$. \hfill\rule{2mm}{2mm}
\fi
\bigskip
\section{Additional Material for Section~\ref{sec:mrm_poly}}
\medskip
The steps of our algorithm \mbox{\textsc{Alg-MRM}}{} for \textsc{MRM}{} were
shown in Figure~\ref{fig:alg-mrma-prb}.
A slightly more detailed version of the algorithm that
mentions the intuition behind some of the steps
appears in Figure~\ref{fig:detailed-alg-mrma-prb}.
\begin{figure}[ht]
\rule{\columnwidth}{0.01in}
\begin{enumerate}
\item Starting from the given compatibility graph $G(X, Y, E)$,
create a new bipartite graph $G'(V', W', E')$ as follows.
To begin with, the sets $V'$, $W'$ and $E'$ are all empty.
\begin{enumerate}
\item For each resource node $y_j \in Y$, add $k$ nodes denoted
by $y_j^t$, where $t = 1, 2, \ldots, k$, to $W'$.
(\textbf{Intuition:}~ If node $y_j^t$ is included in the
matching, the interpretation is that resource $y_j \in Y$ is
matched to some agent in round $t$.)
\item For each agent node $x_i \in X$ with requirement $\rho_i = 1$,
do the following.
\begin{enumerate}
\item Add a new node $x_i^1$ to $V'$.
\item For each edge $\{x_i, y_j\} \in E$, do the following:
for each $t \in K_i$, add the edge $\{x_i^1, y_j^t\}$
to $E'$.
\end{enumerate}
\item For each agent node $x_i \in X$ with requirement $\rho_i \geq 2$,
do the following.
\begin{enumerate}
\item For each $t \in K_i$, add a node denoted by $x_i^t$ to $V'$.
(\textbf{Intuition:}~ If node $x_i^t$ is included in the
matching, the interpretation is that agent $x_i$ is matched
to some resource in round $t$.)
\item Add $q_i = |K_i|- \rho_i$ ``dummy-resource" nodes, denoted
by $z_i^{\ell}$, where $\ell = 1, 2, \ldots, q_i$, to $W'$.
(\textbf{Intuition:} Matching an agent node $x_i^t$ to a
dummy-resource node
$z_i^{\ell}$ means that agent $x_i$ is \emph{not} matched
in round $t$.)
\item For each edge $\{x_i, y_j\} \in E$ and each $t \in K_i$,
add the edge $\{x_i^t, y_j^t\}$ to $E'$.
\item For each node $x_i^t$, add the
$|K_i|- \rho_i$ edges $\{x_i^t, z_i^{\ell}\}$,
$1 \leq \ell \leq |K_i|-\rho_i$, to $E'$.
\end{enumerate}
\end{enumerate}
\item Find a maximum matching $M'$ in $G'(V', W', E')$.
\item If $M'$ does \emph{not} include all the nodes in $V'$, then
print ``No Solution" and \textbf{stop}.
\item Otherwise (i.e., $M'$ includes all the nodes in $V'$),
compute a collection of matchings $M_1$, $M_2$, $\ldots$, $M_k$, for
$G$ as follows. (\textbf{Note:}~ At the end, some of these matchings
may be empty.)
\begin{enumerate}
\item For each $\ell$, $1 \leq \ell \leq k$, initialize
$M_{\ell}$ to the empty set.
\item For each edge $e \in M'$ that does \emph{not} use a
dummy resource, do the following.
\begin{enumerate}
\item Let $x_i^{t}$ and $y_j^{\ell}$ denote the
end points of $e$.
\item Add the edge $\{x_i, y_j\}$ to $M_{\ell}$.
\end{enumerate}
\end{enumerate}
\end{enumerate}
\caption{A More Detailed Description of the Steps of \mbox{\textsc{Alg-MRM}}{} for \textsc{MRM}{}}
\label{fig:detailed-alg-mrma-prb}
\rule{\columnwidth}{0.01in}
\end{figure}
An example to illustrate the construction used in Step~1 of
the algorithm is shown in Figure~\ref{fig:constr_example}.
In that example, the compatibility graph $G(X, Y, E)$ (shown in
the left panel of Figure~\ref{fig:constr_example}) has three agent nodes
($x_1$, $x_2$, $x_3$) and two resource nodes ($y_1$ and $y_2$).
The number of rounds ($k$) is 3.
For each agent $x_i$, the set of allowed rounds
$K_i = \{1, 2, 3\}$, $1 \leq i \leq 3$.
The requirements for agents
$x_1$, $x_2$ and $x_3$ are 1, 2 and 2 respectively.
The right panel of Figure~\ref{fig:constr_example} shows
the new graph $G'(V', E', W')$ generated at the end of Step~1
of the Algorithm in Figure~\ref{fig:alg-mrma-prb}.
A maximum matching (of size 7) in the graph $G'$ and
the corresponding 3-round solution to the \textsc{MRM}{}
for the graph $G$ are shown in Figure~\ref{fig:sol-mmra-prb}.
\begin{figure}[tb]
\noindent
\rule{\columnwidth}{0.01in}
\smallskip
\centering
\input{ex_compatibility_graph.pdf_t}
\caption{An Example to Illustrate the Construction Used in
the Algorithm of Figure~\ref{fig:alg-mrma-prb}.
The left panel shows the original compatibility graph $G(X, Y, E)$
where the requirements $\rho_1$, $\rho_2$ and $\rho_3$
for agent nodes $x_1$, $x_2$ and $x_3$ are 1, 2 and 2 respectively.
The number of rounds $k$ is set to 3.
The right panel shows the new graph $G(V', W', E')$ constructed
using the the Algorithm of Figure~\ref{fig:alg-mrma-prb}.
The dummy resource nodes ($z_2^1$ and $z_3^1$) are shown as
open rectangles.}
\label{fig:constr_example}
\smallskip
\noindent
\rule{\columnwidth}{0.01in}
\end{figure}
\begin{figure}[htb]
\rule{\columnwidth}{0.01in}
\begin{minipage}{0.55\columnwidth}
\smallskip
\centering
\input{matching_larger_graph.pdf_t}
\smallskip
\end{minipage}
\hspace*{0.1in}
\begin{minipage}{0.35\columnwidth}
\textbf{Three-Round Solution for $G$:}
\begin{eqnarray*}
M_1 & = & \{\{x_1, y_1\}, \{x_2, y_2\}\} \\
M_2 & = & \{\{x_2, y_1\}, \{x_3, y_2\}\} \\
M_3 & = & \{\{x_3, y_2\}\} \\
\end{eqnarray*}
\end{minipage}
\caption{A Maximum Matching for $G'$ and the
corresponding Three-Round Solution for $G$}
\label{fig:sol-mmra-prb}
\smallskip
\noindent
\rule{\columnwidth}{0.01in}
\end{figure}
\medskip
\noindent
\textbf{Statement and Proof of Theorem~\ref{thm:alg_mmra_prb_correct}:}
(i) There is a solution to the \textsc{MRM}{} instance iff the graph
$G'$ constructed in Step~1 of Algorithm
\mbox{\textsc{Alg-MRM}}{} has a matching of size $|V'|$.
(ii) The running time of the lgorithm is
$O(k^{3/2}|E| \sqrt{|X|+|Y|})$.
\smallskip
\noindent
\textbf{Proof:}
\smallskip
\noindent
\textbf{Part (i):}~
Suppose $G'$ has a matching $M'$ of size $|V'|$.
Thus, $M'$ includes every node in $V'$.
We will show that the solution produced in Step~4 of \mbox{\textsc{Alg-MRM}}{}
satisfies the requirements of each agent by
considering two cases.
\smallskip
\noindent
\underline{Case 1:}~ Agent $x_i$ has requirement $\rho_i = 1$.
The node corresponding to $x_i$ in $G'$
is $x_i^1$. Note that $x_i^1$ is not adjacent to any dummy resource
node in $W'$.
Further, each edge adjacent to $x_i^1$ is of the form $\{x_I^1, y_j^t\}$
for some $t \in K_i$.
Thus, $M'$ must have the edge $\{x_i^1, y_j^t\}$
for some $j$ and some $t \in K_i$.
Since $M'$ is a matching, no other edge in $M'$
is incident on $y_j^t$. In our solution, the edge $\{x_i, y_j\}$
is added to $M_t$; that is, agent $x_i$ is matched to resource $y_j$
in round $t$.
\smallskip
\noindent
\underline{Case 2:}~ Agent $x_i$ has requirement $\rho_i \geq 2$.
Let $S_i = \{x_i^{\ell}: 1 \leq \ell \leq |K_i|\}$
denote the set of $|K_i|$ nodes in $G'$ that correspond to $x_i$.
Since only $|K_i|-\rho_i$ dummy resource nodes corresponding
to $x_i$ were added to $G'$, at least $\rho_i$ nodes in $S_i$
must be matched in $M'$ to non-dummy resource nodes.
Let $S'_i \subseteq S_i$ denote the subset of nodes of $S_i$
that are matched in $M'$ to non-dummy resource nodes.
Further, each $x_i^{\ell}$ has edges only to nodes of the form $y_j^{\ell}$.
Thus, for each node $x_i^{\ell} \in S'_i$, $M'$ contains the
edge $\{x_i^{\ell}, y_j^{\ell}\}$ for some $j$.
In other words, by considering $S'_i$, we can
find at least $\rho_i$ rounds and the corresponding resources
with which $x_i$ is matched in $\rho_i$ of the rounds in $K_i$.
We thus have a solution to the \textsc{MRM}{} instance.
\medskip
For the converse, suppose there is a solution to the \textsc{MRM}{}
instance consisting of $k$ matchings
given by $M_1$, $M_2$, $\ldots$, $M_k$.
By deleting edges from these matching arbitrarily, we can
ensure that each node $x_i$ with requirement $\rho_i$ appears
in exactly $\rho_i$ of the matchings $M_1$, $M_2$, $\ldots$, $M_k$.
We refer to this as the \textbf{pruning step} in the following discussion.
For simplicity, let the the matchings after the pruning step
be also denoted by $M_1$, $M_2$, $\ldots$, $M_k$.
We construct a matching $M'$ of size $|V'|$ for $G'(V', W', E')$
as follows.
Initially, $M'$ is empty.
\begin{enumerate}
\item Consider each node $x_i$ of $G$ such that $\rho_i = 1$.
By our pruning step, $x_i$ appears in just one matching,
say $M_t$, for some $t \in K_i$. Let $M_t$ contain the edge $\{x_i, y_j\}$.
By our construction of $G'$, the edge $\{x_i^1, y_j^t\}$ is in $E'$,
and we add that edge to $M'$.
\item Consider each node $x_i$ of $G$ such that $\rho_i \geq 2$.
By our pruning step, $x_i$ appears in exactly $\rho_i$ of the matchings
$M_1$, $M_2$, $\ldots$, $M_k$.
Let $H = \{1, 2, \ldots, k\}$.
Further, let $H_i = \{p_1, p_2, \ldots, p_{\rho_i}\}$ $\subseteq$ $H$
denote the set of indices such that for each $p_{\ell} \in H_i$,
$x_i$ appears in the matching $M_{p_{\ell}}$.
Note that $H_i \subseteq K_i$ and $|H_i| = \rho_i$.
By our construction of $G'$, for each $p_{\ell} \in H_i$,
the edge $\{x_i^{p_{\ell}}, y_j^{p_{\ell}}\}$ is in $E'$,
for some $j$.
For each $p_{\ell} \in H_i$, we
add the edge $\{x_i^{p_{\ell}}, y_j^{p_{\ell}}\}$ to $M'$.
Further, for $x_i$, $W'$ has a set $Z_i =$
$\{z_i^1, z_i^2, \ldots, z_i^{q_i}\}$ with $q_i = |K_i|-\rho_i$
dummy resource nodes.
For each node $x_i^t \in V'$ such that $t \not\in H_i$, we can match
$x_i^t$ with an arbitrary node in $Z_i$ and add the corresponding
edge to $M'$.
This ensures that $M'$ includes all the $|K_i|$ nodes in $V'$ that
correspond to $x_i$.
\end{enumerate}
Thus, the resulting $M'$ includes every node in $V'$.
This completes our proof of Part~(i).
\medskip
\noindent
\textbf{Part (ii):}~ We first estimate the number of nodes and
edges in $G'$.
For each node in $X \cup Y$ of $G'$, $G'$ adds at most $k$
nodes to $G'$.
Further, for each node in $X$, $G'$ has at most $k$ dummy
resource nodes.
Therefore, the total number of nodes in $G'$ is at most
$(k+1)|X| + k|Y|$ = $O(k(|X|+|Y|))$.
For each edge in $E$, at most $k$ edges are added to $G'$.
Further, for each node in $X$, at most $k$ edges are added to
dummy resource nodes of $G'$.
Therefore, the total number of edges in $G'$ is at most
$k|E| + k|X|$.
Since each agent is compatible with at least one resource,
we have $|X| \geq |E|$.
Thus, the number of edges in $G'$ = $O(k|E|)$.
In other words, Step~1 runs in $O(k(|X| + |Y| + |E|))$ time.
For any bipartite graph $\mbox{$\mathcal{H}$}(V_{\mathcal{H}}, W_{\mathcal{H}},
E_{\mathcal{H}})$,
it is well known that a maximum matching can be computed in
time $O(|E_{\mathcal{H}}| \times \sqrt{|V_{\mathcal{H}}
+ |W_{\mathcal{H}}|})$ \cite{CLRS-2009}.
Thus, the running time of Step~2 is
$O(k|E| \sqrt{k(|X|+|Y|)})$ =
$O(k^{3/2}|E| \sqrt{|X|+|Y|})$.
The matching $M'$ is of size $O(k|X|)$ and Step~4 of
the algorithm uses $O(1)$ time per edge in $M'$ to construct
the $k$-round matchings. Thus, Step~4 runs in $O(k|X|)$ time.
Thus, the dominant part of the running time is due to Step~2.
In other words, the running time of Algorithm~\mbox{\textsc{Alg-MRM}}{} is
$O(k^{3/2}|E| \sqrt{|X|+|Y|})$. \hfill$\Box$
\section{Additional Material for Section~\ref{sec:algmaxagmrm}}
\medskip
\begin{table}[htbp]
\begin{center}
\begin{tabular}{|c|p{4.5in}|}\hline
\textbf{Symbol} & \textbf{Explanation}\\ \hline\hline
\agset{} & Set of $n$ agents; \agset{} = $\{x_1, x_2, \ldots, x_n\}$ \\ \hline
\rset{} & Set of $m$ resources; \rset{} = $\{y_1, y_2, \ldots, y_m\}$ \\ \hline
$\mbox{$\mathcal{C}$}_i$ & Set of labels $\{c_i^1, c_i^2, \ldots, c_i^{\ell_i}\}$
of associated with agent $x_i$, $1 \leq i \leq n$.
(Thus, $\ell_i = |\mbox{$\mathcal{C}$}_i|$.)
\\ \hline
$\psi_i^t$ & Cost of removing the label $c_i^t$, $1 \leq t \leq \ell_i$ and
$1 \leq i \leq n$. \\ \hline
$\beta_i$ & Cost budget for agent $x_i$, $1 \leq i \leq n$.
(This is the total cost agent $x_i$ may spend
on removing labels.)
\\ \hline
$\rho_i$ & The minimum number of times an agent must appear in the
set of matchings. \\ \hline
$\Gamma_e$ & Set of labels appearing on edge $e$. (If an edge $e$ joins
agent $x_i$ to resource $y_j$, then $\Gamma_e \subseteq \mbox{$\mathcal{C}$}_i$.)
Edge $e$ can be added to the compatibility graph only
after \emph{all} the labels in $\Gamma_e$ are removed.
\\ \hline
$k$ & Upper bound on the number of rounds of matching \\ \hline
\end{tabular}
\end{center}
\caption{Notation Used in the Definition of \textsc{AG-MRM}{}{}{}{}
and the ILP Formulation of Section~\ref{sec:general_ilp}}
\label{tab:notation}
\end{table}
\iffalse
\section{Additional Material for
Section~\ref{sec:methods_per_round_budget}}
\medskip
\subsection{A Simpler ILP for \maxmrm{}}
\label{sup:sse:simpler_ilp}
Section~\ref{sec:general_ilp} presented an ILP for \maxagmrm{}.
Here, we present a simpler ILP for \maxmrm{} where
the compatibility graph $G(X, Y, E)$ is given.
\smallskip
\noindent
\textbf{ILP Formulation:}~
\smallskip
\noindent
\underline{\textsf{Variables:}}
\begin{itemize}
\item For each agent $x_i$, let $A_i$ denote the
set of resources with which $x_i$ is compatible;
that is, $A_i = \{y_j ~:~ \{x_i, y_j\} \in E\}$, $1 \leq i \leq n$.
For each agent $x_i$ and each resource $y_j \in A_i$,
we have $k$ \{0,1\}-variables
denoted by $a_{ijr}$, where $1 \leq i \leq n$, $1 \leq j \leq m$ and
$1 \leq r \leq k$.
The interpretation is that $a_{ijr}$ is 1 iff agent $x_i$ is matched
to resource $y_j$ in round $r$.
\item For each agent $x_i$, we have a non-negative integer
variable $\eta_i$ which gives the number of rounds
in which $x_i$ is matched.
\item For each agent $x_i$, we have a \{0,1\}-variable $s_i$
that is 1 iff agent $x_i$'s requirement is satisfied.
\end{itemize}
\smallskip
\noindent
\underline{\textsf{Objective:}}~ Maximize~~
$\sum_{i=1}^{n} s_i$.
\smallskip
\noindent
\underline{\textsf{Constraints:}}
\begin{itemize} [leftmargin=*,noitemsep,topsep=0pt]
\item For each agent $x_i$, the number of rounds
in which $x_i$ is matched should equal $\eta_i$.
This constraint can be expressed as
\begin{equation}
\sum_{r=1}^{k}\: \sum_{y_j \in A_i} a_{ijr} ~=~ \eta_i, ~~1 \leq i \leq n
\end{equation}
\item Each agent $x_i$ is matched to a resource \emph{at most once}
in each round. This constraint can be expressed as
\begin{equation}
\sum_{y_j \in A_i}\: a_{ijr} ~\leq~ 1, ~~1 \leq i \leq n,~~ 1 \leq r \leq k
\end{equation}
\item For each resource $y_j$, let $B_j$ denote the set of agents
with which $y_j$ is compatible, $1 \leq j \leq m$;
that is, $B_j = \{x_i ~:~ \{x_i, y_j\} \in E\}$, $1 \leq j \leq m$.
In each round, each resource must be matched to an agent
\emph{at most} once.
This constraint can be expressed as
\begin{equation}
\sum_{x_i \in B_j} a_{ijr} ~\leq~ 1, ~~
1 \leq j \leq m,~~ 1 \leq r \leq k
\end{equation}
\item The rounds in which an agent $x_i$ is matched
must be in $K_i$. The corresponding constraint is:
\begin{align}
a_{ijr} ~=~ 0, ~~ r \not\in K_i,~ 1 \leq j \leq m,~
1 \leq i \leq n
\end{align}
\item Variable $s_i$ to be 1
iff agent $x_i$ was matched
in at least $\rho_i$ rounds. The following constraints,
which must hold for each $i$, $1 \leq i \leq n$, ensure this
condition.
\begin{eqnarray*}
k\,s_i ~\leq~ \eta_i - \rho_i + k \\
k\,s_i ~\geq~ \eta_i - \rho_i + 1
\end{eqnarray*}
\item $a_{ijr} \in \{0,1\}$,
$1 \leq i \leq n$,~ $1 \leq j \leq m$,~ $1 \leq r \leq k$.
\end{itemize}
\medskip
\noindent
\underline{\textsf{Obtaining a Solution:}} After solving
the ILP, for each variable $a_{ijr}$ which is set to 1 in the
solution, we match agent $x_i$ with resource $y_j$ in round $r$.
\fi
\iffalse
\medskip
We now present an example to illustrate the above ILP
formulation.
\noindent
\textbf{Example:} In the compatibility graph shown below,
we have an agent $x_3$ which must appear in at least two rounds
of matching.
(Recall from Section~\ref{sec:general_ilp} that for each agent
$x_i$, $A_i$ is the set of resources to which $x_i$
can be matched. Likewise, for each resource
$y_j$, $B_j$ is the set of agents to which $y_j$
can be matched.)
\bigskip
\begin{center}
\begin{minipage}{0.3\textwidth}
\input{graph_one.pdf_t}
\end{minipage}
\hspace*{0.1in}
\begin{minipage}{0.4\textwidth}
\begin{itemize}
\item Let $k = 2$.
\item Let $\rho_1 = 1$, $\rho_2 = 1$ and $\rho_3 = 2$.
\item $A_1 = \{y_1\}$, $A_2 = A_3 = \{y_1, y_2\}$.
\item $B_1 = \{x_1, x_2, x_3\}$ and $B_2 = \{x_2, x_3\}$.
\end{itemize}
\end{minipage}
\end{center}
\medskip
\noindent
The ILP for the above problem instance is as follows.
\bigskip
\noindent
\underline{\textsf{Variables:}}~
$a_{1,1,1}$, $a_{1,1,2}$,
$a_{2,1,1}$, $a_{2,1,2}$,
$a_{2,2,1}$, $a_{2,2,2}$,
$a_{3,1,1}$, $a_{3,1,2}$,
$a_{3,2,1}$ and $a_{3,2,2}$.
(Each of these variables takes on a value from $\{0,1\}$.
The significance of variable $a_{ijr}$ is that it takes on the
value 1 iff agent $x_i$ is assigned resource $y_j$ in round $r$.)
\bigskip
\noindent
\underline{\textsf{Constraints:}}
\begin{itemize}
\item For Agent $x_1$: (i) $a_{1,1,1} + a_{1,1,2} ~\geq~ 1$,~
(ii) $a_{1,1,1} \leq 1$~ and (iii) $a_{1,1,2} \leq 1$.
(The last two constraints can be omitted since the fact
that each variable takes on a value from $\{0,1\}$
implies each of the last two constraints.)
\item For Agent $x_2$: (i) $a_{2,1,1} + a_{2,2,1}
+a_{2,1,2} + a_{2,2,2} ~\geq~ 1$,~
(ii) $a_{2,1,1} + a_{2,2,1} ~\leq~ 1$~ and
(iii) $a_{2,1,2} + a_{2,2,2} ~\leq~ 1$.
\item For Agent $x_3$: (i) $a_{3,1,1} + a_{3,2,1}
+a_{3,1,2} + a_{3,2,2} ~\geq~ 2$,~
(ii) $a_{3,1,1} + a_{3,2,1} ~\leq~ 1$ and
(iii) $a_{3,1,2} + a_{3,2,2} ~\leq~ 2$.
\item For Resource $y_1$:
\begin{description}
\item{(a)} $a_{1,1,1} + a_{2,1,1} + a_{3,1,1} ~\leq~ 1$
\item{(b)} $a_{1,1,2} + a_{2,1,2} + a_{3,1,2} ~\leq~ 1$
\end{description}
\item For Resource $y_2$:
\begin{description}
\item{(a)} $a_{2,2,1} + a_{3,2,1} ~\leq~ 1$
\item{(b)} $a_{2,2,2} + a_{3,2,2} ~\leq~ 1$
\end{description}
\end{itemize}
\bigskip
\noindent
\underline{\textsf{A solution:}} One solution that satisfies
all the above constraints is obtained by setting $a_{2,1,1}$, $a_{3,2,1}$,
$a_{1,1,2}$ and $a_{3,2,2}$ to 1 and all the other variables to 0.
This leads to the following matching in two rounds.
In Round 1, $x_2$ and $x_3$ are matched to $y_1$ and $y_2$
respectively; in Round 2, $x_1$ and $x_3$ are matched
to $y_1$ and $y_2$ respectively.
\section{Additional Material for Section~\ref{sec:experiments}}
\label{sup:sec:experiments}
Due to space limitation, we could not include the results of our experiments
with the \mbox{\emph{Passeport Vacances}}{} dataset in the context of \textsc{MRMA-R1}{} (\textsc{AG-MRM}{} with
requirement at least one) in the main paper. Those results are in
Figure~\ref{mrmar1_pv}. The experiment design is same as that explained
for Figure~\ref{mrmar1} (first three plots) with regard to \mbox{\emph{Course-Classroom}}{}
experiments. We note that the results indicate that among all
restrictions, activity preferences of children is the one that leads to the
most reduction in the number of rounds required when relaxed. Also, we note
that, unlike in the \mbox{\emph{Course-Classroom}}{} case, relaxation of combinations of attributes
does not have much effect compared to relaxation of the activity preference
alone..
\begin{figure}[!htb]
\centering
\includegraphics[width=.32\columnwidth]{figures/mrmar1_pv_1.pdf}
\includegraphics[width=.32\columnwidth]{figures/mrmar1_pv_2.pdf}
\includegraphics[width=.32\columnwidth]{figures/mrmar1_pv_3.pdf}
\caption{\textsc{MRMA-R1}{} results for \mbox{\emph{Passeport Vacances}}{}. In
the \mbox{\emph{Passeport Vacances}}{} plots, for relaxations beyond the values on the $x$-axes,
the results are unchanged.}
\label{mrmar1_pv}
\end{figure}
\begin{figure}[!htb]
\centering
\includegraphics[width=.5\columnwidth]{figures/mrma_heuristic_pv.pdf}
\caption{\textsc{SimAnn-MRMA}{} results for \mbox{\emph{Passeport Vacances}}{}. The graph that compares \textsc{SimAnn-MRMA}{} to \textsc{ILP-MRMA}{} is not presented since the runtime of \textsc{ILP-MRMA}{} on the \mbox{\emph{Passeport Vacances}}{} dataset is too long and not practical. }
\label{mrmar1_pv_2}
\end{figure}
\fi
\iffalse
\noindent
\textbf{Idea:}~ We will formulate the ILP for \textsc{MRMA}{} so that the subgraph (of the compatibility graph)
resulting from the solution is \emph{not} a matching but one
in which the degree of agent node $x_i$ is at least $\rho_i$.
We will add constraints to ensure that in each round, each agent
is matched to at most one resource.
We will also ensure through appropriate constraints that
in each round, each resource is assigned to at most one agent.
\fi
\subsection{\textsc{MRMA-PRB}{}: A variant of \textsc{MRMA}}
\label{sse:def_each_round_budget}
We also consider a variant of \textsc{MRMA},
denoted by \textsc{MRMA-PRB}{}, where the budget $\beta_i$
specified for each agent $x_i$ is for \emph{each round}
of matching.
Thus, the difference between \textsc{MRMA-PRB}{} and \textsc{MRMA}{}
is that in the latter, the budget is the upper bound on
the cost incurred by an agent \emph{over all the rounds}.
Except for this, the specifications of the decision and
minimization versions of \textsc{MRMA}{} and \textsc{MRMA-PRB}{}
are identical.
Because of the difference in the way the budget
is interpreted in \textsc{MRMA}{} and \textsc{MRMA-PRB}{},
it easier to construct the compatibility graph for the \textsc{MRMA-PRB}. To see why,
notice that for \textsc{MRMA}{}, the edges in the compatibility graph can be constructed only after the labels removed
by all the agents are known.
For \textsc{MRMA-PRB}, an agent $x_i$ can consider each incident
edge in the restrictions graph and add it
to the compatibility graph if the cost of
removing the labels on that edge is at most the budget.
This is possible because each such edge meets the
budget constraint and an agent uses
at most one edge in each round (matching).
Therefore, when considering \textsc{MRMA-PRB}{}, we may
assume that the input is the compatibility graph
(instead of the restrictions graph).
In this work, we establish complexity results and develop several
algorithms for the \textsc{MRMA}{} and \textsc{MRMA-PRB}{} problems. We experiment
with novel real-world datasets and synthetic data to study the performance
and utility of the algorithms. A summary of our contributions is as follows.
\begin{itemize}
\item Only a placeholder. Hopefully will have something by the end of our holiday.
\end{itemize}
\label{local_search}
\end{figure}
\begin{figure}
\includegraphics[scale=0.5]{figures/local_search.png}
\caption{\aacomment{is this required?} General budget; looking for optimal relaxation, changing agents that needs more than 2 matching; in this case 10. for different budgets.}
\label{local_search}
\end{figure}
\begin{figure}
\caption{General budget; looking for optimal relaxation, changing agents that needs more than 2 matching; in this case 10. budget =2, compare local search and ILP}
\paragraph{ILP vs Heuristic}
Running the heuristic may take few minutes , ilp may even few days.
The quality ?
\paragraph{Budget sufficient for each matching separately}
In Figure~\ref{school_k} and figure~\ref{class_k} we compared between the ILP and the heuristic for finding how many matchings are need to satisfy the agents' requests where the budget should be sufficient for each matching separately. In \ref{school_k} we study the children Summer Vacation
Activities and in Figure~\ref{class_k} we refer to the class room data set. That is the agents refer to children and courses respectively and resources refer to activities and classes, respectively.
In Figure~ \ref{school_times} and \ref{class_times} we report the time needed for these settings for the children activity and the courses datesets respectively.
\begin{figure}
\includegraphics[scale=0.5]{figures/school_times.png}
\caption{Budget for each matching, school time}
\label{school_times}
\end{figure}
In Figure~ \ref{school_times} we ran:
\begin{itemize}
\item run time for greedy and ilp
\item using cbc solver. tried also gurobi which considered as state of the art.
\end{itemize}
\begin{figure}
\includegraphics[scale=0.5]{figures/class_k.png}
\caption{Budget for each matching, courses, k}
\label{class_k}
\end{figure}
In Figure~ \ref{class_k}:
\begin{itemize}
\item Same definitions but for courses and classes
\end{itemize}
\begin{figure}
\includegraphics[scale=0.5]{figures/class_times.png}
\caption{Budget for each matching, courses,time }
\label{class_times}
\end{figure}
In Figure~ \ref{class_times}:
\begin{itemize}
\item Same definitions but for courses and classes
\end{itemize}
\begin{figure}
\caption{General budget, random graph; different probability.at least 1, k as a function of m }
\label{random_k}
\end{figure}
In Figure~\ref{random_k}
\begin{itemize}
\item Relaxing 0.0,0.2,0.4,0.6,0.8 or 1.0 of the constraints for each relevant attribute.
\item Remove agents with no edges in the beginning.
\item save runtimes as well
\item choose k by using algorithm of at least one.
\end{itemize}
\begin{figure}
\includegraphics[width=\columnwidth]{figures/relax_course_class.pdf}
\caption{General Budget, courses increasing budget and its effect on different attributes, at least one}
\label{relax_course_k_1}
\end{figure}
\begin{itemize}
\item Random graphs. agents are chosen among large initial set such that they will have at least 1 edge.
\item No requirement from the resources.
\item 4 data points, 100,0.75,0.5,0.25
\item run massively in parallel, 1000 times per option.
\end{itemize}
The first
set of experiment results corresponds to \textsc{MRMA-R1}, followed by results
for \textsc{MRMA-PRB}{} where we compare
\textsc{ILP-MRMA-PRB}{} with \textsc{Greedy-MRMA-PRB}. The third set
corresponds to the general \textsc{MRMA}{} where we compare \textsc{ILP-MRMA}{} with
\textsc{Greedy-MRMA}.
\medskip
\noindent
\textbf{Problem Statement:} (Decision Version)
\noindent
\underline{\textsf{Given:}}~ A restriction graph $G_R(\agset, \rset, E_R)$;
for each agent $x_i$,
two positive integers $\beta_i$ (budget on the total cost of removing labels) and
$\rho_i$ (the minimum
number of times $x_i$ should be matched), $1 \leq i \leq n$;
for each edge $e = \{x_i, y_j\} \in E_R$, a subset $\Gamma_e \subseteq \mbox{$\mathcal{C}$}_i$
of labels;
for each label $c_{i,t}$, a cost $\psi_{i,t}$ of removing
that label, $1 \leq t \leq \ell_i$ and
$1 \leq i \leq n$;
a positive integer $k$ (the upper bound on the number of rounds
of matching).
\smallskip
\noindent
\underline{\textsf{Requirement:}}~ For each agent $x_i$, is there a
subset $\mbox{$\mathcal{C}$}'_i \subseteq \mbox{$\mathcal{C}$}_i$ such that the following
conditions hold?
\begin{description}
\item{(i)} The cost of removing all the labels in $\mbox{$\mathcal{C}$}'_i$ for agent $x_i$
is at most $\beta_i$, $1 \leq i \leq n$, and
\item{(ii)} the compatibility graph \mbox{$G(\agset,\,\rset,\,E)$}{} resulting
from the removals of labels has a collection of at most $k$ matchings
$M_1$, $M_2$, $\ldots$, $M_k$, with agent $x_i$ appearing in at least
$\rho_i$ of these matchings.
\end{description}
the general version of the problem for minimizing the number of rounds
when some agents need to be matched two or more times.
Further, for each agent, the total cost of relaxation
over all the rounds must be within the agent's budget.
We will consider scenarios where~$\rho(\cdot)$ is a constant function. In
such cases, we will use the notation~$r$ to refer to this constant and
denote this special case as~\textsc{MRMA}$(G_R,\cost,b,k,r)$.
Given a restrictions graph~$G_R(\agset\cup\rset,E_R)$ coresponding
to~$n_{\agset}$ agents~$\agset$ and~$n_\rset$ resources~$\rset$ with
agent-specific restrictions defined by~$E_R$, a
function~$\cost(\cdot)$ that defines the cost incurred in removing a subset
of agent-specific restrictions, budget~$b:\agset\rightarrow\mathbb{Z}$,
number of rounds~$k$ and minimum number of matchings
$\rho:\agset\rightarrow\mathbb{Z}$.
\smallskip
\noindent
\textbf{Problem.} For each agent~$x$, find a set of
restrictions~$C\subseteq C_x$ to remove such that~$\cost(C_x)\le b(x)$ and
the resulting compatibility graph~$G_C$ has~$k$ matchings where each
agent~$x$ is matched at least~$\rho(x)$ times.
:~\tikz[baseline=-.5ex]{\node
(x) {$x_i$}; \node at (1,0) (y) {$y_j$}; \draw (x) --
node[label=above:{\scriptsize $C$},shift={(0,-.15)}]{} (y)}
se have formulate the problem of multi-round matching
generating advice (i.e., suggesting relaxations of agents' requirements) so
that all agents can be matched to resources using a minimum number of
rounds. (Each round allows a subset of agents to access resources.)
\noindent
\textbf{Multi-round matching with advise.} We describe a multi-round
resource allocation problem called~\textsc{MRMA}{} where
a set of agents are matched to resources given agent restrictions and
resource specifications in a specified number of rounds. Relaxation of each
restriction incurs a cost. The objective is
to advise agents to relax certain restrictions in order to match resources
Let~$\mathcal{Z}'\subseteq\mathcal{Z}$ be a solution to the set cover instance. This
means that there exist~$\alpha$ subsets that cover~$U$. We will remove the
corresponding labels in~$G_R$. Since~$\mathcal{Z}'$ covers all elements in~$z_j
\in U$,~$\exists A_h\in \mathcal{Z}'$ that contains it. This implies that there
is no label on the edge~$y^j_h$. The special agent~$x^*$ can be matched to
one such~$y^j_h$ in each matching. For any~$z_j\in U$, since there are
only~$k\cdot\deg(z_j)-1$ agents in~$\agset^j$ all of which are adjacent
to the same set of~$\deg(z_j)$ resources, there are enough resources to match
each~$x\in\agset^j$ in some matching.
For each agent~$x$, there is a cost
associated with removing restrictions. Let~$\cost: 2^{C_x}\rightarrow \mathbb{R}$
be a mapping of each subset of agent~$x$'s constraints to a real number.
Each resource in \rset{} is
associated with a collection of \emph{attributes}, and
each attribute takes on values from a finite domain.
Every agent would like to be matched to a resource.
However, agents may have
\emph{preferences} that prevent them from being matched to certain
resources. Such agent-resource pairs are said to be \emph{incompatible}. The problem of assigning
resources to agents can be seen
as a \emph{maximum matching problem} \cite{CLRS-2009} on a \emph{bipartite graph}
$G(\mbox{$V_{\mathbb{X}}$}, \mbox{$V_{\mathbb{Y}}$}, E)$, where the node sets \mbox{$V_{\mathbb{X}}$}{} and \mbox{$V_{\mathbb{Y}}$}{}
correspond to agents and resources respectively and each
edge $\{u,v\} \in E$, with $u \in \mbox{$V_{\mathbb{X}}$}$ and $v \in \mbox{$V_{\mathbb{Y}}$}$,
indicates that the agent represented by $u$ is compatible
with the resource represented by $v$.
We refer to $G$ as the \textbf{compatibility graph}.
\emph{While the matching problem on $G$ plays a role in our work,
our focus is not on that problem.}
We will use the following running example of matching courses to
classrooms. Each classroom is a resource and each course (or its
instructor) is an agent. Classrooms have three attributes: capacity, region
(building or division) and accessibility (i.e., whether it can accommodate
students with disabilities). For each classroom, the values of these
attributes represent the constraints associated with that classroom. Each course has preferences such as the required minimum and maximum capacity
values, preferred regions, and whether it requires an accessible classroom.
Formally, let~$\agset =\{x_1,x_2,\ldots, x_n\}$ be a set of~$n$ agents
and~$\rset =\{y_1,y_2,\ldots, y_m\}$ be a set of~$m$ resources.
Each resource is characterized by a finite set of~$\alpha$ attributes. It is
assumed that each attribute can take on a finite set of values and that these values can be either symbolic or discrete. The values of $y_j$'s attribute, $a$, are denoted as $y^a_{j}$. The vector of attribute values for a resource $y_j$ is denoted as $b_j$.
Each agent~$x_i$ expresses its preferences as personal ordering, capacity with lower and upper bounds and binary decision.
The personal ordering threshold is modeled as the threshold function- $t(f_i(y^a_{j}),0)=f_i(y^a_{j})>0$. For this function, the attribute values are symbolic. The symbolic values are converted to real values according to the personal preferences of agent~$x_i$ and the maximum among them is chosen using $f_i$.
Regarding the binary decision, the possible attribute values are $\{-1,1\}$ and the threshold function is one of $t(f_i(y^a_{j}),0)$ and $t(f_i(-y^a_{j}),0)$ where $f_i$ is choosing the maximum value among the values of $y^a_{j}$.
Capacity is modeled as a couple of threshold functions; A set of two thresholds, $5<=x^a_{i}<=10$, is written as $t(f_i(y^a_{j}),5)$ and $t(f_i(-y^a_{j}),-10)$ where like before, $f_i$ is choosing the maximum among values of $y^a_{j}$.
The whole preference set of an agent, including the $f_i$ function for converting symbols to real numbers is defined as a conjunction of threshold functions denoted as $\kappa_i = \{R|S\}^\alpha \longrightarrow \{0,1\}$. In case when all clauses of the conjunction function belong to the binary decision class, the conjunction of threshold functions could be modeled as a simple conjunction of Boolean variables.
\\
\noindent
\textbf{Example 1:}~
We now illustrate the above definitions using the course-classroom example. Suppose each classroom has a
capacity between~$10$ and~$50$ in steps of 10, and there are four regions numbered~1 through 4.
Here, we have two attributes ($\alpha=2$).
Let~$y_1$ be a
classroom in region~$'3'$ with capacity~$30$ and~$y_2$ be a classroom
in region~4 that can accommodate courses of size ~$50$.
Suppose the instructor
for the course~$x_1$ has the following preference over the regions- $(4,2,3,1)$ and requires that the selected region will be $>=3$. Suppose also that the instructor requires that the capacity will be in the range ~$20$ and~$30$.
The corresponding
compatibility function is
$\kappa_1=(20 \leq c \leq 30) \And (~3\leq f_i(r))$ for $c=30$ and $r='3', f_i('3')=3$ and in more formal way,$\kappa_1(b_1) =1$ for $b_1=(30, '3')$.
Note that~$x_1$ is compatible with $y_1$;
in fact, $x_1$'s preferences satisfy both the capacity and region
constraints of $y_1$.
However, $x_1$ is not compatible with ~$y_2$.
\paragraph{The advice framework.}
The following are the steps in the maximum matching advice framework.
\begin{enumerate}[leftmargin=*,noitemsep,topsep=0pt]
\item Every agent $x_i$ in~$\agset$ sets its preferences by specifying the thresholds and the $f_i$ function in $\kappa_i$.
\item For each agent-resource pair $(x_i,y_j)$,
if~$\kappa_i(b_j))=1$, we add the edge $\{x_i,y_j\}$ to the
compatibility graph $G$.
\item The nodes are ordered deterministically and the \hk{} algorithm is applied.
\item Few unmatched agents approach the \mbox{\textsc{Principal}}{} with the query as to why they were not matched.
\item For each unmatched agent, $x_i$, the \mbox{\textsc{Principal}}{} adds to the compatibility graph, $G$, all edges that fulfil a budget constraint specified by agent $x_i$.
\item Then, the principal is running again the \hk{} algorithm:
\begin{itemize}
\item With only the unmatched agents and resources.
\item With all agents and resources
\item with all agents and resourses, starting with matching only previously matched agents and then augmenting that matching.
According to the proof of $\hk{}$, it is guaranteed that the resulting matching will be a maximum matching that contains all previously matched agents.
\end{itemize}
\item Finally, for each matched agent among the approaching agents, the \mbox{\textsc{Principal}}{} suggests to relax the relevant constraint as a \textsc{MRMA}{}.
\end{enumerate}
We now introduce certain concepts related to the last few steps above
and formulate the \textsc{MRMA}{} problem.
\paragraph{The advice framework alternative.}
The following are the steps in the maximum matching advice framework.
\begin{enumerate}[leftmargin=*,noitemsep,topsep=0pt]
\item Every agent $x_i$ in~$\agset$ sets its preferences by specifying the thresholds and the $f_i$ function in $\kappa_i$.
\item For each agent-resource pair $(x_i,y_j)$,
if~$\kappa_i(b_j))=1$, we add the edge $\{x_i,y_j\}$ to the
compatibility graph $G$.
\item The nodes are shuffled and the \hk{} algorithm is applied.
\item Few unmatched agents approach the \mbox{\textsc{Principal}}{} with the query as to why they were not matched.
\item The \mbox{\textsc{Principal}}{} creates a new empty compatibility graph $G\prime$ with the unmatched nodes and the unmatched resources as nodes.
\item Then, for each matched agent among the approaching agents, the \mbox{\textsc{Principal}}{} suggests to relax some constraints as a \textsc{MRMA}{}.
\item According to the decision of the remaining agents, the \mbox{\textsc{Principal}}{} adds to the new compatibility graph, $G'$, all new compatible edges.
\end{enumerate}
We now introduce certain concepts related to the last few steps above
and formulate the \textsc{MRMA}{} problem.
\paragraph{Suggesting changes to~$\kappa_i$ through extensions.} The
objective is to suggest modifications to the compatibility function in such
a way that any resource that is already compatible (but unmatched)
continues to be compatible with the agent, and additional resources become
compatible as a result of the modifications.
Such modifications increase the chances
of the agent being matched. Therefore, we will consider only modifications that
satisfy the following property: $\kappa'_i$ is an \textbf{extension}
of~$\kappa_i$; i.e., for any input~$b_j$,~$\kappa_i(b_j)=1$ implies that~$\kappa'_i(b_j)=1$.
Continuing with our course-classroom example, there are two ways to obtain
an extension of~$\kappa_1$: we can either increase threshold bound or remove it totally. For instance,
$\kappa'_1= (20 \leq c \leq 60 )$
is an extension of~$\kappa_1$ considered in Example~1.
It was obtained by replacing the current threshold of $30$ with the new threshold- $60$ and removing the region preferences threshold.
Now,~$x_1$ is compatible with~$y_2$ also.
\paragraph{Cost and benefit of extending~$\kappa_i$.} For each attribute~$a\in
\mathcal{A}$, we will assign a cost~$\chi(a)$ for changing its value in one step. If~$a$ is untouched, then, no cost is incurred.
The benefit of extending~$\kappa_i$ to~$\kappa'_i$ is having ~$x_i$ matched in some cases.
We are now ready to define formally the advice framework. Given a set of
agents~$\agset$, resources~$\rset$, attributes ~$\mathcal{A}$ and
the compatibility graph~$G(V_\agset,V_\rset,E)$, the advice framework
for agents~$x_i...x_j$ is denoted
by~$\mathcal{E}_i({\mathbf b}_i,\kappa_i,\chi)$,
where~${\mathbf b}_i{(\cdot)}$ is
the attribute function,~$\kappa_i$ is the
current compatibility function of~$x_i$ and~$\chi(\cdot)$ is the cost
function. Now we define the \textsc{MRMA}{} problem.
\begin{definition}[Problem {\normalfont \textsc{MRMA}}]
For a set of customers~$\{x_i...x_j\}\in X$ with advice
frameworks ~$\mathcal{E}_i({\mathbf b}_i,
\kappa_i,\chi)$ and
budgets~$\beta_i$, find~$\kappa^*_i$ that maximizes benefit with costs $\leq$ $\beta_i$;.
\end{definition}
Suppose there are two
sets of restrictions~$C$ and~$C'$ such that if either one of them is
removed,~$x$ becomes compatible with~$y$, then, we draw two separate edges
between them with one lableled~$C$ and the other~$C'$.
Numbers:
AND: Average(maximum(0,Exhaustive probability - Greedy))=0.016, stdev= 0.06837. min(pi +) for the greedy and exhustive algorithm were 0, 0 and max values were 1 and 1.
OR: Average(maximum(0, Exhaustive probability - Greedy))=0.0085, stdev= 0.01256. min(pi +) for the greedy and exhustive algorithm were 0.502 and 0.485 and max values were 1 and 1.
The parameters with greatest covariance were B (0.02 in AND and 0.0007 in OR) and resources_amount( -0.03 and 0.0036) .
For the AND case I run ~300 experiments when setting the other parameters to some constant value. I found that when the world (B) is greater, the error is also greater. I couldn't have the same findings on the OR case since the greedy and the exhaustive gave very similar probabilities.
A graph for the AND case with |B| as the X axis, is available on the sup_figures folder(with some more heatmaps and the graph with the distinct number of resources per 100 when having different amounts of attributes and values).
Parameters that were used for the AND case for verifying the effect of B were: R=1, Gamma=3, #of resources=40.
and (ii)~evaluation of the algorithms developed for the \textsc{MRMA}{} under
different explanation frameworks.
\begin{figure}[t]
\centering
\begin{tabular}{cc}
\includegraphics[height=2.5cm,width=0.5\linewidth]{figures/theta1_change_2.png}&
\includegraphics[height=2.5cm,width=0.5\linewidth]{figures/theta2_change_2.png}\\
\multicolumn{2}{c}{\includegraphics[height=2.5cm,width=0.5\linewidth]{figures/p_change_2.png}}
\end{tabular}
\caption{Uno vs Hopkroft}
\label{fig:exp_utility_cmp}
\end{figure}
\begin{itemize}
\item We run each experiment 1000 times
\item Results for 10*10 random graphs were considered. We tried also {5-15}*10 graphs with no important conclusions.
\item For each graph class the parameters for $\theta_hk$ were different.
\item For measuring our results on larger graphs we run the hk-uno algorithm with different parameters on the real dataset and on larger random graphs(e.g., $40*40$ and $80*40$. Here we couldn't calculate the true probabilities because it can take forever. We therefore assumed that lower variance may predict on better parameter set. We found that increasing the number of uno iterations is not improving the variance while the number of hk improves it linearly. That was the reason for using only Hopkroft iterations in the relaxation problem.
\item Runtime of Hopkroft was significantly longer than of a single Uno iteration. HK as a preference because it can run in parallel.
\end{itemize}
\paragraph{Datasets.}
\subsubsection{Children School Vacation.}
A real dataset ~\cite{varone2019dataset}, based on online registration during the summer of 2017 for assigning holiday activities to children.
Each activity has a relevant age range. In addition, dataset contains some children preferences. Some of the activities were very expensive and therefore a child was permitted to participate in them only once in her life. There were three holiday periods in the dataset. Authors suggested a linear program for solving the relevant optimization problem in the case when assigning at most one activity per child is permitted.
\begin{itemize}
\item 634 children participated.
\item there were three vacation period. I picked the one that started at 09/10/2017 0:00 and ended at 15/10/2017 0:00.
\item there were 249 relevant activities in the relevant period (out of 496 in total).
\item Attribute Preferences has the values: 1,2,3,4,5. 1-4 are explicit ratings that provide partial order.
and 5 is when there is no such rating. I assumed that 5 is worse than the other 4 for having a complete order.
\item Attribute min age with values 6-15
\item Attribute max age with values 7-16
\item I did not use the lifetime attribute in the school children case because it was very rare and with no important meaning.
\item There were 3 distict vacation periods in the graph, I picked one of them.
\item I added all children to the matching.
\item The most relaxed parameter was the preference. In many cases it was relaxed to 5. It means that they need to find a way to increase number of ratings for having better idea about the preferred activities.
\end{itemize}
\subsubsection{Courses and classrooms graphs}
Although the problem of assigning classrooms to courses is quite common ( e.g., ~\cite{phillips2015integer} ) we couldn't find a dataset that is good for our needs. We collected a new classroom assignment dataset from
a university on 2018-2019 \footnote{Additional information about
the data set will be provided in the final version of the paper}. For each of the 144 classrooms, a region in the university and total student capacity is given. In addition, each classroom has details about its available disability accessories. For many of the courses there were specific region preferences. Since we couldn't find real details about people with disability, we generated the relevant data randomly, giving a course 10 percents for needing one of the accessories and 1 percent for needing both.
\begin{itemize}
\item We have the Capacity attribute with values from 16 to 270
\item there are also the region attributes with values {1100,900,200,400,500,300,100,1000 }
\item As discussed, their order was determined randomly.
\the hearing and accessible attributes were generated randomly as before.
\item 144 rooms
\item I picked all courses that used at least part of the window of Tuesday, 14:00 pm- 16:00 pm.
\item I filtered out randomly about 40 percents of the rooms for having lower matching probabilities.
\item The administrator said that they have to keep 20 percents of the rooms empty for some events.
\item The initial number of courses in the time-range is 154.
\end{itemize}
\subsection{Evaluating \textsc{RhkUno}{} algorithm.}
The main objective was to assess the quality of the algorithm.
For the \rhk{} algorithm, we used the implementation of the python networkx package~(\citeyear{SciPyProceedings_11}). For the Uno~(\citeyear{uno1997algorithms}) iterations, we used a github implementation. \footnote{https://github.com/Xunius/bipartite\textunderscore matching} as a basis. For making the implementation simple we did not implement the suggested speed up improvements.
For measuring the quality of the \rhk{} algorithm and determining its parameters we generated a large set of random graphs. Graphs differ in their $P$ values, which is the probability of an edge to exist. They also differ in the number of the nodes in each of their parts. For each graph and for each of its nodes, the ~$\empprob$ was calculated by using \rhk{} with different parameters. The results were averaged over multiple nodes and multiple graphs and compared to the ~$\trueprob$ by using the Uno~(\citeyear{uno1997algorithms}) algorithm.
\begin{figure}
\includegraphics[height=6cm,width=9cm]{figures/0.35_10_10_1000.png}
\caption{An example heatmap that shows the Average MSE in a set of $1000$ random graphs with $P=0.35$, $n=10$ and $m=10$. The y axis represents $\nhk$ and the x axis represents $\nuno$. The brighter squares indicate greater mistakes. }
\end{figure}
\subsection{Performance of the algorithms for calculating ~$\mathcal{E}_i^{\text{AND}}$\label{alg:and_greedy} and ~$\mathcal{E}_i^{\text{AND}}$\label{alg:or_greedy} on synthetic graphs.}
\begin{itemize}
\item For both the AND and OR cases, I used the parameters: R= values per Attribute,{1..5}
B= world size, {2,4,6,8,10,12}
Gamma= preferences size, { 1..5 }
Resources amount, {20,40}
Budget { 1...5 }
\item for the AND case, the average difference between the greedy heuristic and the exhustive search was 0.02 for all 6921 experiments.
\item In my implementation, I called the oracle for each set of relaxed resources (1 or more) without checking if it increased the matching size.
\item In the OR case there was no significant difference. Actually the greedy was better in 0.001 percents (negligible because of the error).
\Item I found that as the world (B) is greater, the error is also greater.
\end{itemize}
\subsection{Performance of the algorithm for calculating ~$\frameworkth$\label{alg:thresh} on the real datasets.}
>>>>>>> 9b9805c8d9813b8318c8eabf60ef4957b5e7121e
\begin{itemize}
\item I picked all courses that used at least part of the window of Tuesday, 14:00 pm- 16:00 pm.
\item I filtered out randomly about 40 percents of the rooms for having lower matching probabilities.
\item The administrator said that they have to keep 20percents of the rooms empty for some events.
\item The initial number of courses in the time-range is 154.
\end{itemize}
\begin{itemize}
\item We run each experiment 1000 times
\item Results for 10*10 random graphs were considered. We tried also {5-15}*10 graphs with no important conclusions.
\item For each graph class the parameters for $\theta_hk$ were different.
\item For measuring our results on larger graphs we run the hk-uno algorithm with different parameters on the real dataset and on larger random graphs(e.g., $40*40$ and $80*40$. Here we couldn't calculate the true probabilities because it can take forever. We therefore assumed that lower variance may predict on better parameter set. We found that increasing the number of uno iterations is not improving the variance while the number of hk improves it linearly. That was the reason for using only Hopkroft iterations in the relaxation problem.
\item Runtime of Hopkroft was significantly longer than of a single Uno iteration. HK as a preference because it can run in parallel.
\end{itemize}
The main objective was to assess the quality of the algorithm. For the
\rhk{} algorithm, we used the implementation of the python networkx
package~(\citeyear{SciPyProceedings_11}) and for the ``Uno'' component of
the algorithm we used a github
implementation\footnote{https://github.com/Xunius/bipartite\textunderscore
matching} as a basis. For making the implementation simple we did not
implement the suggested speed up improvements. For measuring the quality
of the \rhk{} algorithm and determining its parameters we generated a large
set of random
graphs. Graphs differ in their $P$ values, which is the probability of an
edge to exist. They also differ in the number of the nodes in each of their
parts. For each graph and for each of its nodes, the ~$\empprob$ was
calculated by using \rhk{} with different parameters. The results were
averaged over multiple nodes and multiple graphs and compared to the
~$\trueprob$ by using the Uno~(\citeyear{uno1997algorithms}) algorithm.
Parameter sets for both AND and OR cases:
R= values per Attribute,{1..5}
B= world size, {2,4,6,8,10,12}
Gamma= preferences size, { 1..5 }
Resources amount, {20,40}
Agents amount, {40 for 20 resources and 80 for 40 resources}
Budget { 1...5 }
\section{Additional Material for Section~\ref{sec:rmmrm_poly}}
\label{sup:sec:rmmrm_poly}
\medskip
\subsection{Statement and Proof of Lemma~\ref{lem:saturated_matching}}
\medskip
\noindent
\textbf{Statement of Lemma~\ref{lem:saturated_matching}:}~
Given any maximum weight matching $M$ for $G'$, a saturated
maximum weight matching $M'$ for $G'$ with the same weight
as $M$ can be constructed.
\begin{proof}
Recall that for each agent~$x_i$, there are~$|K_i|$ copies denoted
by~$x_i^t$,~$t\in K_i$ in~$G'$ by our construction. First, we will show by contradiction that
every type-3 resource is matched in~$M$.
Suppose a type-3 resource~$y^3_{i,p}$ is not matched.
By our construction, this resource has edges only to
copies of nodes corresponding to $x_i$.
There are two cases.
\noindent
\underline{Case 1:}~
There is a node $x_i^{t'} \in X'$ that is not
matched in $M$. Here, we can add the edge
$\{x_i^{t'}, y^3_{i,p}\}$ with weight $k+1 \geq 2$ to $M$;
this would contradict the fact that $M$ is a maximum
weight matching for $G'$.
\noindent
\underline{Case 2:}~
Every copy of $x_i$ is matched in $M$.
In this case, at least one copy of $x_i$, say $x_i^{t'}$,
is matched to a type-1 or type-2 resource node, and
weight of the corresponding edge is at most 1.
We can replace that edge in $M$ by the edge
$\{x_i^{t'}, y^3_{i,p}\}$ with weight $k+1 \geq 2$
to create a new matching whose weight is larger than
that of $M$. Again, this contradicts the maximality
of $M$.
\smallskip
We thus conclude that every type-3 resource node
is matched in $M$.
\smallskip
We now argue that $M$ can be modified to include
all the nodes of $X'$ without reducing
the total weight.
Consider any agent $x_i$.
As argued above, $|K_i|-\rho_i$ copies of $x_i$
are matched to type-3 resources in $M$.
Now consider the remaining~$\rho_i$ copies of~$x_i$. Suppose a
copy~$x_i^{t'}$ is unmatched in~$M$. Recall that every type-2 resource is
adjacent to every~$x_i^t$ and no other~$x_{i'}^t$ where~$i'\ne i$. Also,
there are~$\rho_i$ type-2 resources. This implies there exists at least one
unmatched type-2 resource to which~$x_i^{t'}$ can be matched. Also, we note
that such a scenario occurs only if the weight corresponding to edge
of~$x_i^{t'}$ and any unmatched type-2 resource is~$0$. (Otherwise, by
adding this edge, one can increase the weight of the matching contradicting
the fact that~$M$ is a maximum weighted matching.)
\smallskip
Therefore, if~$M$ is not saturated, we can construct a saturated
matching~$M'$ from~$M$ as follows. We include all the edges of~$M$ in~$M'$.
Then, we match each unmatched copy~$x_i^{t'}$ to an available type-2
resource. Thus, all nodes of~$X'$ are matched in~$M'$.
\end{proof}
\subsection{Statement and Proof of Lemma~\ref{lem:benefit-to-matching}}
\medskip
\noindent
\textbf{Statement of Lemma~\ref{lem:benefit-to-matching}:}~
Suppose there is a solution to the \mbox{\textsc{MaxTB-MRM}}{} problem instance with
benefit $Q$. Then, there a saturated matching $M$ for $G'$
with weight $Q + \lambda$ can be constructed.
\begin{proof}
Let~$\mathcal{M}$ be the solution to the \mbox{\textsc{MaxTB-MRM}}{} problem. We will
construct a saturated matching~$M$ with weight $Q+\lambda$ as follows. Consider any
agent~$x_i$. If~$x_i$ is matched to~$y_j$ in round~$t$ in~$\mathcal{M}$,
then,~$\{x_i^t,y_j^t\}$ is added to~$M$. There are~$\gamma_i$ such edges.
Of the remaining~$|K_i|-\gamma_i$ copies of~$x_i$,~$|K_i|-\rho_i$ copies
are matched to type-3 resources. The remaining~$\rho_i-\gamma_i$ copies are
matched to type-2 resources in the following manner.
Let~$\overline{X}_i=\{x_i^{t_1},x_i^{t_2},\ldots,x_i^{t_{\rho_i-\gamma_i}}\}$
be the remaining copies ordered in an arbitrary manner. We will add the
edges~$\{x_i^{t_\ell},y^3_{i,\rho_i-\ell+1}\}$ to~$M$
for~$\ell=1,\ldots,\rho_i-\gamma_i$. Note that every~$x_i^t$,~$t\in K_i$ is
matched, and therefore, every node in~$X'$ is matched.
\smallskip
Now, we compute the total weight of~$M$.
Again, consider any agent $x_i$. Each edge corresponding to a type-3
node contributes weight~$k$, and there are~$|K_i|-\rho_i$ such edges for~$x_i$. Hence, the total contribution from type-3 resources
is~$k(|K_i|-\rho_i)$. There are~$\gamma_i$ edges corresponding to type-1
resources. Since each such edge has weight~$1$, it contributes~$\gamma_i$
to the sum. Finally, the edges corresponding to type-2 resources
contribute~$\sum_{\ell=1}^{\rho_i-\gamma_i}w(x_i^{t_\ell},y^2_{i,\rho_i-\ell+1})
= \sum_{\ell=1}^{\rho_i-\gamma_i}\big(1-\delta_i(\rho_i-\ell+1)\big)$.
Combining the terms corresponding to type-1 and type-2 resources,
the total weight of the edges in $M$ due to agent $x_i$ is
\(
\gamma_i +
\sum_{\ell=1}^{\rho_i-\gamma_i}\big(1-\delta_i(\rho_i-\ell+1)\big) =
\sum_{\ell=1}^{\gamma_i}1 +
\sum_{\ell=\gamma_i}^{\rho_i}\big(1-\delta_i(\ell)\big)
= \sum_{\ell=1}^{\rho_i}\big(1-\delta_i(\ell)\big) +
\sum_{\ell=1}^{\gamma_i}\delta_i(\ell)
\)\,.
Combining this over all the agents, the total
weight of the matching $M$ is given by~$\sum_{i=1}^nk(|K_i|-\rho_i) +
\sum_{i=1}^n\sum_{\ell=1}^{\rho_i}\big(1-\delta_i(\ell)\big) +
\sum_{i=1}^n\sum_{\ell=1}^{\gamma_i}\delta_i(\ell)=\lambda + Q$,
as stated in the lemma.
\end{proof}
\medskip
\subsection{Statement and Proof of Lemma~\ref{lem:opt-benefit-matching}}
\medskip
\noindent
\textbf{Statement of Lemma~\ref{lem:opt-benefit-matching}:}
There is an optimal solution to the MaxTB-MRM problem instance with benefit $Q^*$
if and only if there is a maximum weight saturated matching $M^*$
for $G'$ with weight $Q^* + \lambda$.
\begin{proof} Suppose there is an optimal solution to the \mbox{\textsc{MaxTB-MRM}}{}
instance with benefit $Q^*$. By
Lemma~\ref{lem:benefit-to-matching}, there is a saturated matching $M^*$
for $G'$ with weight $Q^* + \lambda$. Now, if $G'$ has a saturated
matching with weight $W'$ \emph{larger than} $Q^* + \lambda$, then by
Lemma~\ref{lem:matching-to-benefit}, we would have a solution to the
\mbox{\textsc{MaxTB-MRM}}{} problem with benefit $W'-\lambda > Q^*$. This contradicts the
assumption that $Q^*$ is the maximum benefit for the \mbox{\textsc{MaxTB-MRM}}{} instance.
In other words, $M^*$ is a maximum weight saturated matching for $G'$. The
other direction can be proven in similar way.
\end{proof}
\medskip
\subsection{Statement and Proof of Proposition~\ref{pro:time-algmaxtbmrm}}
\medskip
\textbf{Statement of Proposition~\ref{pro:time-algmaxtbmrm}:}~
Algorithm \mbox{\textsc{Alg-MaxTB-MRM}}{} runs in time
$O(k^{3/2} (n+|E|)\sqrt{n+m}))$, where $n$ is the
number of agents, $m$ is the number of resources,
$k$ is the number of rounds and $E$ is the number of
edges in the compatibility graph $G(X, Y, E)$.
\begin{proof} We first estimate the number of nodes and
edges in the bipartite graph $G'(X', Y', E')$
constructed in Step~1 of \mbox{\textsc{Alg-MaxTB-MRM}}{}.
For each agent, there are at most $k$ nodes in $X'$.
Thus, $|X'| \leq kn$.
For each resource, there are $k$ nodes corresponding to
type-1 resources.
Thus, the total number of type-1 resource nodes is $km$.
For each agent, the total number of type-2 and type-3 resource nodes is at most $2k$. Therefore, the total number of type-2 and type-3
resource nodes over all the agents is $2kn$.
Thus, $|Y'| \leq km+ 2kn$.
Thus, the number of nodes in $G'$ is at most $km+3kn$.
We now estimate $|E'|$.
For each edge $e \in E$, there are $k$ edges in $E'$
corresponding to edges incident on type-1 resources.
Thus, the number of edges of $G'$ incident on type-1 resource nodes
is at most $k|E|$.
As mentioned above, the total number of type-2 and type-3 nodes
for each agent is at most $2k$. Thus, the total number of edges
in $E'$ contributed by all agents to type-2 and type-3 resource nodes is at most $2kn$. Thus, $|E'| \leq k|E| + 2kn$.
It can be seen that the running time of the algorithm is dominated
by Step~2, which computes a maximum weighted matching in $G'$.
It is well known that for a bipartite graph with $p$ nodes and $q$
edges, a maximum weighted matching can be computed in
time $O(q\sqrt{p})$ \cite{CLRS-2009}.
Since $G'$ has at most $3kn+km$ nodes and at most
$k|E| + 2kn$ edges, the running time of \mbox{\textsc{Alg-MaxTB-MRM}}{}
is $O(k^{3/2} (|E|+n)\sqrt{n+m}))$.
\end{proof}
\medskip
\subsection{Statement and Proof of Theorem~\ref{thm:rawlsian}}
\medskip
\noindent
\textbf{Statement of Theorem~\ref{thm:rawlsian}:}~
There exists a benefit function $\mu_i$ for each agent $x_i$ such that maximizing the total benefit under this function
maximizes the Rawlsian social welfare function,
i.e., it maximizes the minimum
satisfaction ratio over all agents.
Further, this benefit function is valid
and therefore, an optimal solution to the \mbox{\textsc{MaxTB-MRM}}{}
problem under this benefit function can
be computed in polynomial time.
\smallskip
The benefit function mentioned in the above theorem was
defined in Section~\ref{sec:rmmrm_poly}.
For the reader's convenience, we have reproduced the
definition below.
\smallskip
\noindent
\begin{enumerate}[leftmargin=*]
\item Let~$F=\big\{k_1/k_2\mid k_1,k_2\in\{1,\ldots,k\} ~\mathrm{and}~ k_1 \leq k_2\big\}\cup\{0\}$.
\item Let~$\pi: F\rightarrow\{1,\ldots,|F|\}$ correspond to the index of
each element in~$F$ when sorted in descending order.
\item For each~$q\in F$, let $\xi(q)=(nk)^{\pi(q)}/(nk)^{|F|}$, where~$n$ is
the number of agents and~$k$ is the number of rounds. Note that
each~$\xi(q)\in(0,1]$.
\item The incremental benefit~$\delta_i(\ell)$ for an agent~$x_i$ for
the~$\ell$th matching is defined
as~$\delta_i(\ell)=\xi\big((\ell-1)/\rho_i\big)$.
Thus, the benefit function $\mu_i$ for agent $x_i$ is
given by $\mu_i(0) = 0$ and
$\mu_i(\ell) = \mu_i(\ell-1) + \delta_i(\ell)$ for
$1 \leq \ell \leq \rho_i$.
\end{enumerate}
It can be seen that $\mu_i$ satisfies
properties P1, P2 and P4 of a valid benefit
function. We now show that it also satisfies P3,
the diminishing returns property.
\begin{lemma}
For each agent~$x_i$, the incremental benefit~$\delta_i(\ell)$ is monotone
non-increasing in~$\ell$. Therefore,~$\mu_i(\cdot)$ satisfies
diminishing returns property.
\end{lemma}
\begin{proof}
By definition, for~$\ell=1,\ldots,\rho_i-1$,~$\delta_i(\ell)/\delta_i(\ell+1)=
\xi\big((\ell-1)/\rho_i\big)/\xi\big(\ell/\rho_i\big)\ge nk > 1$, by noting
that~$\pi(\ell/\rho_i)-\pi((\ell+1)/\rho_i)\ge1$. Hence, the lemma holds.
\end{proof}
To complete the proof of Theorem~\ref{thm:rawlsian},
we need to show that any solution that maximizes the benefit function defined above also maximizes
the minimum satisfaction ratio.
We start with some definitions and a lemma.
\smallskip
For an agent~$x_i$ and~$q\in F$, let~$F^>_i(q)=\{\ell\mid 0\le\ell\le\rho_i
\text{ and } \ell/\rho_i>q\}$. We will now show that the incremental
benefit~$\delta_i(\ell)$ obtained by agent~$x_i$ for matching~$\ell$ is
greater than the sum of all incremental benefits~$\delta_{i'}(\ell')$, for
all agents~$x_{i'}$, $i'\ne i$ and for all~$\ell'$
satisfying~$\ell'/\rho_{i'}>\ell/\rho_i$.
\begin{lemma}\label{lem:cost}
For any agent~$x_i$ and non-negative
integer~$\ell\le\rho_i$, we have ~$\delta_i(\ell)>\sum_{i'=i}\sum_{\ell'\in
F^>_{i'}(\ell/\rho_i)}\delta_{i'}(\ell')$.
\end{lemma}
\begin{proof}
For any~$\ell'\in F^>_{i'}(\ell/\rho_i)$, note that
$\ell/\rho_i<\ell'/\rho_{i'}$.
Hence,~$\pi(\ell/\rho_i)-\pi(\ell'/\rho_{i'})\ge1$. This implies
that~$\delta_i(\ell)/\delta_{i'}(\ell') =
\xi\big((\ell-1)/\rho_i\big)/\xi\big((\ell'-1)/\rho_{i'}\big)\ge nk$.
Since~$\rho_{i'}\le k$, the number of
$\delta_{i'}(\ell')$ terms
per~$i'$ is at most $k$.
Since there are at most~$n-1$ agents~$x_{i'}$,~$i'\ne i$,~ it
follows that there are at most~$(n-1)k$ terms~$\delta_{i'}(\ell')$ in total. Therefore,~$\sum_{i'=i}\sum_{\ell'\in
F^>_{i'}(\ell/\rho_i)}\frac{\delta_{i'}(\ell')}{\delta_{i}(\ell)}<1$.
\end{proof}
\smallskip
We are now ready to complete the proof of Theorem~\ref{thm:rawlsian}.
\medskip
\noindent
\textbf{Proof of Theorem~\ref{thm:rawlsian}.}
The proof is by contradiction. Suppose~$\mathcal{M}^*$ is an optimal solution
given the benefit function defined above. We will show that if there exists
a solution~$\mathcal{M}$ with minimum satisfaction ratio greater than that
of~$\mathcal{M}^*$, then the total
benefit~$\mathbb{B}(\mathcal{M})>\mathbb{B}(\mathcal{M}^*)$, contradicting the fact
that~$\mathcal{M}^*$ is an optimal solution. Let~$q(\mathcal{M}^*)$
and~$q(\mathcal{M})$ denote the minimum satisfaction ratio in~$\mathcal{M}^*$
and~$\mathcal{M}$.
For a given solution $\mathcal{M}$, we use $\gamma_i(\mathcal{M})$
to denote the number of rounds assigned to agent $x_i$,
$1 \leq i \leq n$.
We recall that the benefit function for~$\mathcal{M}$ can be written
as~$\mathbb{B}(\mathcal{M})=\sum_{i=1}^n\sum_{\ell=1}^{\gamma_i(\mathcal{M})}
\delta_i(\ell)$. For each~$i$, the~$\delta_i(\ell)$ terms can be
partitioned into three blocks as follows.
\begin{description}
\item{(i)} $D_1(\mathcal{M})=\{(i,\ell)\mid \forall
i,~\ell/\rho_i\le q(\mathcal{M}^*)\}$,
\item{(ii)} $D_2(\mathcal{M})=\{(i,\ell)\mid
\forall i,~q(\mathcal{M}^*)<\ell/\rho_i\le q(\mathcal{M})\}$, and
\item{(ii)} $D_3(\mathcal{M})=\{(i,\ell)\mid \forall i,~\ell>q(\mathcal{M})\}$.
\end{description}
\noindent
We can
partition the terms corresponding to~$\mathbb{B}(\mathcal{M}^*)$ in the same
way, and these blocks are denoted by~$D_1(\mathcal{M}^*)$, $D_2(\mathcal{M}^*)$ and $D_3(\mathcal{M}^*)$.
Since
every~$x_i$ has a satisfaction ratio of at least~$q(\mathcal{M}^*)$ in
both~$\mathcal{M}^*$ and~$\mathcal{M}$, all the terms with~$\ell/\rho_i\le
q(\mathcal{M}^*)$ will be present. Therefore,~$D_1(\mathcal{M}^*)=D_1(\mathcal{M})$.
\smallskip
In~$\mathcal{M}^*$, let~$x_{i'}$ be an agent for which the satisfaction ratio
is~$q(\mathcal{M}^*)$. There are no~$(i',\ell)$ terms in~$D_2(\mathcal{M}^*)$ while
for every agent~$x_i$, all~$(i,\ell)$ terms
satisfying~$q(\mathcal{M}^*)<\delta_i(\ell)\le q(\mathcal{M})$ are present
in~$D_2(\mathcal{M})$. Therefore,~$D_2(\mathcal{M}^*)\subset D_2(\mathcal{M})$. Now,
\begin{align*}
\mathbb{B}(\mathcal{M})-\mathbb{B}(\mathcal{M}^*) = &
\sum_{(i,\ell)\in D_2(\mathcal{M})}\delta_i(\ell) +
\sum_{(i,\ell)\in D_3(\mathcal{M})}\delta_i(\ell) -
\sum_{(i,\ell)\in D_2(\mathcal{M}^*)}\delta_i(\ell) -
\sum_{(i,\ell)\in D_3(\mathcal{M}^*)}\delta_i(\ell) \\
& >
\sum_{(i,\ell)\in D_2(\mathcal{M})}\delta_i(\ell) -
\sum_{(i,\ell)\in D_2(\mathcal{M}^*)}\delta_i(\ell) -
\sum_{(i,\ell)\in D_3(\mathcal{M}^*)}\delta_i(\ell) \\
\end{align*}
Now, let~$(i',\ell')=\argmin_{(i,\ell)\in D_2(\mathcal{M})\setminus
D_2(\mathcal{M}^*)} \ell/\rho_i$. Also, recalling that~$D_2(\mathcal{M}^*)\subset
D_2(\mathcal{M})$,
\begin{align*}
\mathbb{B}(\mathcal{M})-\mathbb{B}(\mathcal{M}^*) & >
\sum_{(i,\ell)\in D_2(\mathcal{M})}\delta_i(\ell) -
\sum_{(i,\ell)\in D_2(\mathcal{M}^*)}\delta_i(\ell) -
\sum_{(i,\ell)\in D_3(\mathcal{M}^*)}\delta_i(\ell) \\
& > \delta_{i'}(\ell') -
\sum_{(i,\ell)\in D_3(\mathcal{M}^*)}\delta_i(\ell) > 0\\
\end{align*}
where the inequality follows from Lemma~\ref{lem:cost}.
Thus, $\mathbb{B}(\mathcal{M})>\mathbb{B}(\mathcal{M}^*)$ and this
contradicts the optimality of $\mathcal{M}^*$.
The theorem follows.
\qed
\medskip
\subsection{Proof of the Complexity of \mbox{\textsc{MaxSA-MRM}}{}}
\medskip
\noindent
\textbf{Statement of Theorem~\ref{thm:max_sat_agents_npc}:}
The \mbox{\textsc{MaxSA-MRM}}{}{} problem is \textbf{NP}-hard even when
the number of rounds ($k$) is 3.
\medskip
\noindent
\textbf{Proof:}~
To prove \textbf{NP}-hardness, we use a reduction from the Minimum Vertex Cover
Problem for Cubic graphs, which we denote as \mbox{\textsc{MVC-Cubic}}{}.
A definition of this problem is as follows: given
an undirected graph $H(V_H, E_H)$ where the degree of each node is 3
and an integer $h \leq |V_H|$, is there a vertex cover of size at most $h$
for $H$ (i.e., a subset $V'_H \subseteq V_H$
such that $|V'_H| \leq h$, and for each edge $\{x,y\} \in E_H$, at least
one of $x$ and $y$ is in $V'_H$)?
It is known that \mbox{\textsc{MVC-Cubic}}{} is \textbf{NP}-complete \cite{GareyJohnson79}.
\medskip
Given an instance $I$ of \mbox{\textsc{MVC-Cubic}}{} consisting of graph $H(V_H, E_H)$
and integer $h \leq |V_H|$, we produce an instance $I'$ of \textsc{MS-MRM}{}
as follows.
\begin{enumerate}
\item For each node $v_i \in V_H$, we create an agent $x_i$,
called a \textbf{special agent}.
For each edge $e_j \in E_H$, we create
two agents $z_{j,1}$ and $z_{j,2}$, called \textbf{simple agents}.
Thus, the set $X$ of agents consists of $|V_H|$ special agents
and $2|E_H|$ simple agents for a total of $|V_H| + 2|E_H|$ agents.
\item For each edge $e_j \in E_H$, we create
a resource $y_j$.
Thus, the set $Y$ of resources has size $|E_H|$.
\item The edge set $E$ of the compatibility graph $G(X, Y, E)$
is constructed as follows.
For $a \in \{1,2\}$, each simple agent $z_{j,a}$ has an edge in $E$ only to
its corresponding resource $y_j$.
Further, for each edge $e_j = \{v_a, v_b\} \in E_H$,
$E$ has the two edges $\{x_a, y_j\}$ and $\{x_b, y_j\}$.
Since the degree of each node $v_i \in V_H$ is 3,
each special agent has exactly three compatible resources.
The edge set $E$ ensures that each resource is compatible
with exactly two simple agents and two special agents.
It follows that $|E| = 4|Y| = 4|E_H|$.
\item For each agent, the allowed set of rounds is $\{1, 2, 3\}$.
\item The requirement for each simple agent is 1 and
that for each special agent is 3.
\item The number $k$ of rounds is set to 3.
\item The parameter $Q$, the number of agents to
be satisfied, is given by $Q ~=~ (2|E_H| + |V_H| -h)$,
where $h$ is the bound on the size of a vertex cover for $H$.
\end{enumerate}
It can be seen that the above construction can be carried out
in polynomial time.
We now show that the resulting instance $I'$ of \textsc{MS-MRM}{}
has a solution iff the \mbox{\textsc{MVC-Cubic}}{} instance $I$ has a solution.
\smallskip
Suppose the \mbox{\textsc{MVC-Cubic}}{} instance $I$ has a solution.
Let $V'_H$ denote a vertex cover of size $h$ for $H$.
We construct a solution for the instance $I'$ of \textsc{MS-MRM}{}
consisting of three matchings $M_1$, $M_2$ and $M_3$
as follows.
Initially, these matchings are empty.
Let $X' \subseteq X$ consist of all the simple agents and
those special agents corresponding to the nodes of $H$ in $V_H - V'_H$.
(Thus, the special agents in $X'$ correspond to the nodes of $H$
which are \emph{not} in $V'_H$.)
First, consider each special agent $x_i \in X'$.
Let the three resources that are compatible with $x_i$ be denoted
by $y_a$, $y_b$ and $y_c$ respectively.
We add the edges $\{x_i, y_a\}$, $\{x_i, y_b\}$, and
$\{x_i, y_c\}$ to $M_1$, $M_2$ and $M_3$ respectively.
Since $V'_H$ is a vertex cover, each resource is used in
one of the three rounds by a special agent.
Thus, each of the two simple agents $z_{j,1}$ and $z_{j,2}$
for each resource $y_j$ can be matched in the two remaining
rounds. (For example, if agent $x_i$ is matched to $y_j$ in $M_1$,
$z_{j,1}$ and $z_{j,2}$ can be matched to $y_j$ in $M_2$ and $M_3$
respectively.)
Thus, in this solution, the only unsatisfied agents are the
$h$ special agents corresponding to the nodes in $V'_H$.
In other words, at least $2|E_H| + |V_H| -h$ agents are satisfied.
\smallskip
For the converse, suppose there is a solution to the \textsc{MS-MRM}{}
instance $I'$ that satisfies at least
$2|E_H| + |V_H| -h$ agents.
Let $X'$ denote the set of satisfied agents in this solution.
We have the following claim.
\smallskip
\noindent
\textbf{Claim 1:}~
$X'$ can be modified without changing its
size so that it includes \emph{all} the simple agents.
\smallskip
\noindent
\textbf{Proof of Claim 1:}~
Suppose a simple agent $z_{j,a}$ for some $a \in \{1,2\}$
is not in $X'$ (i.e., $z_{j,a}$ is not a satisfied agent).
By our construction, $z_{j,a}$ is only compatible with resource $y_j$.
Since $y_j$ is compatible with two simple agents and two special agents,
the current solution must assign at least one special agent,
say $x_w$, to $y_j$ in one of the matchings.
In that matching, we can replace $x_w$ by $z_{j,a}$ so that $z_{j,a}$
becomes a satisfied agent and $x_w$ becomes an unsatisfied agent.
This change corresponds to adding $z_{j,a}$ to $X'$ and
deleting $x_w$ from $X'$. Thus, this change does \emph{not}
change $|X'|$. By repeating this process, we ensure that $X'$ contains
only special agents and $|X'| ~\geq~ 2|E_H| + |V_H| -h$.
\smallskip
We now continue the main proof.
From the above discussion, all the unsatisfied agents, that is, the agents
in $X - X'$, are special agents and their number is at most $h$.
Let $V'_H$ denote the nodes of $H$ that correspond to the
agents in $X-X'$.
To see that $V'_H$ forms a vertex cover for $H$, consider
any edge $e_j = \{v_a, v_b\}$ of $H$.
We show that $V'_H$ contains at least one of $v_a$ and $v_b$.
There are four agents compatible with the resource $y_j$
that corresponds to $e_j$.
Two of these are simple agents and the other two are special agents.
However, the number of rounds is 3.
Therefore, there is at least one unsatisfied agent that is
compatible with $y_j$.
By Claim~1, such an unsatisfied agent is a special agent.
The only special agents that are compatible with $y_j$ are
$x_a$ and $x_b$. Thus, at least of one these agents
appears in $X-X'$.
By our construction of $V'_H$, at least one of $v_a$ and $v_b$
appears in $V'_H$. Further, $|V'| \leq h$.
Thus, $V'_H$ is a solution to the \mbox{\textsc{MVC-Cubic}}{} instance $I'$.
This completes our proof of Theorem~\ref{thm:max_sat_agents_npc}. \hfill$\Box$
\section{Additional Material for Section~\ref{sec:algmsagmrm}}
\label{sup:sec:algmsagmrm}
\medskip
\subsection{Proof of the Complexity of \textsc{AG-MRM}{}}
\medskip
\paragraph{Statement of Theorem~\ref{thm:hardness}.}
The \textsc{AG-MRM}{} problem is NP-hard when there is just one
agent~$x_i$ for which~$\rho_i > 1$.
\medskip
\noindent
\textbf{Proof.}~ We use a reduction from the
Minimum Set Cover (MSC) problem which is known to
be \textbf{NP}-complete~\cite{GareyJohnson79}.
Consider an instance of MSC
with~$U=\{z_1,z_2,\ldots, z_t\}$,~$\mathcal{Z}=\{A_1,A_2,\ldots, A_q\}$, and an
integer~$\alpha\le|\mathcal{Z}|$. We will construct an instance of \textsc{AG-MRM}{}{}
as follows. Let~$t =|U|$.
Let degree of an element~$z\in U$,
denoted by~$\deg(z)$, be the number of sets
in~$\mathcal{Z}$ which contain $z$.
For each~$z_j\in U$, we
create~$a=\deg(z_j)$ resources~$\rset_j=\{y_j^h\mid z_j\in A_h\}$. Thus,
the resource set is~$\rset = \bigcup_{z_j\in U}\rset_j$. For each~$\rset_j$,
we create a set of agents~$\agset_j = \{x_j^1,x_j^2,\ldots\}$,
where~$|\agset_j| = t\cdot\deg(z_j)-1$. For each~$z_j\in U$, we have an
edge for every~$x\in \agset_j$ and~$y\in \rset_j$. Finally, we add a
special agent~$x^*$ with edges to all resources. The set of agents
is~$\agset=\bigcup_{z_j\in U}\agset_j\cup\{x^*\}$. For each~$x\ne x^*$,
there are no labels on the edges that are incident on $x$. For each
edge~$\{x^*,y_j^h\}$, we assign a single label~$c_h$. Each label has
cost~$1$. This completes the construction of~$G_R$. For~$x^*$, the budget
$\beta^*=\alpha$, which is the budget for the MSC instance. For the
rest of the agents, the budget is~$0$. The number of repetitions
for~$x^*$,~$\rho^*=t$ and for the rest of the vertices~$x_i\ne
x^*$,~$\rho_i=1$. This completes the construction of the \textsc{AG-MRM}{} instance,
and it can be seen that the construction can be done in polynomial time.
Now, we show that a solution exists for the MSC
instance iff a solution exists for the resulting \textsc{AG-MRM}{} instance.
\smallskip
Suppose that there exists a solution to the \textsc{AG-MRM}{} instance. By our
construction, since~$t\cdot\deg(z_j)-1$ agents in~$\agset_j$ are all
adjacent to the same set of~$\deg(z_j)$ resources, it follows that~$x^*$
can be matched to at most one resource in~$\rset_j$ in the~$k$ rounds.
The solution to the~$\textsc{AG-MRM}{}$ instance matches~$x^*$ to~$t$
resources, one in each matching. Thus, $x^*$ is adjacent to
some~$y_j^h\in\rset_j$ for all~$j$.
This means that the
collection~$\mathcal{Z}'=\{A_h\mid y_j^h\in\rset_j \text { and } x^*\text{
compatible with } y_j^h\}$ covers all the elements in $U$.
Further, since at most~$\alpha$ labels were removed, it follows that~$|\mathcal{Z}'|=\alpha$. In other words, we have a solution to the
MSC instance.
\smallskip
Let~$\mathcal{Z}'$ be a solution to the MSC instance. We can construct a
solution with~$k$ matchings for the \textsc{AG-MRM}{} instance as follows. First,
we remove restrictions~$c_h$ $\forall A_h\in \mathcal{Z}'$. Since~$\mathcal{Z}'$
covers~$U$, for every~$\rset_j$, there exists a resource~$y_j^h$ such
that~$A_h\in \mathcal{Z}'$ and therefore,~$x^*$ is compatible with~$y_j^h$. We
choose exactly one such resource from each~$\rset_j$. Let this chosen set
of resource be denoted by~$\rset'$. Since~$t=|U|$ matchings are required
and~$|\rset'|=t$, we can choose a distinct~$y\in \rset'$ to match~$x^*$.
This means that each resource in~$Y_j\setminus\rset'$ is available to be
matched to an agent in~$t$ rounds while the resource~$y\in \rset_j\cap\rset'$
can be matched in~$t-1$ rounds. Since there are exactly~$t\cdot\deg(z_j)-1$
resources in~$\agset_j$, each of them can be matched in one of the~$t$
rounds. Hence, we have a solution to the \textsc{AG-MRM}{} instance and this completes our proof
of \textbf{NP}-hardness. \qed
\medskip
\subsection{An ILP Formulation for \mbox{\textsc{AG-MaxSA-MRM}}{}}
\medskip
\begin{table}[htbp]
\begin{center}
\begin{tabular}{|c|p{4.5in}|}\hline
\textbf{Symbol} & \textbf{Explanation}\\ \hline\hline
\agset{} & Set of $n$ agents; \agset{} = $\{x_1, x_2, \ldots, x_n\}$ \\ \hline
\rset{} & Set of $m$ resources; \rset{} = $\{y_1, y_2, \ldots, y_m\}$ \\ \hline
$\mbox{$\mathcal{C}$}_i$ & Set of labels $\{c_i^1, c_i^2, \ldots, c_i^{\ell_i}\}$
of associated with agent $x_i$, $1 \leq i \leq n$.
(Thus, $\ell_i = |\mbox{$\mathcal{C}$}_i|$.)
\\ \hline
$\psi_i^t$ & Cost of removing the label $c_i^t$, $1 \leq t \leq \ell_i$ and
$1 \leq i \leq n$. \\ \hline
$\beta_i$ & Cost budget for agent $x_i$, $1 \leq i \leq n$.
(This is the total cost agent $x_i$ may spend
on removing labels.)
\\ \hline
$\rho_i$ & The desired number of rounds requested by an
agent. \\ \hline
$\Gamma_e$ & Set of labels appearing on edge $e$. (If an edge $e$ joins
agent $x_i$ to resource $y_j$, then $\Gamma_e \subseteq \mbox{$\mathcal{C}$}_i$.)
Edge $e$ can be added to the compatibility graph only
after \emph{all} the labels in $\Gamma_e$ are removed.
\\ \hline
$k$ & Upper bound on the number of rounds of matching \\ \hline
\end{tabular}
\end{center}
\caption{Notation Used in the Definition of \mbox{\textsc{AG-MaxSA-MRM}}{}{}{}{}
and its ILP Formulation}
\label{tab:notation}
\end{table}
We now provide an ILP formulation for the \mbox{\textsc{AG-MaxSA-MRM}}{} problem.
Recall that the goal of this problem is to generate advice to agents
(i.e., relaxation of restrictions) subject to budget constraints
so that there is $k$-round matching that satisfies the maximum
number of agents.
For an agent $x_i$ and resource $y_j$,
if the edge $e
= \{x_i, y_j\}$ does \emph{not} appear in the restricted graph, it is
assumed the cost of removing the labels associated with that edge is larger than agent $x_i$'s budget.
This will ensure that the edge won't appear in the compatibility graph.
The reader may want to consult
Table~\ref{tab:notation} for the notation used in this
ILP formulation.
\medskip
\noindent
\textbf{\ilpagmaxsamrm{}:}
\medskip
\noindent
\textbf{Note:}~ This ILP is also referred to as
\textsc{ILP-MaxSA-AG-MRM}.
\medskip
\noindent
\underline{\textsf{Variables:}}
Throughout this discussion, unless specified otherwise,
we use $\forall i$, $\forall j$ and $\forall r$~ to
mean ~$1\le i\le n$, $1\le j\le
m$, and $1\le r\le k$ respectively.
\begin{itemize}[leftmargin=*,noitemsep,topsep=0pt]
\item For each label $c_i^t$, a \{0,1\}-valued variable $w_i^t$,
$1 \leq t \leq \ell_i$ such that
$w_i^t$ is 1 iff label $c_i^t$
is removed.
\item For each agent $x_i$ and resource $y_j$,
a \{0,1\}-valued variable~$z_{ij}$ such that
$z_{ij}$ is 1 iff the edge $\{x_i, y_j\}$
appears in the compatibility graph (after removing labels).
\item
For each agent $x_i$,
and each resource $y_j \in \rset$,
we have $k$ \{0,1\}-variables
denoted by $a_{ijr}$.
The interpretation is that $a_{ijr}$ is 1 iff edge $\{x_i, y_j\}$
is in the compatibility graph and agent $x_i$ is matched
to resource $y_j$ in round $r$.
\item
For each agent $x_i$, we have an integer
variable $\eta_i$
that gives the number of rounds in which $x_i$ is matched.
\item
For each agent $x_i$, we have a \{0,1\}-variable $s_i$
that is 1 iff agent $x_i$'s requirement
(i.e., $\eta_i \geq \rho_i$) is satisfied.
\end{itemize}
\medskip
\noindent
\underline{\textsf{Objective:}}~
Maximize $\sum_{i=1}^{n} s_i$.
\medskip
\noindent
\underline{\textsf{Constraints:}}
\begin{itemize}
\item For each agent $x_i$, the cost of removing the labels from $\mbox{$\mathcal{C}$}_i$
must satisfy the budget constraint:
\(\forall i~
\sum_{t=1}^{\ell_i} \psi_i^t\,w_i^t ~\leq~ \beta_i\,.
\)
\item The edge $e = \{x_i, y_j\}$ appears in the graph only if
\emph{all} the labels in $\Gamma_e$ are removed.
\begin{align*}
z_{ij} \leq~& w_i^t ~~ \mathrm{for~each~} c_i^t \in \Gamma_e \\
z_{ij} \geq~& \bigg[\sum_{c_i^t \in \Gamma_e} w_i^t\bigg] - (|\Gamma_e| -1)
\end{align*}
The first constraint ensures that if any of the labels on the edge
$\{x_i, y_j\}$ is not removed, edge $\{x_i, y_j\}$ won't be added
to the compatibility graph.
The second constraint ensures that if all of the labels on the edge
$\{x_i, y_j\}$ are removed, edge $\{x_i, y_j\}$ \emph{must be} added
to the compatibility graph.
These constraints are for $\forall i$ and $\forall j$.
\item If an edge $\{x_i, y_j\}$ does not have any labels on it,
then it is included in the compatibility graph:
\(
z_{ij} ~=~1 ~~ \mathrm{for~each~} e =\{x_i,y_j\} ~\mathrm{with}~ \Gamma_e = \emptyset{}.
\) This constraint is for $\forall i$ and $\forall j$.
\item If edge $\{x_i, y_j\}$ is not in the compatibility graph,
each variable $a_{ijr}$
must be set to 0:
\(
a_{ijr} ~\leq~ z_{ij},~ \forall i,~ \forall j,~ \forall k.
\)
\item
For each agent $x_i$, the number of rounds in which $x_i$
is matched should be equal to $\eta_i$:
\(
\eta_i = \sum_{r=1}^{k}\, \sum_{j=1}^{m} a_{ijr},~ \forall i~
\)
\item Each agent $x_i$ is matched to a resource \emph{at most once}
in each round:
\(
\sum_{j = 1}^m\: a_{ijr} ~\leq~ 1,~ \forall i,~ \forall r.
\)
\item For each resource $y_j$,
in each round, $y_j$ must be matched to an agent
\emph{at most} once:
\(
\sum_{i = 1}^{n} a_{ijr} ~\leq~ 1,~ \forall j,~ \forall r.
\)
\item The rounds in which an agent $x_i$ is matched
must be in $K_i$:
\(
a_{ijr} ~=~ 0, ~~ r \not\in K_i,~ \forall i,~ \forall j.
\)
\item
Variable $s_i$ should be 1
iff agent $x_i$ was matched
in at least $\rho_i$ rounds. The following constraints,
which must hold $\forall i$, ensure this
condition.
\begin{align}\label{eqn:s-i-ineq}
\eta_i - \rho_i + 1 \le k\,s_i \le \eta_i - \rho_i + k
\end{align}
\item $w_i^t \in \{0,1\}$, $z_{ij} \in \{0,1\}$, $a_{ijr} \in \{0,1\}$,
$\eta_i$ is a non-negative integer, and $s_i \in \{0,1\}$.
\end{itemize}
\medskip
\smallskip
\noindent
\underline{\textsf{Obtaining a Solution from the ILP:}}~
For each variable $w_i^t$ set to 1, the corresponding
label $c_i^t$ is removed.
These variables can be used to get the set of all labels
each agent must remove; this is the advice that is given to
each agent.
For each variable $a_{ijr}$ which is set to 1 in the
solution, we match agent $x_i$ with resource $y_j$ in round $r$.
\section{Additional Material for Section~\ref{sec:experiments}}
\label{sup:sec:experiments}
\medskip
\subsection{Additional Classroom Example with Restrictions}
\label{app_sec:addl_example}
\begin{figure}[hbt]
\rule{\columnwidth}{0.01in}
\centering
\includegraphics[width=.5\columnwidth]{figures/example2.pdf}
\caption{An example of the $\textsc{AG-MRM}$ problem.\label{fig:example2}}
\rule{\columnwidth}{0.01in}
\end{figure}
\medskip
\paragraph{A course-classroom example.} This example is motivated by the classroom
assignment application considered in this work. See
Figure~\ref{fig:example2}. Suppose there are agents (cohorts) who need to
be assigned to classrooms on three days ($k=3$) at some specific time such
that each agent is assigned a room at least twice ($\forall i,\,\rho_i=2$).
There are three classrooms. Each agent has preferences regarding the
minimum seating capacity of the room, its location, and the rounds in which
it would like to be matched. For example, agent~$x_1$ requires the room to
have a capacity (i.e., space) of~$\ge30$, prefers a room in
location~$\ell_1$ over one in~$\ell_2$, and does not want a room
in~$\ell_3$ (a hard constraint). Also, it wants to be matched in rounds~$1$
and~$2$. Resource~$y_1$ has capacity~$10$ and is situated in
location~$\ell_1$. The restrictions graph based on agent preferences and
resource properties is constructed as follows. To minimize the number of
labels, we will assume that each agent can relax its capacity constraint
only in steps of~$10$. For~$x_1$ to be compatible with~$y_1$, it must
relax its capacity requirement from~$30$ to~$10$. To represent this, we
introduce two labels~$s_1^{30}$ and~$s_1^{20}$ on the edge between~$x_1$
and~$y_1$. Removing $s_1^{30}$ implies that~$x_1$ has relaxed its capacity
restriction from~$30$ to~$20$. If a resource is situated in location
$\ell_j$, then labels corresponding to all locations above~$\ell_j$ in the
agent's preference order are assigned to the edge. For example, the edge
between~$x_2$ and~$y_3$ has labels~$\ell_2^2$ and~$\ell_2^1$ as~$y_3$
belongs to region~$\ell_3$, which is its least preferred location. The
restriction graph for this problem is shown in the middle panel of
Figure~\ref{fig:example2}. A solution to $\textsc{AG-MRM}$ in the bottom panels
of the figure.
\subsection{Generation of restrictions graphs}
\medskip
In the real-world datasets, the agent restrictions are mostly induced by
the properties of resources (room size, WiFi connectivity, location, etc.).
Three different types of restrictions are considered: binary attributes
such as yes/no and present/absent; ordinal attributes such as preferences;
and quantitative attributes. The example in Section~\ref{sec:definitions}
has binary attributes. We discretize quantitative attributes like capacity
by generating labels in steps of some fixed value. Suppose an agent~$x$
prefers a resource~$y$ of capacity~5, but~$y$ has capacity~3, then, we add
labels~$\ell_5$ and~$\ell_4$ to the restrictions set of edge~$\{x,y\}$. To relax the capacity constraint and allow an agent to be matched to a
resource of capacity~3, the two labels $\ell_3$ and $\ell_4$ must be
removed. For ordinal attributes we use the following method: suppose~$x$
has the following preference order~$a>b>c$ for some attribute values~$a$, $b$,
and $c$ and~$y$ has attribute~$b$, we add restrictions~$\ell_a$ to the
restrictions set of edge~$\{x,y\}$. Relaxing the restriction to
accommodate~$b$ corresponds to removing~$\ell_a$.
For both
real-world datasets, each round corresponds to a day. The cost is assigned
as follows: for binary attributes, the cost is~1, while for quantitative
and ordinal attributes, the cost on a label depends on the distance from
the preferred value: in the above example, the cost~$\ell_5$ is~1 while the
cost of~$\ell_4$ is~2. The same applies to ordinal attributes.
\medskip
\subsection{An Additional Figure for the Lab-Space dataset}
\medskip
As in Figure~\ref{fig:ls_total}(d), Figure~\ref{fig:ag2students} shows that there is a sharp increase in the number of agents satisfied for a
budget of~4. Figure~\ref{fig:ag2students} also implies that the performance of
\textsc{PS-Max-AG-MRM}{} is close to that of optimum (given by \ilpagmaxsamrm{}). Finally, when budget is high, the fraction of agents satisfied in the latter is reaching $100\%$ while in the former it is at most ~$90\%$.
\begin{figure}
\centering
\includegraphics[width=.48\columnwidth]{figures/fig_num_shared_20.pdf}
\caption{\mbox{\emph{Lab-Space}}{} experiment results: Evaluation
of the advice generation algorithm for increasing budget when each big room may contain up to two students.
\label{fig:ag2students}
}
\end{figure}
\medskip
\subsection{An Additional Figure for the Course-Classroom dataset}
\medskip
In Figure~\ref{fig:prbresources} we
demonstrate how critical the current set of resources is for having a satisfactory solution for the ~\mbox{\emph{Course-Classroom}}{} application.
We withheld only a portion of the resources (by sampling)
to satisfy the agents' preferences. The motivation behind this is that some of the university's classrooms are to be dynamically allocated for some conferences and other events during the year, and the
\mbox{\textsc{Principal}}{} needs to decide in advance what capacity to keep free for such events.
The graph shows that with 80\% of the resources, it is possible to achieve an average assignment ratio of about ~$0.8$.
\begin{figure}
\centering
\includegraphics[width=.48\columnwidth]{figures/ClsPrb2.pdf}
\caption{\mbox{\emph{Course-Classroom}}{} results. Average assignment ratio when
the number of resources is restricted.
\label{fig:prbresources}
}
\end{figure}
\medskip
\subsection{Additional Figures for Synthetic Graphs}
\medskip
To analyze the performance of the algorithms with respect to size of the
network, we consider complete bipartite graphs where the number of
agents~$n$ and resources~$m$ are the same. The number of agents (same as
resources) is varied from~50 to~200. There are~10 restrictions per agent
assigned costs randomly between~1 and~4. For each edge, we randomly assign
a restrictions subset of size at most five. For each agent~$x_i$, the
number of rounds~$\rho_i$ is chosen randomly between~$1$ and~$5$.
To generate~$K_i$,~$\rho_i$ rounds are sampled uniformly followed by choosing
the remaining rounds with probability~$0.5$.
The results in
Figure~\ref{fig:synth} show the performance of \textsc{PS-Max-AG-MRM}{} with
respect to \ilpagmaxsamrm{} in terms of solution quality and computation
time. We note that not only is the solution obtained using the
\textsc{PS-Max-AG-MRM}{} close to the ILP-based algorithm, but it is also orders of magnitude faster.
\begin{figure}
\centering
\includegraphics[width=.48\columnwidth]{figures/synth_budget.pdf}
\includegraphics[width=.48\columnwidth]{figures/synth_time.pdf}
\caption{Results for synthetic graphs: Solution quality and computation
time.
\label{fig:synth}
}
\end{figure}
\medskip
\subsection{Implementation Details}
\medskip
All the software modules used to implement our algorithms and heuristics
were written in Python 3.9. Graphs were generated and graph algorithms
were implemented using the Networkx package \cite{hagberg2008exploring}.
For local search, we used the simulated annealing implementation by Simple
AI \cite{simpleai}. We use “state” to be a set of relaxations per agent
(only the relevant ones as described). Energy is the number of agents
satisfied or the number of successful matchings, depends on the specific
problem. We use the geometric schedule\footnote{Kirkpatrick, Scott, C.
Daniel Gelatt, and Mario P. Vecchi. ``Optimization by simulated
annealing.'' Science 220.4598 (1983): 671-680.}. By trial and error, we
found the best setting of T1 to be 0.99 and T0 to be 100. If the
temperature decreased beyond 0.01, we set it to be 0.01. We stopped after
1000 iterations, moved back to the best solution if there was no
improvement in 40 iterations and returned the best found solution. We used
Gurobi Optimizer~\cite{gurobi} for solving the Integer Linear Problems.
The advice generation experiments were performed on a Linux machine equipped with two Intel
2.0 GHz Xeon Gold 6138 CPU processors (40 cores and 80 threads in total)
and 192 GB of memory. The other experiments, which required fewer resources, were performed using the 'Google Colab' platform.
In all places where random numbers were generated, we used the default seeds provided by python 3.9 and the Linux operating system we used.
\section{A General Result on Maximizing Utilitarian Welfare}
\label{sup:sec:gen_util_theorem}
\medskip
\begin{theorem}
\label{thm:total}
Suppose the benefit function $\mu_i$ of each agent $x_i$
is valid and strictly monotone
increasing in the number of rounds.
Any solution that maximizes the total benefit
corresponding to these benefit functions also maximizes
the utilitarian welfare, i.e., it maximizes the total number of rounds assigned to the agents.
\end{theorem}
\noindent
\textbf{Proof:}~
The proof is by contradiction. Suppose~$\mathcal{M}^*$ is a solution
that provides the maximum benefit when each
benefit function satisfies the properties
mentioned in the theorem. We will show that if there exists
a solution~$\mathcal{M}$ with number of total assignments greater than that
of~$\mathcal{M}^*$, then, that solution can be modified to a solution~$\mathcal{M}'$ with benefit~$\mathbb{B}(\mathcal{M}')>\mathbb{B}(\mathcal{M}^*)$, contradicting the fact
that~$\mathcal{M}^*$ is an optimal solution.
For each agent $x_i$, Let $\gamma_i(\mathcal{M})$ be the number of matchings
in which $x_i$ participates in $\mathcal{M}$.
\paragraph{Steps for creating $\mathcal{M}'$ given $\mathcal{M}$ and
$\mathcal{M}^*$.}
\begin{itemize}
\item Let~$t=0$ and initialize $\mathcal{M}'_t=\mathcal{M}$.
\item while$\big(\exists x_i$ for which $\gamma_i(\mathcal{M}^*)>
\gamma_i(\mathcal{M}'_t) \big)$:
\begin{itemize}
\item Let~$\mathcal{M}'_{t+1}=\mathcal{M}'_t$
\item pick $\gamma_i(\mathcal{M}^*)-\gamma_i(\mathcal{M}_t')$ rounds in
which $x_i$ participates in $\mathcal{M}^*$ but not in $\mathcal{M}_t'$.
\item In each round, match $x_i$ to the
same resource it was matched to in $\mathcal{M}^*$. If that resource is
already matched to another agent in $\mathcal{M}_t'$, then replace that
corresponding edge with the new edge.
\item $t\leftarrow t+1$
\end{itemize}
\item return $\mathcal{M}'=\mathcal{M}'_t$.
\end{itemize}
\begin{lemma}
In each iteration of the algorithm, the total number of rounds assigned to all agents does
not decrease, i.e., the total number of rounds in~$\mathcal{M}'_t$ is at least as large as that in~$\mathcal{M}'_{t-1}$.
\end{lemma}
\begin{proof}
In the construction of~$\mathcal{M}'_t$, for every edge added, at most one
edge is removed from~$\mathcal{M}'_{t-1}$.
\end{proof}
\begin{lemma}
The algorithm for creating $\mathcal{M}'$ terminates.
\end{lemma}
\begin{proof}
First, in each iteration, the algorithm adds at least one edge from $\mathcal{M}^*$ to $\mathcal{M}'$.
Second, once an edge is added it will never be removed since each edge that is added belong to one of the matchings in $\mathcal{M}^*$.
\end{proof}
\begin{lemma}
For all benefit functions that fulfil the conditions of the theorem,
$\mathbb{B}(\mathcal{M}')>\mathbb{B}(\mathcal{M}^*)$.
\end{lemma}
\begin{proof}
As before, we use $\gamma_i(\mathcal{M})$ to denote the number of
rounds assigned to $x_i$ in solution $\mathcal{M}$.
Note that for each $i$, $\gamma_i(\mathcal{M}') > \gamma_i(\mathcal{M}^*)$.
By the contradiction assumption, the number of assignments in $\mathcal{M}$ is grater than that of $\mathcal{M}^*$ and therefore initially in $\mathcal{M}'$.
During the construction, the number of assignments does not decrease and therefore there exists at least one $i$ for which
$\gamma_i(\mathcal{M}') > \gamma_i(\mathcal{M}^*)$.
Since the benefit function, $\mu_i$ is increasing for all $i$, it follows that $\mathbb{B}(\mathcal{M}')>\mathbb{B}(\mathcal{M}^*)$.
\end{proof}
The last lemma above shows that $\mathbb{B}(\mathcal{M}')>\mathbb{B}(\mathcal{M}^*)$.
This contradicts the optimality of $\mathcal{M}^*$ and
the theorem follows. \hfill$\Box$
\subsection{Maximize Minimum allocation}
\begin{enumerate}[leftmargin=*]
\item $Q=\{k_1/k_2 ~|~,k_1\in[0..k],k_2\in[1..k],k_1\leq k_2\}$
\item $Q = unique(reverse(sorted(Q)))$
\item $ord: Q -> N$ is a function that returns for each item in $Q$ its position in $Q$.
\item $\xi: Q\rightarrow N$, $\xi(j)=(k\cdot n)^{ord(j)}$
\item $\xi_{max}=max_{q\in Q}(\xi(q))$
\item $\xi^*:Q\rightarrow [0,1],\forall{q\in Q}, \xi^*(q)=\xi(q)/\xi_{max}$.
\item $\mu_i: [1,2,..\rho_i]\rightarrow R$, $\mu_i(l)=\sum_{o=0}^{l-1}\xi^*(o/rho_i)$ if $l>0$ else $0$
\end{enumerate}
\begin{lemma}
$\forall{i}, \mu_i(\cdot)$ satisfies diminishing returns property
\end{lemma}
\begin{proof}
We show that $\mu_i(h)-\mu_i(h-1) \leq \mu_i(h-1)-\mu_i(h-2)$.\\
\\
\noindent
\textbf{Case 1}: $h\geq3$:\\
Following definition:
$\mu_i(h)=\sum_{l=1}^{h-1}\xi^*(l/\rho_i)$,
$\mu_i(h-1)=\sum_{l=1}^{h-2}\xi^*(l/\rho_i)$,
$\mu_i(h-2)=\sum_{l=1}^{h-3}\xi^*(l/\rho_i)$.\\
Therefore, $\mu_i(h)-\mu_i(h-1)=\xi^*({h-1}/\rho_i)$ and similarly $\mu_i(h-1)-\mu_i(h-2)=\xi^*({h-2}/\rho_i)$.
Since $(h-2)/\rho_i<(h-1)/\rho_i$, $ord(h-2/\rho_i)>ord(h-1/\rho_i)$
and also $\xi(h-2/\rho_i)=((k)\cdot n)^{ord(h-2/\rho_i)} >\xi(h-1/\rho_i)=((k)\cdot n)^{ord(h-1/\rho_i)}$. Finally, $\xi(h-2/\rho_i)>\xi(h-1/\rho_i) \rightarrow \xi^*((h-2)/\rho_i)>\xi^*(h-1/\rho_i)$ and we are done.\\
\\
\noindent
\textbf{Case 2}: $h=2$:\\
Following definition:
$\mu_i(h)=\sum_{l=1}^{h-1}\xi^*(l/\rho_i)$,
$\mu_i(h-1)=\sum_{l=1}^{h-2}\xi^*(l/\rho_i)$,
$\mu_i(h-2)=((k)\cdot n)^{k^2}$\\
Therefore, $\mu_i(h)-\mu_i(h-1)=\xi^*({1}/\rho_i)$.
Regarding the right side, $\mu_i(h-1)-\mu_i(h-2)= \mu_i(1)-\mu_i(0) = \xi^*({0}/\rho_i)$.
And we continue similar to case 1.
\end{proof}
\begin{lemma}
$\forall{i},\forall{ h\in[1..k]}, 0 \leq \mu_i(h)-\mu_i(h-1) \leq 1$
\end{lemma}
\begin{proof}
Follows directly from the normalization in line 4
\end{proof}
\begin{theorem}
(weak version)
Given a multi-round solution~$\mathcal{M}$ that maximizes $\mathbb{B}(\mathcal{M})=\sum_{i=1}^n\mu_i(\ell_i)$, $\mathcal{M}$ also maximizes
$min_{x_i, 1\leq i \leq n}\ell_i/\rho_i$.
\end{theorem}
Proof:
Let $x_o=min_{x_i, 1\leq i \leq n}\ell_i/\rho_i$.
For each agent $x_i, 1\leq i \leq n$, ${{\ell_o}_i}=\min \{\ell_i,\min \{j~|~ j/\rho_i> \ell_o/\rho_o\}$.
Let $C_1=\sum_{i=1}^n\mu_i({\ell_o}_i)$ and let $C_2=\sum_{i=1}^n\mu_i(\ell_i)-\mu_i({\ell_o}_i)$. We note that $C_1+C_2 =\sum_{i=1}^n\mu_i({\ell_o}_i) + \sum_{i=1}^n\mu_i(\ell_i)-\mu_i({\ell_o}_i)= \sum_{i=1}^n\mu_i(\ell_i)=\mathbb{B}(\mathcal{M})$.
Assume by negation that $\mathcal{M}$ maximizes $\sum_{i=1}^n\mu_i(\ell_i)$ but not $min_{x_i, 1\leq i \leq n}\ell_i/\rho_i$.
Let $\mathcal{M}'$ be a multi-round solution that maximizes $min_{x_i, 1\leq i \leq n}\ell'_i/\rho_i$ where for each agent $x_i, 1\leq i \leq n$, $l'_i$ is the number of rounds assigned to $x_i$ in $\mathcal{M}'$.
We first define $C_1',C_2'$ as they were defined for $\mathcal{M}$.
We show that $\mathbb{B}(\mathcal{M}')>\mathbb{B}(\mathcal{M})$, contradicting the assumption that $\mathcal{M}$ maximizes $\mathbb{B}(\cdot)$.
First, $\delta_o(\ell_o+1)=\xi^*(\ell_o/\rho_o)$ (by definition).
In addition, $C_2=\sum_{i=1}^n\mu_i(\ell_i)-\mu_i({\ell_o}_i)=\sum_{i=1}^n\sum_{l={\ell_o}_i}^{\ell_i-1}\xi^*(l/\rho_i)$. We notice that at least for one agent ($x_o$), the addition to the sum is zero.
Following definition, for all $i,\ell$, s.t. $1\leq i\leq n,\ {{\ell_o}_i} \leq \ell \leq \ell_i-1$, $\ell_o/\rho_o<{{\ell_o}_i}/\rho_i$ and also $\ell_o/\rho_o<{\ell}/\rho_i$
Therefore $ord(\ell_o/\rho_o)\geq ord({{\ell_o}_i}/\rho_i)+1$ and also $ord(\ell_o/\rho_o)\geq ord({\ell}/\rho_i)+1$.
Following definition of $\xi$, $\xi(\ell_o/\rho_o)/\xi({{\ell_o}_i}/\rho_i)\geq (k\cdot n)$ and therefore $\xi^*(\ell_o/\rho_o)/\xi^*({{\ell_o}_i}/\rho_i)\geq (k\cdot n)$. Since sum contains at most $(n-1)\cdot k$ non zero items, we conclude that $\delta_o(\ell_o+1)>C_2$.
Next we show that $C_1'-\delta_o(\ell_o+1)\geq C_1$.
Since $\forall{1\leq i\leq n}$,
$\ell'_i/\rho_i > \ell_o/\rho_o$, the value of $C_1'=\sum_{i=1}^n\mu_i({\ell'_o}_i)$ is the maximum possible value for each element in the sum.
Following definitions, ${\ell_o}_o=\ell_o$ and ${\ell'_o}_o=\ell_o+1$ and therefore
$\mu_i({\ell'_o}_i)-\mu_i({\ell_o}_i)=\delta_o(\ell_o+1)$.
Therefore $C_1\leq C_1'-\delta_o(\ell_o+1)$ and given that we showed that $C_2<\delta_o(\ell_o+1)$ we conclude that $C_1'>C_1+C_2$.
Finlay, since $C_1'>C_1+C_2$ and since $C_1+C_2=\mathbb{B}(\mathcal{M})$, $\mathcal{M}$ is not maximizing $\mathbb{B}(\cdot)$. a contradiction.
| {'timestamp': '2022-12-01T02:20:17', 'yymm': '2211', 'arxiv_id': '2211.17199', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17199'} | arxiv |
\section{Introduction}
Coalition formation is a vibrant topic in multi-agent systems that has been continuously researched during the last decades.
It concerns the question of dividing a set of agents, for example, humans or machines, into disjoint coalitions such as research teams.
Agents carry preferences over these coalition structures.
A common assumption is that externalities, that is, the coalition structure outside one's own coalition, play no role.
This is captured in the prominent framework of hedonic games.
Moreover, the desirability of a coalition structure is usually measured with respect to stability.
Abstractly speaking, a coalition structure is stable if there is no agent or set of agents that can perform a beneficial deviation by joining existing coalitions or by forming new coalitions.
There are two specific properties of hedonic games crucially influencing past research.
First, the number of possible coalitions an agent can be part of is exponentially large.
Therefore, a repeatedly considered challenge is to come up with reasonable succinctly representable settings.
It is very prominent in this context to aggregate utilities from cardinal valuations of other agents.
Second, most established stability concepts suffer from non-existence under strong restrictions which often leads to computational boundaries such as hardness of the decision problem whether a stable state exists.
Much of the research has therefore focused on identifying suitable conditions guaranteeing stable states.
The dominant coalition formation framework is static in two dimensions. First, stability is usually a static concept in the sense that, since a coalition structure is either stable or not, we are only interested in \emph{finding} these stable structures.
The underlying assumption here is that we operate in a centralized system where a (desirable) coalition structure can be created by a central authority.
This paradigm has only recently been complemented by interpreting deviations of agents as a dynamic process.
The goal here is to reach stable coalition structures through decentralized individual decisions \citep{BBW21a,BBT22a}.
Second, utility functions are static.
To demonstrate the implications of this assumption, we describe a run-and-chase example, which is present in many classes of hedonic games.
Consider a situation where there are only the two agents Alice and Bob.
Alice wants to be alone in her coalition, whereas Bob wants to be in a joint coalition with Alice.
It is clear that in the two possible coalition structures, there is always an agent who wants to change their situation.
From a centralized perspective, this simply means that no coalition structure has the prospect of stability.
In a distributed, dynamic setting where utilities are static, the following occurs indefinitely: Whenever Alice and Bob are in a joint coalition, then Alice leaves the coalition to be alone.
However, whenever Alice and Bob are in two separate coalitions, then Bob joins Alice.
In practice, such an infinite situation is unreasonable:
After playing run-and-chase for a while, either Alice or Bob are likely to change their behavior and therefore their preferences.
On the one hand, Bob might get frustrated because he is constantly left by Alice and therefore stops his efforts to join her.
On the other hand, Alice could realize the high effort that Bob makes to be in a coalition with her and feels sufficient appreciation to eventually accept Bob in her coalition.
In both scenarios, we reach a state that is stable because of the \emph{history} of the coalition formation process.
In this paper, we model situations where the history influences the agents' utilities, offering a new perspective on the reachability of stable coalition structures.
We study a dynamic coalition formation process where agents perform deviations based on stability concepts.
However, in contrast to previous work on dynamics, we assume that a deviation has an effect on the \emph{perception} of the deviator, resulting in agents changing their utility for the deviator.
We distinguish two approaches.
First, an agent might act \emph{resentfully} in the sense that, like Bob, she lowers her utility for an agent abandoning her.
A deviator abandoning a resentful agent again and again eventually looses all of her attraction to the resentful agent.
On the other hand, an agent could \emph{appreciate} the effort of another agent to be part of her coalition, and therefore, like Alice, increase her utility for an agent whenever the agent joins her.
After sufficient effort, the urge to leave the deviator ceases.
\begin{table}[t!]\centering
\caption{Overview of results. ``\cmark'' means that the corresponding dynamics is guaranteed to converge; ``\xmark'' means that we have an example for an infinite sequence. See \Cref{se:prelims} for definitions. For each result, we include the number of the respective statement.}\label{se:ov-table}
\setlength{\tabcolsep}{4pt}
\begin{tabular}{lc|c|c|c|c|c|c}
\toprule
& \multicolumn{1}{c}{SCS} & \multicolumn{1}{c}{CS} & \multicolumn{1}{c}{IS} & \multicolumn{1}{c}{CNS} & \multicolumn{1}{c}{NS} \\
\midrule
\makebox[-1pt][l]{\textbf{ASHG}}\\
resent & \cmark~(\ref{thm:resent:SC-converges}) & \cmark~(\ref{thm:resent:SC-converges})& \cmark~(\ref{thm:resent:SC-converges})& \textbf{?} & \textbf{?} \\
resent+IR & \cmark~(\ref{thm:resent:SC-converges})& \cmark~(\ref{thm:resent:SC-converges})& \cmark~(\ref{thm:resent:SC-converges})& \cmark~(\ref{thm:resent:NS-IR-converges})& \cmark~(\ref{thm:resent:NS-IR-converges}) \\
appreciation & \xmark~(\ref{th:appreciative-core-cylce}) & \xmark~(\ref{th:appreciative-core-cylce}) & \textbf{?} & \cmark~(\ref{thm:apprec-CNS})& \textbf{?} \\
\midrule
\makebox[-1pt][l]{\textbf{MFHG}}\\
resent & \textbf{?} & \textbf{?} & \textbf{?} & \textbf{?} & \xmark~(\ref{th:mfhg-resent}) \\
resent+IR & \cmark~(\ref{thm:resent:SC-can-converge}) & \cmark~(\ref{thm:resent:SC-can-converge})& \cmark~(\ref{thm:resent:SC-can-converge})& \cmark~(\ref{thm:resent:NS-IR-converges})& \cmark~(\ref{thm:resent:NS-IR-converges}) \\
appreciation & \xmark~(\ref{th:appreciative-core-cylce}) & \xmark~(\ref{th:appreciative-core-cylce})& \textbf{?} & \textbf{?} & \xmark~(\ref{th:mfhg-apprec})\\
\bottomrule
\end{tabular}
\end{table}
\subsection{Contribution}
We initiate the study of cardinal hedonic games under utility functions changing over time.
In particular, we consider utility modifications based on the resentful and appreciative perception of other agents.
We investigate whether decentralized dynamics based on various types of deviations are guaranteed to converge.
Deviations might be constrained to be individually rational (IR), that is, a deviating agent needs to prefer her new coalition to being alone.
We showcase our results by considering additively separable hedonic games (ASHGs) and modified fractional hedonic games (MFHGs), where an agent's utility for a coalition is the sum or average utility for the other agents in the coalition, respectively.
\Cref{se:ov-table} provides an overview of these results.
First, for resentful agents performing individually rational deviations, convergence is guaranteed in all considered cases.
If deviations may also violate individual rationality,
the situation becomes more complicated and elusive to a complete understanding; nevertheless, we establish several convergence guarantees while also having an involved example of a cycling dynamics in MFHGs.
In contrast, appreciation is usually not sufficient to guarantee convergence.
Notably, as proved in \Cref{co:equivalence} four of our open questions concerning both resentful and appreciative agents are in some sense equivalent.
In fact, most of our results do not only apply to ASHGs and/or MFHGs but to larger classes of hedonic games.
For this, we develop an axiomatic framework for utility aggregation based on the perception of friends and enemies, that is, agents yielding positive and negative utility, respectively.
In our simulations, we observe that our model of dynamic utilities leads to the (quick) convergence of Nash dynamics.
Moreover, we analyze the structure and expressiveness
of the produced outcomes.
Finally, we outline results for other perception models and for computational questions concerned with finding shortest converging sequences.
\subsection{Related Work}
Hedonic games originate from economic theory \citep{DrGr80a}, but their constant and broad consideration only started with key publications by \citet{BKS01a}, \citet{CeRo01a}, and \citet{BoJa02a}.
An overview of hedonic games is provided in the survey by \citet{AzSa15a}.
The search for suitable representations of reasonable classes of hedonic games has led to various proposals \citep[see, e.g.,][]{CeRo01a,BoJa02a,Ball04a,ElWo09a,Olse12a,ABB+17a}.
Various stability concepts and their computational boundaries have been previously studied. We focus on results concerning ASHGs \citep{BoJa02a} and MFHGs \citep{Olse12a}.
\citet{SuDi10a} show prototype \NP-hardness reductions for single-agent stability concepts in ASHGs, paving the way for many similar results for single-agent and group stability \citep[see, e.g.,][]{ABS11c,BBT22a,Bull22a}.
\citet{GaSa19a} consider ASHGs under symmetric utilities and show \PLS-completeness of computing stable states, while \citet{Woeg13a} and \citet{pet:c:precise-hed-games} show $\Sigma_2^\P$-completeness of the (strict) core in ASHGs.
\citet{pet-elk:c:simple-causes-complex-hed-games} provide a meta view on computational hardness.
For MFHGs, there seem to be less computational boundaries. Indeed, for symmetric and binary utilities, stable states exist and can be efficiently computed. Core stability is even tractable for symmetric and arbitrarily weighted utilities \citep{MMV18a}.
Apart from the consideration of stability, other desirable notions of efficiency or fairness such as Pareto optimality, envy-freeness, or popularity have been studied for ASHGs and MFHGs \citep{ABS11c,EFF20a,Bull19a,BrBu22a}.
These papers provide more evidence that MFHGs seem to be less complex than ASHGs.
The dynamical, distributed approach to coalition formation received increased attention very recently \citep{HVW18a,BFFMM18a,CMM19a,BBW21a,FMM21a,BBT22a,BMM22a}.
There, \citet{BFFMM18a,BBW21a,BBT22a} consider stability based on single-agent deviations, whereas \citet{CMM19a,FMM21a} consider group stability.
Finally, another recent approach to achieve a guarantee to stability in hedonic games is the consideration of loyalty \citep{BuKo21a} which is based on altruism in hedonic games \citep{KNRRRSW22}.
\section{Preliminaries and Model}\label{se:prelims}
In this section, we define the basic coalition formation setting, our specific model, and provide some first observations. For an integer $i\in \mathbb{N}$, we define $[i]=\{1,\ldots,i\}$.
\subsection{Cardinal Hedonic Games}
Let $N=[n]$
be a finite set of \emph{agents}.
A \emph{coalition} is any subset of $N$.
We denote the set of all possible coalitions containing agent $i\in N$ by
$\mathcal N_i = \{C\subseteq N\colon i\in C\}$.
Any \emph{partition} of the agents $N$
is also called \emph{coalition structure} and
we denote the set of all partitions of $N$ by $\Pi_N$.
Given an agent $i\in N$ and a partition $\pi \in \Pi_N$, let $\pi(i)$ denote the coalition of $i$, i.e., the unique coalition $C\in \pi$ with $i\in C$.
A \emph{(cardinal) hedonic game} is a pair $(N,u)$ consisting of
a set $N$ of agents and a utility profile $u=(u_i)_{i\in N}$ where $u_i\colon N \to \mathbb Q$ is the \emph{utility function} of agent $i$.
Thus, for $i,j\in N$, $u_i(j)$ is $i$'s utility for agent $j$.
We sometimes equivalently view a utility function as a vector $u_i\in \mathbb Q^n$.
An agent $j\in N$ is a \emph{friend} (or \emph{enemy}) of an agent $i\in N$ if $u_i(j) > 0$ (or $u_i(j) < 0$).
To move from utilities for single agents to utilities over coalitions, we use
\emph{cardinal aggregation functions} (\cafs).
For every agent $i\in N$,
the {\caf} $A_i\colon \mathcal N_i \times \mathbb Q^n \to \mathbb Q$ specifies $i$'s utility for a given coalition
for her given utility vector.
Then, the utility of an agent for a partition $\pi$ with respect to aggregation function $A_i$ is $u_i^{A_i}(\pi) = A_i(\pi(i), u_i)$. To keep notation concise, we sometimes omit the {\caf} as a superscript when it is clear from the context.
For an agent $i\in N$ with utility function $u_i$, a coalition $C\in \mathcal{N}_i$ is \emph{individually rational} (IR) if $A_i(C,u_i) \ge A_i(\{i\},u_i)$.
Further, a partition $\pi$ is \emph{individually rational} (IR) for agent $i$ if $\pi(i)$ is an individually rational coalition.
Common classes of cardinal hedonic games such as the two specific classes studied in this paper have a straightforward representation with respect to \cafs. For each agent $i\in N$ with utility function $u_i$,
\begin{itemize}
\item additively separable hedonic games (ASHGs) \citep{BoJa02a}
use the aggregation function $\mathit{AS}$ defined by
$\mathit{AS}_i(C, u_i)= \sum_{j\in C\setminus\{i\}}u_i(j)$ and
\item modified fractional hedonic games (MFHGs) \citep{Olse12a}
use the aggregation function $\mathit{MF}$ defined by
$\mathit{MF}_i(C, u_i)= \frac{\sum_{j\in C\setminus \{i\}}u_i(j)}{|C|-1}$ if $|C|\ge 2$ and $\mathit{MF}_i(C, u_i) = 0$, otherwise.
\end{itemize}
\subsection{Deviations and Stability}
As indicated in the introduction, we
distinguish different stability notions
based on single-agent deviations
and group deviations.
Given a partition $\pi\in \Pi_N$,
agent $i\in N$ might perform
a \emph{single-agent deviation} from $\pi(i)$ to any coalition $C\in \pi\cup\{\emptyset\}$,
resulting in the partition
$\pi'
=(\pi \setminus \{\pi(i), C \})\cup \{\pi(i)\setminus\{i\},C\cup\{i\}\}$;
and a group of agents $C\subseteq N$ might perform
a \emph{group deviation},
leading to the partition
$\pi'
=(\pi \setminus\{\pi(j)\mid j\in C \})\cup\{\pi(j)\setminus C\mid j\in C\}\cup\{C\}$.
Depending on which agents improve as a result of a deviation,
we distinguish the following \emph{types of deviations}.
Agent $i$'s single-agent deviation from $\pi(i)$ to $C\in \pi\cup\{\emptyset\}$,
resulting in partition $\pi'$,
is a
\emph{Nash} (NS) deviation if $u_i(\pi') > u_i(\pi)$.
An NS deviation of $i$ from $\pi$ to $\pi'$
is called
\begin{itemize}
\item an \emph{individual} (IS) deviation if $u_j(\pi')\ge u_j(\pi)$
for all $j\in C$, where $C$ is the coalition to which $i$ deviated;~and
\item a \emph{contractual Nash} (CNS) deviation if $u_j(\pi')\ge u_j(\pi)$
for all $j\in \pi(i)\setminus\{i\}$.
\end{itemize}
A group deviation of coalition $C$ from $\pi$ to $\pi'$ is
\begin{itemize}
\item a \emph{core} (CS) deviation if $u_i(\pi') > u_i(\pi)$
for all $i\in C$; and
\item a \emph{strict core} (SCS) deviation if $u_i(\pi') \ge u_i(\pi)$
for all $i\in C$ and
$u_j(\pi') > u_j(\pi)$
for some $j\in C$.
\end{itemize}
Finally, for all types of deviations introduced above, we
define the respective stability notion of a partition by the absence of a corresponding deviation.
For example, a partition $\pi$ is said to be Nash-stable (NS) if
there is no NS deviation from $\pi$ to another partition.
The logical relations among the resulting stability concepts are illustrated in \Cref{fig:stability-relations} \citep[see also][]{AzSa15a}.
For a given partition,
several single-agent or group deviations might be possible.
Yet, some deviations seem to be more reasonable than others.
We say that a deviation is IR if
the resulting partition is IR
for all deviating agents.
For all our considered stability concepts it holds that if an agent has a deviation (that is potentially not IR), then she also has an IR deviation where she forms a singleton coalition.
\begin{figure}
\centering
\begin{tikzpicture}
\pgfmathsetmacro\lengthunit{0.8}
\pgfmathsetmacro\heightunit{0.8}
\node (NS) at (0,2*\heightunit) {NS};
\node (IS) at (\lengthunit,\heightunit) {IS};
\node (CNS) at (-\lengthunit,\heightunit) {CNS};
\node (SC) at (2*\lengthunit,2*\heightunit) {SCS};
\node (C) at (3*\lengthunit,\heightunit) {CS};
\draw[->] (NS) edge (CNS);
\draw[->] (NS) edge (IS);
\draw[->] (SC) edge (IS);
\draw[->] (SC) edge (C);
\end{tikzpicture}
\caption{Relations among our stability concepts.
Arrows
indicate implications.
For example,
strict core stability (SCS) implies
core stability (CS) and
individual stability~(IS).
\label{fig:stability-relations}}
\end{figure}
\subsection{Dynamic Coalition Formation}
We now introduce our model of dynamic coalition formation over time, and the concepts of \emph{resent} and \emph{appreciation}.
Throughout the paper, we consider sequences of partitions $(\pi^t)_{t\ge 0}$, where for every $t\ge 1$,
$\pi^t$ evolves from $\pi^{t-1}$ by means of some single-agent or group deviation.
We assume that both the initial coalition structure $\pi^0$ and the initial utility vectors $u_i^0$ for each agent $i\in N$ are given.
However, utilities change over time as follows.
Under \emph{resent}, agents
decrease their utilities for all deviators that leave them (by one), while under \emph{appreciation}, agents increase their utilities
for all deviators that join them (by one).\footnote{Note that our choice of decreasing, resp., increasing the utilities by one is somewhat arbitrary, as our theoretical results hold for any fixed increase or decrease of utilities. However, note that in case the utility change in each round is not constant, our convergence guarantees are no longer applicable, as, for instance, run-and-chase situations can occur.}
More formally, if for some $t\ge 1$, $\pi^t$ evolves from $\pi^{t-1}$ via a
single-agent deviation of agent $k\in N$, then, for $i,j\in N$,
\begin{itemize}
\item for \emph{resentful} agents, $u_i^t(j)$ arises from $u_i^{t-1}(j)$ as
\[u_i^t(j) = \begin{cases}
u_i^{t-1}(j) -1 & i\neq k, j=k, j\in \pi^{t-1}(i),\\
u_i^{t-1}(j) & \text{else.}\\
\end{cases}\]
\item for \emph{appreciative} agents, $u_i^t(j)$ arises from $u_i^{t-1}(j)$ as
\[u_i^t(j) = \begin{cases}
u_i^{t-1}(j) +1 & i\neq k, j=k, j\in \pi^{t}(i),\\
u_i^{t-1}(j) & \text{else.}\\
\end{cases}\]
\end{itemize}
If for $t\ge 1$, $\pi^t$ evolves from $\pi^{t-1}$ via a group deviation of $C\subseteq N$, then, for $i,j\in N$,
\begin{itemize}
\item for \emph{resentful} agents, $u_i^t(j)$ arises from $u_i^{t-1}(j)$ as
\[u_i^t(j) = \begin{cases}
u_i^{t-1}(j) -1 & i\notin C, j\in C, j\in \pi^{t-1}(i),\\
u_i^{t-1}(j) & \text{else.}\\
\end{cases}\]
\item for \emph{appreciative} agents, $u_i^t(j)$ arises from $u_i^{t-1}(j)$ as
\[u_i^t(j) = \begin{cases}
u_i^{t-1}(j) +1 & i\neq j, i\in C, j\in C,\\
u_i^{t-1}(j) & \text{else.}\\
\end{cases}\]
\end{itemize}
We are concerned about sequences of partitions that evolve by deviations with respect to the current utilities of the agents.
For any stability concept $\alpha \in \{\mathit{NS, IS, CNS, CS, SCS}\}$, a sequence of partitions $(\pi^t)_{t\ge 0}$ is called an execution of an $\alpha$ \emph{dynamics} if $\pi^t$ evolves from $\pi^{t-1}$ through an $\alpha$ deviation with respect to the utility functions $(u_i^{t-1})_{i\in N}$.
If all deviations are individually rational, we call the dynamics \emph{individually rational}, e.g., individually rational NS dynamics in the case of Nash stability.
An execution of an $\alpha$ dynamics \emph{converges} if it terminates after a finite number of $T$ steps in a partition $\pi^T$ that is stable with respect to
$(u_i^T)_{i\in N}$
under the stability notion $\alpha$.
We say that the $\alpha$ dynamics \emph{converges} if every execution of the $\alpha$ dynamics converges for every initial utility profile and partition. By contrast, the dynamics \emph{cycles} if there exists an infinite execution of the dynamics (for some initial utilities and partition).
The central question of this paper is when dynamics converge for resentful or appreciative agents.
It is convenient to use a compact notation for utilities. We write $u_i^{t,A_i}(\pi) = A_i(\pi(i),u_i^t)$ and $u_i^{t,A_i}(C) = A_i(C,u_i^t)$ for the utility of agent $i$ at time $t$ for a partition $\pi\in \Pi_N$ or for coalition $C\in \mathcal N_i$, respectively. If the {\caf} $A_i$ is clear from context, we usually omit it as superscript.
Before our main analysis, we present a useful lemma that holds for arbitrary dynamics.
The lemma can be applied to show that, from a certain point onwards, every deviation occurs infinitely often in an infinite execution of a dynamic.
The proof is straightforward and is included in the appendix.
\begin{restatable}{lemma}{infinite}
\label{lem:infoccurence}
Let $(\pi^t)_{t\ge 0}$ be an infinite sequence of partitions induced by single-agent (or group) deviations. Then, there exists a $t_0\ge 0$ such that every single-agent (or group) deviation performed at some time $t\ge t_0$ occurs infinitely often.
\end{restatable}
Lastly, we call an infinite sequence of partitions $\pi = (\pi^t)_{t\ge 0}$ \emph{periodic} if there exist $t_0\in \mathbb N$ and $p\in \mathbb N$ such that, for all $k\in \mathbb N_0$ and $l\in \{0,\dots, p-1\}$, it holds that $\pi^{t_0+kp+l} = \pi^{t_0+l}$.
\subsection{Properties of Aggregation Functions}
We now introduce some
useful properties
of \cafs.
For any $i\in N$, a {\caf} $A_i$ satisfies
\begin{itemize}
\item \emph{aversion to enemies} (ATE) if, for all
coalitions $C\in \mathcal{N}_i$,
agents $j\in C\setminus\{i\}$,
and utility vectors $u_i\in \mathbb Q^n$ with $u_i(j) < 0$, it holds that $A_i(C, u_i) \le A_i(C\setminus\{j\}, u_i)$. In other words, the aggregated utility is weakly better whenever an enemy leaves $i$'s coalition.
\item \emph{individually rational aversion to enemies} (IR ATE) if,
for all
coalitions $C\in \mathcal{N}_i$,
agents $j\in C\setminus\{i\}$,
and utility vectors $u_i\in \mathbb Q^n$ with $u_i(j) < 0$, it holds that $A_i(C, u_i) \le A_i(C\setminus\{j\}, u_i)$
if $A_i(C,u_i)\ge A_i(\{i\},u_i)$. In other words, the aggregated utility is weakly better when an enemy leaves one of $i$'s individually rational coalitions.
\item \emph{enemy monotonicity} (EM) if,
for all
coalitions $C\in \mathcal{N}_i$,
agents $j\in N$, and utility vectors $u_i, u_i'\in \mathbb Q^n$ with $u_i(k) = u_i'(k)$ for all $k \neq j$ and $u_i'(j) < u_i(j) < 0$, it holds that $A_i(C, u_i) \ge A_i(C, u_i')$. In other words, decreasing the utility for an enemy cannot improve a coalition value.
\item \emph{enemy domination} (ED) if,
for all
utility vectors $u_i\in \mathbb Q^n$ and
agents $j\in N\setminus \{i\}$, there exists a constant $c(u_i,j)$ such that for all utility vectors $u_i' \in \mathbb Q^n$ with $u_i'(k) \le u_i(k)$ for all $k\in N$ and $u_i'(j)\le c(u_i,j)$, it holds for every $C\in \mathcal{N}_i$ with $j\in C$
that $A_i(C, u_i') < A_i(\{i\},u_i')$. In other words, an {\caf} satisfies ED if in case $i$'s utility for some agent $j$ is sufficiently negative and $i$'s utility for every other agent is bounded, then no coalition containing $j$ is individually rational for $i$.
\end{itemize}
All of these axioms capture the treatment of enemies.
The first two axioms deal with situations where an enemy leaves the agent's coalition, where ATE is stronger than IR ATE.
On the other hand, EM and ED are variable utility conditions describing situations where the utility for an enemy decreases or some agent turns into a very bad enemy, respectively.
Apart from the implication between ATE and IR ATE, there are no other logical relationships between any pair of axioms.
\begin{example}\label{ex:MFHGviolateATE}
In this example, we consider a game $(N,u)$ for which the {\caf} $\mathit{MF}$ violates ATE.
Let $N = \{a,b,c\}$ and let the single-agent utilities be $u_a(b) = -1$, $u_a(c) = -3$, $u_b(a) = 1$, and $u_b(c) = -1$. (The utilities $u_c(a)$ and $u_c(b)$ are irrelevant.)
\begin{figure}
\centering
\begin{tikzpicture}[
element/.style={shape=circle,draw, fill=white}
]
\node[element] (a) at (-1.2,0) {$a$};
\node[element] (b) at (60:1.2) {$b$};
\node[element] (c) at (300:1.2) {$c$};
\draw[bend right = 20, ->] (a) edge node[midway, fill = white] {$-1$} (b);
\draw[->] (a) edge node[midway, fill = white] {$-3$} (c);
\draw[bend right = 20, ->] (b) edge node[midway, fill = white] {$1$} (a);
\draw[->] (b) edge node[midway, fill = white] {$-1$} (c);
\end{tikzpicture}
\caption{Illustration of teh game $(N,u)$ in \Cref{ex:MFHGviolateATE}. An edge with weight $w$ from agent $x$ to agent $y$ means that $u_x(y) = w$.}
\end{figure}
Then, removing an enemy can make an agent worse. Indeed, $\mathit{MF}_a(N,u_a) = -2 > -3 = \mathit{MF}_a(\{a,c\},u_a)$.
Hence, $\mathit{MF}$ violates ATE.
On the other hand, as we will see in \Cref{prop:axioms}, removing an enemy from an individually rational coalition cannot decrease the utility in an MFHG. For instance, $\mathit{MF}_b(N,u_b) = 0 < 1 = \mathit{MF}_b(\{a,b\},u_b)$. \hfill$\lhd$
\end{example}
Still, classical aggregation functions usually satisfy (most of) our introduced axioms.
\begin{restatable}{proposition}{axioms}
\label{prop:axioms}
The additively separable {\caf} $\mathit{AS}_i$ satisfies ATE, IR ATE, EM, and ED.
The modified fractional {\caf}~$\mathit{MF}_i$ satisfies IR ATE, EM, and ED but violates ATE.
\end{restatable}
\begin{proof}
We first consider additively separable aggregation and each axiom separately.
\begin{itemize}
\item ATE holds because a sum gets smaller when removing a negative summand.
\item IR ATE follows from ATE.
\item EM holds because a sum can only get smaller when decreasing every summand (and decreasing one of them strictly).
\item ED holds because $\sum_{k\in C\setminus\{i\}}u_i(k)$ gets negative if all summands only diminish and, for $j\in C\setminus\{i\}$, $u(j) \le - 1 - \sum_{k\in C\setminus \{j\}}u_i(k)$. Hence, we can choose the constant $c(u_i,j) = \min_{C\in \mathcal N_i\colon j\in C} - 1 - \sum_{k\in C\setminus \{j\}}u_i(k)$.
\end{itemize}
Next, we consider modified fractional aggregation. The violation of ATE is considered in \Cref{ex:MFHGviolateATE}.
\begin{itemize}
\item IR ATE: Let $C\subseteq \mathcal N_i$, $j\in C\setminus\{i\}$, and $u_i\in \mathbb Q^n$ with $u_i(j) < 0$. Moreover, suppose that $\mathit{MF}_i(C,u_i)\ge 0$. Then, $|C| \ge 3$ because otherwise $\mathit{MF}_i(C,u_i) = u_i(j) < 0$. Consequently,
\begin{align*}
&\mathit{MF}_i(C\setminus\{j\},u_i) \ge \mathit{MF}_i(C,u_i) \\
\Leftrightarrow & \frac{\sum_{k\in C\setminus \{i,j\}}u_i(k)}{|C|-2} \ge \frac{\sum_{k\in C\setminus\{i\}}u_i(k)}{|C|-1}\\
\Leftrightarrow & (|C| - 1) {\sum_{k\in C\setminus \{i,j\}}u_i(k)} \ge (|C|-2)\sum_{k\in C\setminus\{i\}}u_i(k)\\
\Leftrightarrow & \sum_{k\in C\setminus \{i,j\}}u_i(k) \ge (|C|-2)u_i(j)\\
\Leftrightarrow & \frac{\sum_{k\in C\setminus\{i\}}u_i(k)}{|C|-1} \ge u_i(j).
\end{align*}
Hence, whenever $u_i(j) < 0$ and $\mathit{MF}_i(C,u_i)\ge 0$, the utility increases in the coalition where $j$ has left.
\item EM and ED hold for the same reasons as for ASHGs because the division by a positive number does not change the respective arguments.
\end{itemize}
\end{proof}
\section{Dynamics for Resentful Agents} \label{sec:resent}
In this section, we study the convergence of different types of dynamics for resentful agents.
We start by considering (S)CS and IS dynamics, before turning to CNS and NS dynamics.
\subsection{Core Stability and Individual Stability}
If deviating agents need consensus from their new coalition, it turns out that resent is a strong force to establish convergence.
The intuitive reason for this is that an agent $a$ can only leave an agent $b$ for a limited number of times until resent prevents that they form a joint coalition again. In fact, otherwise $b$'s utility for $a$ becomes arbitrarily negative and $b$ no longer gives $a$ her consent to join.
We will prove that SCS dynamics, and thereby also CS and IS dynamics, always converge for a wide class of {\cafs}.
\begin{restatable}{theorem}{resentsc}
\label{thm:resent:SC-converges}\label{cor:resent-convergence}
The \mbox{SCS}, CS, and IS dynamics converge for resentful agents whose {\cafs} satisfy
aversion to enemies and enemy monotonicity.
\end{restatable}
\begin{proof}
It suffices to consider SCS dynamics because every CS dynamics and every IS dynamics is also an SCS dynamics.
Let a hedonic game $(N,u^0)$ with resentful agents be given
where every agent $i\in N$ has a {\caf}~$A_i$ that satisfies
aversion to enemies and enemy monotonicity.
The key insight to show convergence of the SCS dynamics is to prove that in every infinite sequence of SCS deviations,
it happens infinitely often that
the \emph{non-negative} single-agent valuation of some agent for another agent is decreased (due to resent). This is a contradiction, as the number of such deviations is bounded by $\sum_{i,j\in N\colon u_i^0(j)\ge 0} (\lfloor u_i^0(j)\rfloor + 1)$.
Consider an infinite execution $(\pi^t)_{t\ge 0}$ of the SCS dynamics.
For the sake of contradiction, assume that there is a step $t_0\ge 0$ in this execution such that, starting with $t_0$, it never happens again that the non-negative valuation of some agent for another agent is decreased. The first step towards a contradiction is to show that every SCS deviation is a Pareto improvement in this situation.\footnote{An outcome is a \emph{Pareto improvement} over another outcome if it is weakly better for all agents and strictly better for some agents.} Indeed, every deviation is weakly improving for every agent in the coalitions that are abandoned: As no agent decreases her non-negative utility for another agent, each abandoned agent is solely abandoned by agents for which she momentarily has a negative utility.
We can then iteratively apply aversion to enemies to conclude that the deviation (weakly) increases
the utility of each abandoned agent.
Further, since by the definition of an SCS deviation, every agent of the newly formed coalition is weakly improving, and some of them are strictly improving, each SCS deviation is a Pareto improvement.
Still, it is not clear, why the changes of the utility functions due to resent cannot cause sequences of Pareto improvements of infinite length, and we need enemy monotonicity to prove that this can never be the case.
To this end, we will show that every agent~$i$ can deviate at most once to each coalition $C\in \mathcal N_i$ while \emph{improving her utility} by doing so. This provides an upper bound for the length of any sequence of Pareto improving deviations.
Consider a time $t \ge t_0$ and define for some agent $i \in N$ the set $\mathcal C_i^t = \{C\in \mathcal N_i \colon u_i^t(C) > u_i^t(\pi^t)\}$, i.e., the set of coalitions that would lead to an improvement of agent $i$ at time $t$. Consider the potential function $V^t = \sum_{i\in N} |\mathcal C_i^t|$. Note that $V^{t_0}\le \sum_{i\in N}|\mathcal N_i|$ is initially bounded and that the potential attains only non-negative integer values. We will show that the potential decreases in every time step after $t_0$.
To this end, let $i\in N$ be some fixed agent and $t\ge t_0$ some fixed time. If $\pi^{t+1}(i) = \pi^t(i)$, then agent $i$ does not change her utilities, and $\mathcal C_i^{t+1} = \mathcal C_i^t$.
Further, if $\pi^{t+1}(i) \neq \pi^t(i)$ but agent~$i$ was not part of the deviating coalition, then, by our above assumption that no non-negative utility gets decreased, $u_i^t(j) < 0$ for all agents $j\in \pi^t(i)\setminus \pi^{t+1}(i)$. Hence, we can repeatedly apply aversion to enemies for all agents in $\pi^t(i)\setminus \pi^{t+1}(i)$ to conclude that $u_i^{t+1}(\pi^{t+1}) = u_i^{t}(\pi^{t+1}) \ge u_i^t(\pi^t)$.
Further, as only $i$'s valuations of agents from $\pi^t(i)\setminus \pi^{t+1}(i)$ got modified (decreased), the only coalitions $C\in \mathcal N_i$ that might have changed their value for agent $i$ contain some agent in $\pi^t(i)\setminus \pi^{t+1}(i)$. Hence, we can (repeatedly) apply enemy monotonicity to conclude that $u_i^{t+1}(C)\le u_i^t(C)$ for all such coalitions.
Hence, $\mathcal C_i^{t+1} \subseteq \mathcal C_i^t$.
Finally, if agent $i$ is part of the deviating coalition at step $t$, then she does not change her utilities for any agent and weakly improves the valuation of her coalition. Hence, $\mathcal C_i^{t+1} \subseteq \mathcal C_i^t$ and we can conclude that $V^{t+1}\le V^t$.
Further, if $i$ strictly improves her utility, then $u_i^{t+1}(\pi^{t+1}) > u_i^{t+1}(\pi^t)$ and it follows that $\pi^{t+1}(i)\in \mathcal C_i^t \setminus \mathcal C_i^{t+1}$. Hence, $\mathcal C_i^{t+1} \subsetneq \mathcal C_i^t$. Since this has to be the case for at least one agent in every time step, we conclude that $V^{t+1} < V^t$.
\end{proof}
As the cardinal aggregation function $\mathit{AS}$ satisfies aversion to enemies and enemy monotonicity (cf. \Cref{prop:axioms}), \Cref{thm:resent:SC-converges} in particular implies that the SCS, CS, and IS dynamics always converge in ASHGs for resentful agents.
Notably, \Cref{cor:resent-convergence} breaks down if we consider a {\caf} violating aversion to enemies, even if enemy monotonicity is still satisfied.
Indeed, we can then ``ignore'' individual utilities.
For instance, anonymous hedonic games where agents only care about the size of their coalitions satisfy enemy monotonicity.
In such games, resent is clearly irrelevant and there exist anonymous hedonic games where IS dynamics cycle \citep{BBW21a}.
Consequently, a result similar to \Cref{thm:resent:SC-converges} for aggregation functions that only satisfy enemy monotonicity cannot be obtained.
On the other hand, it remains an open question whether enemy monotonicity is necessary for \Cref{thm:resent:SC-converges}.
Unfortunately, $\mathit{MF}$ violates aversion to enemies (\Cref{prop:axioms}),
implying that \Cref{cor:resent-convergence} cannot be directly applied to MFHGs for resentful agents.
Nevertheless, if we require the performed SCS deviations to be individually rational, then we can achieve convergence for a class of games containing MFHGs (cf. \Cref{prop:axioms}).
\begin{restatable}{theorem}{resentscenemy}
\label{thm:resent:SC-can-converge}\label{cor:resent-can-converge}
The individually rational SCS, CS, and IS dynamics converge for resentful agents whose {\cafs} satisfy
individually rational aversion to enemies and enemy monotonicity.
\end{restatable}
\begin{proof}
Again, it suffices to consider SCS dynamics.
Let a hedonic game $(N,u^0)$ with resentful agents be given
where every agent $i\in N$ has a {\caf}~$A_i$ that satisfies individually rational aversion to enemies and enemy monotonicity. Assume that agents perform only individually rational deviations.
Assume for contradiction that there exists an infinite execution of the individually rational SCS dynamics. Since the single-agent utilities for other agents can only decrease and are bounded by the initial partition of the sequence, there exists a time $t_0\ge 0$ in the infinite dynamics after which no agent can be left by an agent for which she has non-negative utility.
By \Cref{lem:infoccurence}, there exists a time $t_1\ge t_0$ such that every SCS deviation performed after time $t_1$ is performed infinitely often.
Now, consider the first group deviation performed after time $t_1$, where a coalition $C$ is formed and let $i\in C$ be an arbitrary agent in this coalition. Note that the formation of $C$ was an individually rational deviation, and therefore $C$ is individually rational for agent $i$ at time $t_1$.
We claim that $i$'s utility cannot decrease until the next time when the same deviation is performed, and that all coalitions that $i$ is part of until then are IR. Until the next repetition of the same deviation, there are two potential cases when $i$'s utility is affected. First, it can happen that $i$ is part of a deviating coalition.
Clearly, this cannot decrease her utility, and therefore not affect her individual rationality. Second, it can happen that $i$'s coalition is left by a set of agents $D$.
Since~$i$ is resentful and decreases her utility for all agents in $D$, it must be the case that her utility is negative for every agent in $D$ at the point in time where the deviation involving $D$ occurs.
Moreover, $i$'s coalition is IR when $D$ leaves.
Indeed, assume for contradiction that $i$'s coalition is not IR, and consider the first time after the formation of $C$ when~$i$ is in a coalition that is not IR. By our analysis before, this can only happen after $i$ performed a group deviation, but since this deviation originated from an IR coalition, the resulting coalition must also be IR, a contradiction.
Now, by applying individually rational aversion to enemies for each agent in $D$ one after another, we can conclude that $i$ cannot have decreased her utility at the point in time where she is left by $D$.
Hence, at the next time, when coalition $C$ is formed, by the same deviation as our initial deviation, none of the agents in $C$ has decreased her utility.
Moreover, enemy monotonicity implies that the utility of $C$ of any agent for $C$
can only have decreased since the last time when $C$ was formed.
Hence, no agent can strictly improve her utility when forming $C$ again, a contradiction.
We conclude that the dynamics cannot run infinitely.
\end{proof}
It remains open whether general SCS, CS, or IS dynamics for resentful agents may cycle in an MFHG.
\subsection{Contractual Nash Stability and Nash Stability}
For individually rational NS dynamics,
resent helps to establish convergence for a wide class of games.
\begin{restatable}{theorem}{resentNSIR}
\label{thm:resent:NS-IR-converges} \label{cor:resent-special-classes}
The individually rational NS dynamics converges for resentful agents whose {\cafs} satisfy enemy domination.
\end{restatable}
\begin{proof}
Let a hedonic game $(N,u^0)$ with resentful agents be given
where every agent $i\in N$ has a {\caf}~$A_i$ that satisfies enemy domination. Assume for contradiction that there is an infinite execution of the individually rational NS dynamics $(\pi^t)_{t\ge 0}$. Suppose that, for every $t\ge 1$, $\pi^t$ evolves from $\pi^{t-1}$ by an individually rational NS deviation of agent~$d^t$.
By \Cref{lem:infoccurence}, there exists $t_0\ge 0$ such that every deviation performed after $t_0$ is performed infinitely often. We will reach a contradiction in two steps. First, we use enemy domination to show that no agent can ever be abandoned by an agent that she joined after $t_0$. Then, as a second step, we use this insight to show the existence of a non-negative potential function decreasing in every time step after $t_0$.
For the first step, let $i\in N$ be an agent and let $C\in \mathcal N_i$ be a coalition such that agent~$i$ performs a deviation at time $t_1\ge t_0$ to form coalition $C$.
Then, no agent from $C\setminus \{i\}$ can abandon agent~$i$ in any of their deviations after time~$t_0$.
Assume for contradiction that there exists an agent $j\in C\setminus \{i\}$ who abandons agent~$i$ after time $t_0$.
Since the aggregation function satisfies enemy domination, there is a constant $c(u_i,j)$ such that for all utility vectors $u'_i$ with $u'_i(k) \le u^{t_1}_i(k)$ for all $k\in N$ and $u'_i(j)\le c(u_i,j)$, it holds that $u_i'(C) < u_i'(\{i\})$.
Since every deviation occurs infinitely often, there exists a time $t_2\ge t_1$ such that agent~$j$ has abandoned agent~$i$ for at least $u^{t_1}_i(j) - c(u_i,j)$ times between time $t_1$ and time $t_2$.
Since agent~$i$ is resentful, this implies that $u^{t_2}_i(j) \le u^{t_1}_i(j) - (u^{t_1}_i(j) - c(u_i,j)) = c(u_i,j)$. Additionally, resentful agents can only decrease utilities for other agents.
Therefore, it holds for all $t\ge t_2$ and $k\in N$ that $u^t_i(k) \le u^{t_1}_i(k)$ and $u^t_i(j)\le c(u_i,j)$.
Consequently, it follows from enemy domination for all times $t\ge t_2$ that agent~$i$ cannot deviate to form coalition~$C$ again because this deviation would not be individually rational.
However, this contradicts the fact that every deviation after time~$t_1$ has to be performed infinitely often. This establishes the second step, i.e., that an agent can never be left by an agent that is part of a coalition which she joins after time $t_0$.
For the second step, we will now define a potential function that is bounded from below by $0$, integer-valued, and strictly decreasing in every step $t\ge t_1$.
Therefore, fix an agent~$i\in N$ and define $A_i = \{j\in N\colon j\textnormal{ abandons } i \textnormal{ after time }t_0\}$.
Given $t\ge t_0$, we have to distinguish two cases. If $i$ already performed a deviation after time $t_0$, then let $d_i(t) = \max\{t_0\le t'\le t\colon d^{t'} = i\}$ be the last time that $i$ performed a deviation between $t_0$ and $t$.
In this case, define $P_i(t) = \{C\subseteq N\setminus A_i \colon i \in C, u_i^t(C) > u_i^t(\pi^{d_i(t)})\}$.
Otherwise, set $P_i(t) = 2^{N\setminus A_i}$. Note that $P_i(t)$ contains all coalitions which $i$ could \emph{potentially} form through a deviation after time $t$. Define the potential $\Lambda(t) = \sum_{j\in N}|P_j(t)|$.
We observe that $P_i(t+1) = P_i(t)$ if $i\neq d^{t+1}$.
Assume now that $i = d^{t+1}$.
If the first deviation of $i$ occurs at time~$t$, then $P_i(t+1)\subseteq P_i(t)\setminus\{\pi^t(i)\}$.
Otherwise, it must hold that $\pi^t(i) = \pi^{d_i(t)}(i)$, i.e., $i$ is part of the same coalition in step $t$ to which it deviated in step $d_i(t)$, which is the last deviation performed by $i$.
Indeed, due to the second step, no agent that was present when $i$ joined $\pi^{d_i(t)}(i)\setminus\{i\}$ can have left and~$i$ is not allowed to leave if any agent from $N\setminus \pi^{d_i(t)}(i)$ is still present.
Also, agent $i$'s utilities for agents in $N\setminus A_i$ have not changed since her last deviation and therefore $u^t_i(j) = u^{d_i(t)}(j)$ for all $j\in N\setminus A_i$. Thus, $i$ derives the same utility from $\pi^t(i)$ and $\pi^{d_i(t)}(i)$.
It follows that $P_i(t+1)\subseteq P_i(t)\setminus\{\pi^t(i)\}$.
Consequently, in each case, $\Lambda(t + 1) < \Lambda(t)$. As $\Lambda(t)\ge 0$ for all $t\ge t_1$, the dynamics can run for at most $\Lambda(t_1)$
steps after time $t_1$. This completes the proof.
\end{proof}
As $\mathit{AS}$ and $\mathit{MF}$ satisfy enemy domination (\Cref{prop:axioms}), \Cref{thm:resent:NS-IR-converges} implies that the individually rational NS dynamics converges in ASHGs and MFHGs for resentful agents.
However, we do not know under which conditions resent is sufficient to guarantee convergence for arbitrary (not necessarily individually rational) NS dynamics.
In this case, our proof for \Cref{thm:resent:NS-IR-converges} no longer works because it is possible that agents join coalitions for which they have an arbitrarily low utility (if the utility for their abandoned coalition was even worse).
In fact, slightly counterintuitive, there is a non-trivial example of a cycling NS dynamics in an MFHG for resentful agents.
\begin{restatable}{theorem}{mfhgresent}
\label{th:mfhg-resent}
The NS dynamics may cycle in MFHGs for resentful agents.
\end{restatable}
\begin{proof}
We now describe an involved example of an MFHG together with an infinite periodic sequence of NS deviations for resentful agents.
We construct this example in a way such that each agent leaves every other agent exactly once in each cycle.
This establishes that the agents' preference between relevant coalitions is \emph{maintained}: if a deviating agent prefers a joined coalition $C_1$ to an abandoned coalition $C_2$
before (and during) the \emph{first} execution of the cycle, then it still prefers $C_1$ to $C_2$ before (and during) \emph{each} execution of the cycle.
\begin{table}
\caption{Example from \Cref{th:mfhg-resent}. Utilities after $x$ cycles of deviations. Each row depicts the utility that one agent has for the other agents.} \label{table:mfhg-resent}
\centering
\begin{tabular}{ c|c|c|c|c|c|c }
& $a$ & $a'$ & $b$ & $b'$ & $c$ & $c'$ \\ \hline
$a$ & $-$ & $20-x$ & $10-x$ & $230-x$ & $0-x$ & $230-x$ \\ \hline
$a'$ & $110-x$ & $-$ & $30-x$ & $120-x$ & $30-x$ & $100-x$ \\ \hline
$b$ & $0-x$ & $230-x$ & $-$ & $20-x$ & $10-x$ & $230-x$ \\ \hline
$b'$ & $30-x$ & $100-x$ & $110-x$ & $-$ & $30-x$ & $120-x$ \\ \hline
$c$ & $10-x$ & $230-x$ & $0-x$ & $230-x$ & $-$ & $20-x$ \\ \hline
$c'$ & $30-x$ & $120-x$ & $30-x$ & $100-x$ & $110-x$ & $-$
\end{tabular}
\end{table}
Consider the game with agent set $N = \{a,a',b,b',c,c'\}$ and utilities as depicted in \Cref{table:mfhg-resent}. The initial utilities result from setting $x = 0$ in \Cref{table:mfhg-resent}.
Note that the utility values are not chosen to be minimal but simply in a way that it can easily be verified that deviations are indeed NS deviations.
We now present an infinite sequence $(\pi^t)_{t\ge 0}$ of partitions, always consisting of three coalitions.
For each partition, we refer to the first listed coalition as $C_1$, to the second as $C_2$, and the third as $C_3$.
For the sake of clarity, for each partition, we also specify which agent deviates to which coalition in the next step.
Specifically, for $n\geq 0$, we have
\begin{itemize}
\item $\pi^{18n+1}=\{\{b',a'\},\{a\},\{c',c,b\}\}$ with agent $b$ deviating to $C_1$,
\item $\pi^{18n+2}=\{\{b',a',b\},\{a\},\{c',c\}\}$ with agent $c$ deviating to $C_1$,
\item $\pi^{18n+3}=\{\{b',a',b,c\},\{a\},\{c'\}\}$ with agent $a'$ deviating to $C_3$,
\item $\pi^{18n+4}=\{\{b',b,c\},\{a\},\{c',a'\}\}$ with agent $a'$ deviating to $C_2$,
\item $\pi^{18n+5}=\{\{b',b,c\},\{a,a'\},\{c'\}\}$ with agent $c$ deviating to $C_2$,
\item $\pi^{18n+6}=\{\{b',b\},\{a,a',c\},\{c'\}\}$ with agent $b'$ deviating to $C_3$,
\item $\pi^{18n+7}=\{\{b\},\{a,a',c\},\{c',b'\}\}$ with agent $c$ deviating to $C_3$,
\item $\pi^{18n+8}=\{\{b\},\{a,a'\},\{c',b',c\}\}$ with agent $a$ deviating to $C_3$,
\item $\pi^{18n+9}=\{\{b\},\{a'\},\{c',b',c,a\}\}$ with agent $b'$ deviating to $C_2$,
\item $\pi^{18n+10}=\{\{b\},\{a',b'\},\{c',c,a\}\}$ with agent $b'$ deviating to $C_1$,
\item $\pi^{18n+11}=\{\{b,b'\},\{a'\},\{c',c,a\}\}$ with agent $a$ deviating to $C_1$,
\item $\pi^{18n+12}=\{\{b,b',a\},\{a'\},\{c',c\}\}$ with agent $c'$ deviating to $C_2$,
\item $\pi^{18n+13}=\{\{b,b',a\},\{a',c'\},\{c\}\}$ with agent $a$ deviating to $C_2$,
\item $\pi^{18n+14}=\{\{b,b'\},\{a',c',a\},\{c\}\}$ with agent $b$ deviating to $C_2$,
\item $\pi^{18n+15}=\{\{b'\},\{a',c',a,b\},\{c\}\}$ with agent $c'$ deviating to $C_1$,
\item $\pi^{18n+16}=\{\{b',c'\},\{a',a,b\},\{c\}\}$ with agent $c'$ deviating to $C_3$,
\item $\pi^{18n+17}=\{\{b'\},\{a',a,b\},\{c,c'\}\}$ with agent $b$ deviating to $C_3$, and
\item $\pi^{18n+18}=\{\{b'\},\{a',a\},\{c,c',b\}\}$ with agent $a'$ deviating to $C_1$.
\end{itemize}
Then, it is possible to verify that for $k\ge 1$, $\pi^{k-1}$ leads to $\pi^k$ by means of an NS deviation. Hence, we have presented an MFHG with an infinite sequence of NS deviations for resentful agents.
\end{proof}
This result indicates that some condition like aversion to enemies is probably needed for establishing a convergence guarantee for general NS dynamics; however, it remains open whether such a result is possible (even for ASHGs).
Notably, this question for {\cafs} satisfying aversion to enemies is the same as asking whether a CNS dynamics may cycle: For resentful agents in case of a cycling NS dynamics, there is also a cycling CNS dynamics.
\begin{restatable}{proposition}{NSvCNS}
\label{prop:resent-CNS-vs-NS}
For resentful agents with {\cafs} satisfying aversion to enemies, every sequence of NS deviations contains only finitely many deviations that are not CNS deviations.
\end{restatable}
\begin{proof}
Let a hedonic game $(N,u^0)$ with resentful agents be given
where every agent $i\in N$ has a {\caf}~$A_i$ that satisfies aversion to enemies.
Furthermore,
assume that there exists an infinite sequence $(\pi^t)_{t\ge 0}$ of partitions resulting from NS deviations of resentful agents.
By \Cref{lem:infoccurence}, there exists a time $t_0\ge 0$ such that every deviation performed after $t_0$ must occur infinitely often.
Define $\mathcal L = \{(i,j)\in N^2 \colon i \textnormal{ left by } j \textnormal{ after time }t_0\}$, i.e., the set of pairs of such agents.
Let $(i,j)\in \mathcal L$.
Then, there exists a time $t(i,j)\ge t_0$ such that $i$ was left by $j$ for at least $\lfloor u^{t_0}_i(j)\rfloor + 1$ times after time $t_0$ and before time $t(i,j)$.
Consider the time $t_1 = \max\{t(i,j)\colon (i,j)\in\mathcal L\}$. We claim that all deviations after time $t_1$ are CNS deviations. Indeed, assume that agent~$i$ is left by agent~$j$ at time $t\ge t_1$. By construction, as $t(i,j)\le t_1$, it holds that $u^t_i(j) < 0$.
Consequently, enemy monotonicity implies that $A_i(\pi^t,u_i^t)\le A_i(\pi^{t+1},u_i^t)$. Hence, every deviation after time $t_1$ is a CNS deviation.
Thus, there are only finitely many deviations
(at most $t_1$ many) that are not CNS deviations.
\end{proof}
\section{Dynamics for Appreciative Agents} \label{sec:apprec}
We now turn to analyzing the effects of appreciation on the convergence of different types of dynamics.
Here, as statements for general {\cafs} would require the introduction of (even) further axioms, we focus on $\mathit{AS}$ and $\mathit{MF}$ instead.
We start by establishing a close connection between cycling dynamics for resentful and appreciative agents in ASHGs, highlighting a close connection between the two studied models.
Subsequently, we analyze CS and (C)NS dynamics.
\subsection{From Resent to Appreciation}
We describe how we can transform certain types of infinite sequences of deviations for resentful agents to sequences for appreciative agents and vice versa.
We focus on ASHGs, yet believe that similar statements can hold for other classes of hedonic games. We start with Nash stability.
\begin{restatable}{theorem}{resentappreciation}
\label{thm:NS-resent-vs-appreciation-ASHG}
The following statements are equivalent:
\begin{enumerate}
\item There exists an ASHG admitting an infinite and periodic sequence of NS deviations for resentful agents.
\item There exists an ASHG admitting an infinite and periodic sequence of NS deviations for appreciative agents.
\end{enumerate}
\end{restatable}
The idea to prove \Cref{thm:NS-resent-vs-appreciation-ASHG} is to reverse a periodic fragment of an infinite sequence and to appropriately adjust the initial utilities.
This essentially reverses the roles of resent and appreciation, as the agents that an agent $a$ leaves in the sequence for resentful agents correspond to the agents $a$ joins in the sequence for appreciative agents.
The formal proof is quite technical and we defer it to the appendix.
By \Cref{prop:resent-CNS-vs-NS}, \Cref{thm:NS-resent-vs-appreciation-ASHG}
can be extended to also include infinite and periodic sequences of CNS deviations for resentful agents.
In fact, the equivalence can be extended even further,
as we show that in ASHGs with appreciative agents,
the question whether there is a cycling NS dynamics is
equivalent to asking for a cycling IS dynamics.
The proof idea for the next statement is that in every infinite sequence of NS deviations,
there exists a certain time step from which on
agent $a$ has a positive utility for each agent $b$ that joins $a$
(because $b$ has already joined $a$ sufficiently often).
\begin{restatable}{proposition}{ISvNS}
\label{obs:appreciation-IS-vs-NS}
For appreciative agents in ASHGs
every sequence of NS deviations contains only finitely many deviations that are not IS deviations.
\end{restatable}
\begin{proof}
Let an ASHG $(N,u^0)$ with appreciative agents be given.
Furthermore,
assume that there exists an infinite sequence $(\pi^t)_{t\ge 0}$ of partitions resulting from NS deviations.
By \Cref{lem:infoccurence}, there exists a time $t_0$ such that every deviation performed after $t_0$ occurs infinitely often.
Define $\mathcal L = \{(i,j)\in N^2 \colon i \textnormal{ is joined by } j \textnormal{ after time }t_0\}$.
Let $(i,j)\in \mathcal L$.
Then, there exists a time $t(i,j)\ge t_0$ such that $i$ was joined by $j$ for at least $\lceil |u^{t_0}_i(j)|\rceil + 1$ times after time $t_0$ and before time $t(i,j)$.
Consider the time $t_1 = \max\{t(i,j)\colon (i,j)\in\mathcal L\}$. We claim that all deviations after time $t_1$ are IS deviations. Indeed, assume that agent~$i$ is joined by agent~$j$ at time $t\ge t_1$. By construction, as $t(i,j)\le t_1$, it holds that $u^t_i(j) > 0$.
Consequently, agent $i$ prefers $\pi^{t+1}$ to $\pi^t$.
Hence, every deviation after time $t_1$ is an IS deviation.
Thus, there are only finitely many deviations
(at most $t_1$ many) that are not IS deviations.
\end{proof}
To sum up, combining \Cref{thm:NS-resent-vs-appreciation-ASHG} and \Cref{obs:appreciation-IS-vs-NS,prop:resent-CNS-vs-NS}, we get the following equivalences.
\begin{corollary}\label{co:equivalence}
The following statements are equivalent:
\begin{enumerate}
\item There exists an ASHG admitting an infinite and periodic sequence of CNS deviations for resentful agents.
\item There exists an ASHG admitting an infinite and periodic sequence of NS deviations for resentful agents.
\item There exists an ASHG admitting an infinite and periodic sequence of NS deviations for appreciative agents.
\item There exists an ASHG admitting an infinite and periodic sequence of IS deviations for appreciative agents.
\end{enumerate}
\end{corollary}
\subsection{Convergence for Appreciative Agents}
We now give an overview under which circumstances appreciation is (not) sufficient to guarantee convergence in MFHGs and ASHGs.
In contrast to resent, appreciation is not sufficient to guarantee convergence of CS dynamics.\footnote{For ASHGs,
the next statement can be extended to an ASHG
where initial valuations are symmetric by slightly modifying the game
presented by \citet[Figure 2]{ABS11c}.}
\begin{restatable}{theorem}{appreciativecore}
\label{th:appreciative-core-cylce}
The individually rational CS dynamics may cycle in ASHGs and MFHGs for appreciative agents.
\end{restatable}
\begin{proof}
Let $N=\{a,b,c\}$ be the set of agents and let the agents' initial utilities be as follows:
$$u^0_a(b)=u^0_b(c)=u^0_c(a)=4, \ \ u^0_a(c)=u^0_b(a)=u^0_c(b)=1.$$
Let $\pi^0=\{\{a\},\{b\},\{c\}\}$ and for $t>0$, let
\[
\pi^t =
\begin{cases}
\{\{a,c\},\{b\}\}, & \text{if } t\bmod 3 = 0 \\
\{\{a,b\},\{c\}\}, & \text{if } t\bmod 3 = 1 \\
\{\{a\},\{b,c\}\}, & \text{if } t\bmod 3 = 2.
\end{cases}
\]
We claim that $(\pi^t)_{t\geq 0}$ is an infinite sequence, where for every $t\geq 1$, $\pi^t$ evolves from $\pi^{t-1}$ by a core deviation of coalition $C^t$.
Specifically, we have
\[
C^t =
\begin{cases}
\{a,c\}, & \text{if } t\bmod 3 = 0 \\
\{a,b\}, & \text{if } t\bmod 3 = 1 \\
\{b,c\}, & \text{if } t\bmod 3 = 2.
\end{cases}
\]
Thus in each cycle of length three, each agent performs exactly one core deviation with any other agent. Thus, for $t\geq 0$ with $t\bmod 3 = 0$ it holds that
$$u^t_a(b)=u^t_b(c)=u^t_c(a)=\frac{2}{3}t+4$$ and $$u^t_a(c)=u^t_b(a)=u^t_c(b)=\frac{2}{3}t+1\text{.}$$
Thus, for each $t>0$, it holds that $u^t_a(b)>u^t_a(c)$, $u^t_b(c)>u^t_b(a)$, and $u^t_c(a)>u^t_c(b)$, implying that each of the deviations $C^t$ for $t>0$ is a core deviation if each agent $i\in N$ aggregates utilities according to $\mathit{AS}_i$ or $\mathit{MF}_i$.
\end{proof}
However, in the games considered in \Cref{th:appreciative-core-cylce},
there exists an execution of the CS dynamics that converges.
This raises the (open) question whether a converging execution of the CS dynamics exists for every initial state in ASHGs and MFHGs for appreciative agents.
Lastly, we consider IS and (C)NS dynamics.
In ASHGs for appreciative agents,
it remains open whether IS and NS dynamics may cycle.
In fact, we have seen in \Cref{obs:appreciation-IS-vs-NS} that these two questions are equivalent and in \Cref{co:equivalence} that they are very closely related to our open questions concerning resentful agents. On the other hand, for CNS, appreciation is sufficient to guarantee convergence.
\begin{restatable}{theorem}{apprecCNS}
\label{thm:apprec-CNS}
The CNS dynamics converges in ASHGs for appreciative agents.
\end{restatable}
\begin{proof}
Let an ASHG $(N,u^0)$ be given and consider an execution $(\pi^t)_{t\ge 0}$ of the CNS dynamics. Assume for contradiction that the dynamics is infinite. By \Cref{lem:infoccurence}, there exists $t_0\ge 0$ such that every deviation performed at time $t\ge t_0$ is performed infinitely often.
Now, consider an agent $i$ that joins a coalition $C$ containing agent $j$ at some time $t\ge t_0$.
We claim that it is impossible that $j$ ever joins a coalition containing agent~$i$ after time $t_0$.
For the contrary, assume that this happens, and therefore happens infinitely often.
Then, since agent~$i$ and agent~$j$ join each other infinitely often, there exists a time $t'\ge t_0$ such that $u^{t}_j(i) > 0$ and $u^{t}_i(j) > 0$ for all $t\ge t'$. Some time after $t'$, the agents~$i$ and $j$ will be in a joint coalition, again.
Then, to perform the deviation again where $i$ joins $C$, the two agents have to be dissolved, i.e., one of them has to leave the other.
However, since they by now have positive utility for each other, each of them would block the other agent from leaving according to the additively separable {\caf}. Hence, this cannot happen, a contradiction.
Consequently, agent~$j$ cannot join a coalition containing $i$ after time $t_0$.
Thus, the utilities of an agent $i$ for agents in coalitions which she joins by a deviation are not affected after time $t_0$ by appreciation.
Therefore, there exists a global constant $U$ such that the maximum utility of any agent obtained after any deviation is $U$. We derive a contradiction by showing that some agent has to abandon a coalition of unbounded utility.
To this end, we prove the following claim.
\begin{claim}
There exists an agent $i$ that abandons a coalition $C$ containing an agent $j$ that joins $i$ at some point during the dynamics.
\end{claim}
\renewcommand\qedsymbol{$\vartriangleleft$}
\begin{proof}
Assume for contradiction that no such agent exists. To derive a contradiction, we will construct an infinite sequence of coalitions increasing in utility with respect to the utility at time $t_0$. This cannot happen, because the number of coalitions an agent can be part of (and therefore the number of different utility values that an agent can achieve at a fixed time) is bounded.
We claim that there exists an agent $d\in N$ and a sequence of coalitions $(C_k)_{k\ge 0}$ such that for every $k\ge 1$, the following two conditions hold:
\begin{enumerate}
\item $d$'s utility with respect to time $t_0$ is strictly increasing, i.e., $u^{t_0}_d(C_k) > u^{t_0}_d(C_{k-1})$.
\item The coalition $C_k$ is formed by a deviation of agent $d$.
\end{enumerate}
Consider the first agent $d$ performing a deviation after time $t_0$, where $d$ abandons coalition $C_0$ to form coalition $C_1$.
Then, $u^{t_0}_d(C_1) > u^{t_0}_d(C_0)$. Hence, we have found the first step of the sequence.
Now, assume that we have constructed a sequence $(C_k)_{k=0}^m$ which satisfies the two conditions.
We know that $C_m$ is formed by a deviation of agent~$d$. Consider the next time $\hat t$ where some agent $e\in C_m$ leaves the coalition $C$ containing $C_m$ (which must happen, because the dynamics is infinite).
If $e \neq d$, then we derive a contradiction to our initial assumption because $e$ then leaves a coalition containing an agent, namely agent~$d$, that joined her by a deviation.
Hence, $e = d$. If there exists an agent $f\in C\setminus C_m$, then we again derive a contradiction because $f$ must have joined $d$ at some point.
This implies that $C = C_m$.
Set $C_{m+1}$ to the coalition joined by agent~$d$.
Then, $C_{m+1}$ clearly fulfills the second condition. Also, $u^{t_0}_d(C_{m+1}) = u^{\hat t}_d(C_{m+1}) > u^{\hat t}_d(C) = u^{\hat t}_d(C_m) = u^{t_0}_d(C_m)$.
In the first and last equality, we use that appreciation does not affect the utilities for agents joined by agent $d$ after time $t_0$. Hence, also the first condition is fulfilled. As such a sequence of coalitions cannot exist, we derive a contradiction, and the claim must hold.
\end{proof}
Now, consider an agent~$i$ that abandons a coalition $C$ containing an agent $j$ that joins $i$ at some point during the dynamics.
Since the deviation where agent~$j$ joins $i$ happens infinitely often, there exists a time $T\ge t_0$ such that $u^t_i(j)\ge U - \sum_{l\in C\setminus \{j\}}u^{t_0}_i(l)$ for all $t\ge T$.
Consider the next time $T'\ge T$ where~$i$ abandons $C$ to form some coalition $D$.
Then, $u^{T'}_i(D) \le U \le u^{T'}_i(j) + \sum_{l\in C\setminus \{j\}}u^{t_0}_i(l) \le u^{T'}_i(C)$.
In the last inequality, we use that the utility of $i$ for other agents can only have increased since time $t_0$ (because of appreciation). Hence, this deviation was not beneficial for~$i$. This is a final contradiction showing that an infinite dynamics cannot exist.
\renewcommand\qedsymbol{$\square$}
\end{proof}
We proved in \Cref{th:mfhg-resent} that NS dynamics may cycle in MFHGs for resentful agents.
``Reversing'' this sequence and appropriately adjusting the initial utilities leads to a cycling NS dynamics for appreciative agents.
We defer the details to the appendix.
\begin{restatable}{theorem}{mfhgapprec}
\label{th:mfhg-apprec}
The individually rational NS dynamics may cycle in MFHGs for appreciative agents.
\end{restatable}
It remains open whether IS dynamics may cycle in MFHGs for appreciative agents.
Note that the arguments from \Cref{obs:appreciation-IS-vs-NS} for showing the ``equivalence'' for IS and NS dynamics under appreciation do not work for~MFHGs.
\section{Dynamics with Resentful Deviatiors}\label{sec_dev-resent}
Previously, we have assumed that a deviation of an agent $a$ changes the utility other agents have for $a$.
In contrast, one could also consider what happens if a deviation of $a$ changes $a$'s utility for other agents.
Under deviator-resent, we assume that an agent decreases her utility for all agents she abandons.
Formally, if for some $t\ge 1$, $\pi^t$ evolves from $\pi^{t-1}$ via a
single-agent deviation of agent $k\in N$,
then for \emph{deviator-resentful} agents, for $i,j\in N$, $u_i^t(j)$ arises from $u_i^{t-1}(j)$ as
\[u_i^t(j) = \begin{cases}
u_i^{t-1}(j) -1 & i= k, j\in \pi^{t-1}(i)\setminus \{i\},\\
u_i^{t-1}(j) & \text{else.}\\
\end{cases}\]
Similarly, for deviator-resentful agents, if for $t\ge 1$, $\pi^t$ evolves from $\pi^{t-1}$ via a group deviation of $C\subseteq N$, then, for $i,j\in N$, $u_i^t(j)$ arises from $u_i^{t-1}(j)$ as
\[u_i^t(j) = \begin{cases}
u_i^{t-1}(j) -1 & i\in C, j\in \pi^{t-1}(i)\setminus C,\\
u_i^{t-1}(j) & \text{else.}\\
\end{cases}\]
In addition to the axioms introduced in \Cref{se:prelims}, we also define two more axioms that are only relevant for the results in this section.
These are weak conditions about friends.
\begin{itemize}
\item \emph{friend necessity} (FN) if,
for all
coalitions $C\in \mathcal{N}_i$
and utility vectors $u_i\in \mathbb Q^n$,
$A_i(C,u_i) > 0$ implies that there exists $j\in C\setminus\{i\}$ with $u_i(j) > 0$. In other words, an agent can only have a positive utility for a coalition if it contains a friend.
\item \emph{single friend desire} (SFD) if,
for all
coalitions $C\in\mathcal{N}_i$,
agents $j\in C\setminus\{i\}$, and utility vectors $u_i\in \mathbb Q^n$ such $u_i(j)>0$ and $u_i(k)\leq 0$ for all $k\in C\setminus \{j\}$, it holds that $A_i(C, u_i) > A_i(C\setminus \{j\}, u_i)$. In other words, a coalition to which exactly one friend belongs is strictly preferred to the same coalition without this friend.
\end{itemize}
We show that additively separable and modified fractional utility aggregation satisfies these axioms.
\begin{proposition}\label{prop:allaxioms}
The additively separable {\caf} $\mathit{AS}_i$ and the modified fractional {\caf} $\mathit{MF}_i$ satisfy FN and SFD.
\end{proposition}
\begin{proof}
FN holds because a sum (or a sum divided by a positive number) can only be positive if some summand is positive.
SFD holds for the additively separable aggregation because a sum gets larger when adding a positive number.
SFD holds for the modified fractional aggregation because a negative fraction gets larger when adding a positive number to the numerator while the denominator increases.
\end{proof}
\subsection{Contractual Nash Stability and Nash Stability}
An intuitive reason why deviator-resent can contribute to the convergence of dynamics is that, after agent $a$ abandons a coalition $C$, $a$'s utility for $C$ decreases and thus $a$ is less likely to join $C$ again.
However, deviator-resent does not resolve the run-and-chase example, implying that NS dynamics may cycle for a wide variety of hedonic games with deviator-resentful agents.
Indeed, consider the dynamics between two agents $a$ and $b$ where initially $a$ has utility $1$ for $b$ and $b$ initially has utility $-1$ for $a$.
Then, $a$ will still always join $b$ in one step, while $b$ leaves $a$ in the next step (thereby decreasing $b$'s utility for $a$ even further).
\begin{observation}
The NS dynamics may cycle for deviator-resentful agents whose {\cafs} satisfy friend necessity and single friend desire.
\end{observation}
By \Cref{prop:allaxioms} this implies that the NS dynamics may cycle in ASHGs and MFHGs.
Moreover, somewhat surprisingly, also CNS dynamics may still cycle in ASHGs and MFHGs with deviator-resentful agents, even if deviations are restricted to be
individually rational.
Notably, this is in a clear contrast to our previous results for resentful agents where individual rationality was for all types of dynamics sufficient to guarantee convergence.
\begin{proposition}\label{prop:CNSaIRcycle}
The individually rational CNS dynamics may cycle in MFHGs and ASHGs for deviator-resentful agents.
\end{proposition}
\begin{proof}
Consider a cardinal hedonic game with $N = \{a,b,c\}$
where the initial single-agent utilities are given as $u_a(b) = u_b(c) = u_c(a) = 0$ and $u_b(a) = u_c(b) = u_a(c) = -1$.
For $k \ge 0$, let $\pi^{3k} = \{\{a,b\},\{c\}\}$, $\pi^{3k+1} = \{\{a\},\{b,c\}\}$, and $\pi^{3k + 2} = \{\{a,c\},\{b\}\}$.
Then, $(\pi^k)_{k\ge 0}$ represents an individually rational CNS dynamics with respect to additively separable and modified fractional utility aggregation.
\end{proof}
It is possible to modify the previous examples to start a dynamics from the singleton partition.
In contrast to this, as soon as we enforce that agents only deviate to a non-singleton coalition if they strictly prefer it to being in a singleton coalition, convergence can be guaranteed.
\begin{proposition} \label{prop:dev-resent:CNS-converges}
The \mbox{CNS} dynamics converges for deviator-resentful agents whose {\cafs} satisfy friend necessity and single friend desire if agents only deviate to non-singleton coalitions if they strictly prefer them to being in a singleton.
\end{proposition}
\begin{proof}
Let a hedonic game $(N,u^0)$ with deviator-resentful agents be given
where every agent $i\in N$ has a {\caf}~$A_i$ that satisfies friend necessity and single friend desire.
Assume for the sake of contradiction that there exists an infinite sequence $(\pi^t)_{t\ge 0}$ of partitions resulting from CNS deviations of deviator-resentful agents where agents only deviate to non-singleton coalitions if they strictly prefer them to being in a singleton.
By \Cref{lem:infoccurence}, there exists a time $t_0\ge 0$ such that every deviation performed after $t_0$ must occur infinitely often.
This implies in particular that there is a step $t'_0\ge t_0$ such that an agent $i$ has a negative utility for all agents that $i$ leaves at some point after $t'_0$.
Now, let us fix a time step $t'\geq t'_0$ where some agent $d$ deviates into a non-singleton coalition.
As every deviation is repeated (infinitely often) after $t_0\leq t'$, there has to be some time step where $d$ deviates again.
In particular, let $t''$ be the smallest $t$ with $t>t'$ where $d$ deviates again after time $t'$.
For some time step $t$, let $C_{t}:=\pi^{t}(d)$ be the coalition of $d$ after step $t$.
We now examine the coalitions $C_{t'},\dots, C_{t''-1}$, i.e., the coalitions $d$ is part of between her two deviations.
As we assume that an agent only deviates into a non-singleton coalition if she strictly prefers it to being in a singleton coalition, $d$ prefers $C_{t'}$ to being in a singleton.
Hence, by friend necessity, there is an agent $a\in C_{t'}$ for which $d$ has positive utility at time $t' - 1$.
By single friend desire, it follows that there is an agent $a\in C_{t''-1}$ for which $d$ has a positive utility. Indeed, otherwise, there is some $t\in [t',t''-2]$ such that there is a friend of $d$ in $C_t$ but not in $C_{t+1}$. However, this cannot happen because, due to single friend desire, $d$ strictly prefers $C_t$ to $C_{t+1}$, implying that $d$ would have vetoed the deviation taking place in time step $t+1$.
This implies that there is at least one agent for which $d$ has positive utility in $C_{t''-1}$.
However, $d$ leaves this agent in time step $t''$.
This contradicts our initial assumption that each agent has a negative utility for all agents they leave in some step after $t'_0\leq t'\leq t''$.
\end{proof}
As the {\cafs} $\mathit{AS}_i$ and $\mathit{MF}_i$ satisfy friend necessity and single friend desire (cf. \Cref{prop:allaxioms}), \Cref{prop:dev-resent:CNS-converges} implies that, for every ASHG and MFHG with deviator-resentful agents, some execution of the CNS dynamics converges.
\subsection{Core Stability and Individual Stability}
We now turn to the consent-based stability concepts individual stability and (strict) core stability.
Here, the influence of deviator-resent is more profound.
\subsubsection{Individual Rationality}
We start by considering individually rational SCS dynamics. Here, like for resentful agents, convergence is guaranteed for a wide class of CAFs.
\begin{proposition}\label{thm:dev-resent:SCS-IR-converges}
The individually rational SCS, CS, and IS dynamics converge for deviator-resentful agents whose CAFs satisfy enemy domination.
\end{proposition}
\begin{proof}
We show the statement for SCS deviations, which implies convergence of CS and IS dynamics.
Let a hedonic game $(N,u^0)$ with deviator-resentful agents be given
where every agent $i\in N$ has a {\caf}~$A_i$ that satisfies enemy domination.
Assume for the sake of contradiction that there exists an infinite sequence $(\pi^t)_{t\ge 0}$ of partitions resulting from SCS deviations of deviator-resentful agents.
By \Cref{lem:infoccurence}, there exists a time $t_0\ge 0$ such that every deviation performed after $t_0$ must occur infinitely often.
We first show that if two agent $i$ and $j$ perform a core deviation together at some point after $t_0$, then $i$ cannot leave $j$ nor can $j$ leave $i$ after $t_0$.
We prove that $i$ cannot leave $j$ (the other case is symmetric).
By enemy domination, there exists a constant $c(u^{t_0}_i,j)$ such that for all utility vectors $u'_i \in \mathbb Q^n$ with $u'_i(k) \le u^{t_0}_i(k)$ for all $k\in N$ and $u'_i(j)\le c(u^{t_0}_i,j)$, it holds for every $C\in \mathcal{N}_i$ with $j\in C$ that $A_i(C, u'_i) < A_i(\{i\},u'_i)$.
As each deviation after $t_0$ occurs infinitely often, the fact that $i$ leaves $j$ after $t_0$ infinitely often implies that there exists a time $t_1\ge t_0$ such that agent $i$ leaves agent~$j$ for $u^{t_0}_i(j) - c(u^{t_0}_i,j)$ times between time $t_0$ and time $t_1$.
Since agent~$i$ is deviator-resentful, this implies that $u^{t_1}_i(j) \le c(u^{t_0}_i,j)$.
Additionally, deviator-resentful agents can only decrease utilities for other agents.
Therefore, it holds for all $t\ge t_0$ and $k\in N$ that $u^t_i(k) \le u^{t_0}_i(k)$.
Consequently, from the definition of $c(u^{t_0}_i,j)$ it follows that agent~$i$ cannot deviate to form a coalition together with $j$ after $t_1$, because this deviation would not be individually rational.
However, such a deviation takes place because we have assumed that $i$ and $j$ deviate together at some point after $t_0$ and such a deviation is performed infinitely often.
This establishes that $i$ and $j$ cannot leave each other after $t_0$.
Finally, consider some time $t\geq t_0$ in which a coalition $C_t$ performs a group deviation.
Then, from our above observation we get that no agent that is part of $C_t$ can ever leave another agent that is part of $C_t$ after this, implying that $\pi^{t'}(j)\subseteq C_t$ for all $j\in C_t$ and $t'\geq t$.
This implies that the size of $C_t$ needs to monotonically increase over time.
Notably, this holds for all coalitions that ever performed a deviation after time $t_0$.
Yet the overall number of agents is bounded, resulting in a contradiction.
\end{proof}
As $\mathit{AS}_i$ and $\mathit{MF}_i$ satisfy enemy domination (\Cref{prop:allaxioms}), \Cref{thm:dev-resent:SCS-IR-converges} implies that the individually rational SCS, IS, and CS dynamics converge in ASHGs and MFHGs for deviator-resentful agents.
\subsubsection{Absence of Individual Rationality}
If we drop the requirement that deviations are individual rational, the picture changes.
For MFHGs, IS, CS, and SCS dynamics may cycle.
\begin{proposition}\label{prop:dev-recISycle-frac}
The IS, CS, and SCS dynamics may cycle in MFHG for deviator-resentful agents, even when starting from the singleton partition.
\end{proposition}
\newcommand{\alpha}{\alpha}
\newcommand{\beta}{\beta}
\newcommand{\gamma}{\gamma}
\begin{proof}
\begin{figure}
\centering
\begin{tikzpicture}[
element/.style={shape=circle,draw, fill=white}
]
\pgfmathsetmacro\unit{4}
\node[element] (a) at (0,0) {$a$};
\node[element] (c) at (\unit,0) {$c$};
\node[element] (b) at (0.5*\unit,0.75*\unit) {$b$};
\node[element] (1) at (-0.25*\unit,0.75*\unit) {$\alpha$};
\node[element] (2) at (1.25*\unit,0.75*\unit) {$\beta$};
\node[element] (3) at (0.5*\unit,-0.75*\unit) {$\gamma$};
\draw[->, bend right=15] (a) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $7$} (b);
\draw[->, bend right=15] (b) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $3-x$} (a);
\draw[->, bend right=15] (b) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $7$} (c);
\draw[->, bend right=15] (c) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $3-x$} (b);
\draw[->, bend right=15] (c) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $7$} (a);
\draw[->, bend right=15] (a) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $3-x$} (c);
\draw[->, bend right=15] (b) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $3-x$} (1);
\draw[->, bend right=15] (b) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $1-x$} (2);
\draw[->, bend right=15] (c) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $3-x$} (2);
\draw[->, bend right=15] (c) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $1-x$} (3);
\draw[->, bend right=15] (a) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $3-x$} (3);
\draw[->, bend right=15] (a) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $1-x$} (1);
\draw[->, bend right=15] (1) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $1$} (b);
\draw[->, bend right=15] (1) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $1$} (a);
\draw[->, bend right=15] (2) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $1$} (b);
\draw[->, bend right=15] (2) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $1$} (c);
\draw[->, bend right=15] (3) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $1$} (a);
\draw[->, bend right=15] (3) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt]
{\footnotesize $1$} (c);
\end{tikzpicture}
\caption{Example from \Cref{prop:dev-recISycle-frac}. Utilities after $x$ cycles of deviations. All missing edges indicate that the utilities of the agents for each other are zero.}\label{fig:dev-recISycle-frac}
\end{figure}
Consider the MFHG with agent set $N = \{a,b,c,d,e,f\}$ and utilities as depicted in \Cref{fig:dev-recISycle-frac}, where the number of an arc from agents $i$ to $j$ describes the utility that $i$ has for $j$. The initial utilities result from setting $x$ to $0$ in \Cref{fig:dev-recISycle-frac}.
Consider the following infinite sequence of partitions. For $n\geq 0$,
\begin{itemize}
\item $\pi^{3n} = \{\{\alpha,a,b\},\{\beta\},\{\gamma,c\}\}$,
\item $\pi^{3n+1} = \{\{\alpha,a\},\{\beta,b,c\},\{\gamma\}\}$, and
\item $\pi^{3n+2} = \{\{\alpha\},\{\beta,b\},\{\gamma,a,c\}\}$.
\end{itemize}
Note that the utilities of agents after $x$ executions of this cycle of three deviations are shown in \Cref{fig:dev-recISycle-frac}.
Observing that for $k\ge 1$, $\pi^{k-1}$ leads to $\pi^k$ by means of a (S)CS deviation completes the counterexample.
Note that we can also modify the dynamics to start in the singleton partition, by inserting the two partitions $\{\{\alpha\},\{\beta\},\{\gamma\}, \{a\},\{b\},\{c\}\}$ and $\{\{\alpha,a,b\},\{\beta\},\{\gamma\}, \{c\}\}$ in the beginning of the dynamics.
Using the same initial utilities, for IS deviations we have the following cycling sequence of partitions. For $n\geq 0$,
\begin{itemize}
\item $\pi^{6n} = \{\{\alpha,a,b\},\{\beta\},\{\gamma,c\}\}$,
\item $\pi^{6n+1} = \{\{\alpha,a,b\},\{\beta,c\},\{\gamma\}\}$,
\item $\pi^{6n+2} = \{\{\alpha,a\},\{\beta,b,c\},\{\gamma\}\}$,
\item $\pi^{6n+3} = \{\{\alpha\},\{\beta,b,c\},\{\gamma,a\}\}$,
\item $\pi^{6n+4} = \{\{\alpha\},\{\beta,b\},\{\gamma,a,c\}\}$, and
\item $\pi^{6n+5} = \{\{\alpha,b\},\{\beta\},\{\gamma,a,c\}\}$.
\end{itemize}
Again the utilities of agents after $x$ executions of this cycle of six partitions are shown in \Cref{fig:dev-recISycle-frac}.
We again observe that for $k\ge 1$, $\pi^{k-1}$ leads to $\pi^k$ by means of a IS deviation, which completes the counterexample.
Again we can also modify the example to start in a singleton partition by adding the three partitions $\{\{\alpha\},\{\beta\},\{\gamma\}, \{a\},\{b\},\{c\}\}$, $\{\{\alpha,a\},\{\beta\},\{\gamma\}, \{b\}, \{c\}\}$, $\{\{\alpha,a,b\},\{\beta\},\{\gamma\}, \{c\}\}$ in the beginning of the dynamics.
\end{proof}
By contrast, IS dynamics are still always guaranteed to converge in ASHG.
Note that this is the only contrast between ASHGs and MFHGs proven in this paper (in all other cases we either have the same result for both classes, or a result for one and an open question for the other).
\begin{theorem}
In ASHGs, the IS dynamics converges for deviator-resentful agents.
\end{theorem}
\begin{proof}
Let an ASHG $(N,u^0)$ be given.
For the sake of contradiction assume that there exists an infinite sequence $(\pi^t)_{t\ge 0}$ of partitions resulting from IS deviations of deviator-resentful agents.
For each $t\geq 0$, let $d^t$ be the agent deviating in step $t$ from $\pi^{t-1}(d^t)$ to $\pi^{t}(d^t)$.
By \Cref{lem:infoccurence}, there exists $t_0\geq 0$ such that every deviation performed after $t_0$ is performed infinitely often.
Note that for each $t\geq t_0$ it holds that $d^t$ cannot be left by an agent $j\in \pi^{t}(d^t)$ after $t_0$, as otherwise $j$ will leave $d^t$ infinitely often and thus, as utilities are only decreasing, at some point will no longer approve the join of $d^t$, as she derives negative utility from $d^t$.
We refer to this as the first observation.
Fix some $t\geq t_0$ and let $d:=d_t$ and $C:=\pi^{t}(d^t)$ (note that $d$ joins $C\setminus \{d^t\}$ at step $t$ ). As our second observation we now show that there is some $t'> t$ with $d^{t'}=d$ and $\pi^{t'-1}(d^t) = C$.
From our choice of $t_0$ it follows that there is some $t'\geq t$ where $d$ performs a deviation for the next time.
Assume now, for the sake of contradiction that there is some $t''$ with $t'> t''> t$ where $\pi^{t''}(d)\neq \pi^{t''-1}(d)$ and select the smallest such $t''$.
If $\pi^{t''}(d)$ is changed because an agent $j$ left it, then, by our choice of $t''$, it follows that $j\in C$, which contradicts our first observation.
If $\pi^{t''}(d)$ is changed because an agent $j$ joined it, then it needs to hold that $j$ leaves the coalition of $d$ again before $t'$:
Otherwise, $d$ leaves $j$ which again contradicts the first observation as $d$ needs to approve the join of $j$. Thus, the second observation follows.
However, the second observation implies that for $d$ it holds that $u_d^{t}(\pi^t(d))=u_d^{t'-1}(\pi^{t'-1}(d))$.
In the next step, $d$ performs an IS deviation and thus increases her utility, i.e., $u_d^{t'}(\pi^{t'}(d))>u_d^{t'-1}(\pi^{t'-1}(d))$.
Afterwards, the second observation can be applied again until $d$ performs the next deviation.
Thus, $d$'s utility is strictly increasing, however, as utilities are initially bounded and resent can only cause their decay, this leads to a contradiction. Hence, IS dynamics have to converge.
\end{proof}
We have seen that deviator-resent can be powerful force for stability, as CS dynamics with individual rational deviations in MFHGs and ASHGs and IS dynamics in ASHGs always converge.
However, deviator-resent is not sufficient to guarantee convergence of IS and general CS dynamics in MFHGs, yielding a different behavior of ASHGs and MFHGs for IS dynamics.
Notably, we did not prove any such contrasts in our analysis of resent and appreciation.
Overall, our results indicate that deviator-resent has clear ramifications on convergence guarantees, yet the general picture seems to be slightly more nuanced than for resent or appreciation.
In particular, we were not able to settle whether SCS or CS dynamics are guaranteed to converge in ASHG for deviator-resentful agents without the individual rationality assumption, leaving this as an open question.
\section{Simulations}\label{app:simulations}
In this section, we analyze by means of simulations how resent and appreciation influence dynamics in ASHGs.
We focus on NS dynamics, as in randomly sampled ASHGs the IS dynamics typically converge quickly even without resent or appreciation (implying that they have only a small effect).
Moreover, executing core dynamics is computationally too costly, as already checking whether an outcome is core stable is computationally intractable.
\subsection{Setup}
We mostly focus on ASHGs with an agent set $\ag$ containing $n=50$ agents,\footnote{We analyze the influence of the number of agents in \Cref{sub:varying_n}.} and sample their utilities using one of the following two models:
\begin{description}
\item[Uniform] For two agents $a, b\in \ag$ with $a\neq b$, we sample $u_a(b)$, i.e., $a$'s value for $b$, by drawing a random integer between $-100$ and $100$.
\item[Gaussian] For each agent $a\in \ag$, we sample her \emph{base qualification} $\mu_a$ by drawing a random integer between $-100$ and $100$.
For two agents $a, b\in \ag$ with $a\neq b$, we sample $u_a(b)$ by drawing an integer from the Gaussian distribution with mean $\mu_b$ and standard deviation $10$.\footnote{We analyze the influence of the chosen standard deviation in \Cref{sub:varying_sig}.}
\end{description}
Our dynamics start with the singleton partition.
Subsequently, in each step, we compute all possible NS deviations.
If there are no NS deviations, we stop; otherwise, we sample one NS deviation uniformly at random and execute it.
To be able to vary the ``intensity''
of the resentful/appreciative perception, we introduce a change coefficient $c$, which we typically set to $1$:
For resentful agents, if an agent $a$ deviates from a coalition $C'$ to a coalition $C$, then we reduce the utility that agents from $C'$ have for $a$ by $c$; for appreciative agents, we increase the utility that agents from $C$ have for $a$ by $c$.
We also examine what happens if agents are both resentful and appreciative and both of the above described effects are present.
In this case we speak of resentful-appreciative agents.
For all our simulations, we set a time-out of $\num{100000}$, i.e., after $\num{100000}$ steps we report that the dynamics did not converge.\footnote{We want to remark that this does not necessarily imply that no NS stable outcome exists in such a game or that there is no path to stability for the dynamics, but rather that selecting NS deviations randomly was not sufficient to ensure convergence (in a reasonable time).}
\begin{figure*}[t!]
\centering
\begin{subfigure}[t]{0.4\textwidth}
\centering
\resizebox{0.8\textwidth}{!}{\input{./plots/Nash_random_indiv.tex}}
\caption{Uniform utilities}\label{fig:change-coeff-random}
\end{subfigure}\qquad \qquad
\begin{subfigure}[t]{0.4\textwidth}
\centering
\resizebox{0.9\textwidth}{!}{\input{./plots/Nash_gauss_indiv.tex}}
\caption{Gaussian utilities}\label{fig:change-coeff-gauss}
\end{subfigure
\caption{Influence of the change coefficient on the average convergence time} \label{fig:change-coeff}
\end{figure*}
\subsection{Convergence Time}
We start by analyzing the influence of resent and of appreciation on how fast NS dynamics converge.
For this, we sampled $100$ games with $50$ agents and for each recorded the number of steps until convergence.
\paragraph{Uniform Utilities}
In \Cref{fig:change-coeff-random}, we visualize the results for uniform utilities.
The NS dynamics for agents that are neither resentful nor appreciative did not converge in any of our sampled games (within the limit of $\num{100000}$ steps).
By contrast, even for a change coefficient $c=1$, NS dynamics converged in all games for resentful or appreciative agents.
However, there is a clear difference between these two:
For resentful agents, the average number of steps until convergence is $\num{59910}$ for $c=1$, whereas for appreciative agents the NS dynamics converges much faster (for $c=1$ the average convergence time is $\num{4243}$).
Increasing $c$ to $4$, for resentful agents and for appreciative agents, the average convergence time roughly quarters, while increasing $c$ to $10$ only decreases the time by an additional factor of two.
In sum, appreciation seems more helpful to establish fast convergence than resent in case of uniform utilities.
Nevertheless, for both concepts, the number of steps until convergence is quite large (compared to the number of agents).
While increasing the change coefficient leads to faster convergence the decrease in convergence time is particularly strong for smaller values of the coefficient, indicating that NS dynamics need some time to find the ``right'' deviations somewhat independent of the value of the change coefficient.
In contrast to our theoretical analysis, we also consider the case of resentful-appreciative agents.
Compared to appreciative agents, adding resent leads to a substantial increase of the convergence time by a factor of around $2.5$ (while for resentful agents, adding appreciation still leads to faster convergence).
While this slower convergence for resentful-appreciative agents compared to appreciative agents may be surprising at first glance, recall the intuitive justifications why resent and appreciation contribute to a faster convergence.
For appreciative agents, utilities only increase over time, whereas for resentful agents utilities only decrease over time.
Thus, if we combine the two, it is in principle possible that some valuations that increase for appreciative agents stay constant for resentful-appreciative agents, and the two effects can cancel out each other.
For uniform utilities, this effect seems to be stronger than the additional ``stability force'' established by resent.
\paragraph{Gaussian Utilities}
In \Cref{fig:change-coeff-gauss}, we visualize the result of our first set of simulations for Gaussian utilities.
In this case, the NS dynamics for agents that are neither resentful nor appreciative converged in $3$ of the $100$ games.
In contrast, for resentful or for appreciative agents, the NS dynamics converged in all games.
In particular, convergence was much quicker (in at most $\num{2000}$ steps) than under uniform utilities, indicating that ASHGs under Gaussian utilities seems to facilitate reaching stable states compared to uniform utilities.
Examining the results in more detail, the difference between resentful and appreciative agents is less profound here than for uniform utilities.
While resent leads to faster convergence for $c<3$, appreciation is more powerful for $c\geq 3$.
Considering the influence of the change coefficient, for resentful agents, we again see the trend that increasing the change coefficient has a strong effect for smaller $c$ but that this effect becomes less strong for larger $c$.
On the other hand, for appreciative agents, the relation between $c$ and the convergence time is rather linear.
Moreover, in contrast to uniform utilities, resent and appreciation seem to not ``cancel out'' each other.
For resentful-appreciative agents, NS dynamics converge faster than for either of the two separately.
\begin{table*}[t!]\centering
\caption{Properties of different dynamics and the produced outcomes for different ASHGs. For an explanation of the table, we refer to the beginning of \Cref{subsec:structural}.}\label{table:experiment}
\begin{adjustbox}{max width=\textwidth}
\begin{tabular}{@{}llllllllllllll@{}}
\toprule
&
\multicolumn{1}{c}{} &
\phantom{a}&
\multicolumn{3}{c}{coalition sizes} &
\phantom{a}&
\multicolumn{2}{c}{stability in original} &
\phantom{a} &
\multicolumn{3}{c}{utilities}
\\
\cmidrule{4-6}
\cmidrule{8-9}
\cmidrule{11-13}
& steps && number & avg. size & max size && \# ag. IR viol & \# ag. NS dev && avg. util & avg. change & pos. vals
\\
\midrule
\makebox[-1pt][l]{\textbf{Uniform utilities $\mathbf{n=50}$} }\\
resent & 60055.0 && 50 & 1.0 & 1 && 0 & 50 && 0.0 & -51.25 & 0.0 \\
apprec & 4309.0 && 2.74 & 19.31 & 42.57 && 18.7 & 22.21 && 589.39 & 12.8 & 0.56 \\
resent+apprec & 15261.0 && 5.26 & 9.73 & 18.43 && 2.33 & 10.15 && 237.08 & -0.13 & 0.51
\\
\midrule
\makebox[-1pt][l]{\textbf{Gaussian utilities $\mathbf{n=50}$} }\\
resent & 968.0 && 25.74 & 1.99 & 25.2 && 0 & 5.07 && 626.3 & -0.42 & 0.49 \\
apprec & 1226.0 && 21.69 & 2.36 & 25.19 && 3.67 & 5.11 && 638.79 & 0.6 & 0.51 \\
resent+apprec & 694.0 && 24.64 & 2.07 & 25.28 && 0.61 & 4.66 && 637.34 & -0.12 & 0.5 \\
\midrule
\midrule
\makebox[-1pt][l]{\textbf{Gaussian utilities $\mathbf{n=25}$} }
\\
resent & 282.0 && 13.62 & 1.91 & 12.36 && 0 & 2.11 && 291.49 & -0.49 & 0.48 \\
apprec & 438.0 && 11.92 & 2.2 & 12.29 && 1.76 & 2.24 && 296.59 & 0.77 & 0.5 \\
resent+apprec & 208.0 && 13.32 & 1.95 & 12.42 && 0.18 & 1.97 && 297.54 & -0.12 & 0.49 \\
\midrule
\makebox[-1pt][l]{\textbf{Gaussian utilities $\mathbf{n=25}$ with stable outcome (13 games)} }
\\
original & 100.38 && 12.46 & 2.15 & 13.54 && 0 & 0 && 344.26 & 0.0 & 0.52 \\
resent & 90.69 && 12.46 & 2.15 & 13.54 && 0 & 0 && 343.14 & -0.16 & 0.52 \\
apprec & 92.77 && 12.31 & 2.24 & 13.54 && 0.15 & 0.15 && 348.78 & 0.29 & 0.52 \\
resent+apprec & 100 && 12.46 & 2.15 & 13.54 && 0 & 0 && 347.82 & -0.05 & 0.52\\
\bottomrule
\end{tabular}
\end{adjustbox}
\end{table*}
\subsection{Structure of Outcomes and Comparison to Base Game} \label{subsec:structural}
We now take a closer look at the outcomes and utility functions produced by NS dynamics for resentful and/or appreciative agents.
Again, we generated $100$ games with $n=50$ agents each for uniform and Gaussian utilities.
In addition, we generated $100$ games with $n=25$ agents and Gaussian utilities (as the original NS dynamics converge more often in such games).
In all games, we set the change coefficient $c$ to $1$.
\Cref{table:experiment} summarizes the results of our simulations.
All values in the table are averaged from the respective $100$ games.
In the last part of the table, we only consider the $13$ games with $n=25$ and Gaussian utilities in which an NS dynamics in the original game converged within \num{100000} steps.
For reference, we depict the number of steps the dynamics needed to converge in the first column.
We analyze the structure of the produced NS outcomes as follows. Columns three to six consider the produced coalitions, that is, the number of coalitions and their average and maximum size.
The next two columns concern the outcome's degree of stability with respect to the original utilities, where we record the number of agents violating individual rationality and possessing an NS deviation, respectively.
The last three columns concern the change of the utility profile, that is, the average utility in the outcome partition with respect to the final utilities, the average change of each entry of the utility function comparing the initial and final utilities, and the fraction of pairs of friends with respect to the final utilities, that is tuples $(a,b)\in \ag^2$ for which $u_a(b) > 0$.\footnote{Note that, in both utility models, this value is on average $0.5$ for the initial utilities.}
\paragraph{Uniform Utilities}
We first focus on uniform utilities. Recall that our dynamics need many steps until reaching convergence.
Therefore, it is not surprising that the produced outcomes are quite ``degenerated'' for both resentful agents and appreciative agents.
For resentful agents, the produced outcomes consist only of singleton coalitions in all games, which means that agents have left each other sufficiently often to ensure that all pairwise utilities are non-positive.
This is also reflected by the facts that all agents have NS deviations with respect to their original utilities, and that on average the valuations of agents changed by $51.25$.
Overall, the produced outcomes have little connection to the original game and simply exploit that all utilities become negative at some point for resentful agents.
By contrast, for appreciative agents, there is typically one large coalition containing $40$ or more agents together with one or two small coalitions.
Indeed, this is also reflected by the observations that the average number of coalitions is $2.74$ and the average maximum size is $42.57$.
The typical run of an NS dynamics for appreciative agents here can be described in two phases. First, agents increase their utility for each other by deviating between smaller coalitions (where some agents, which are negatively valued by many others, are not joined, which often leads to them being part of small coalitions in the final outcome).
Subsequently, in a second phase, agents already possess a generally high utility level, and thus tend to favor large coalitions (even when having a negative utility for some of the agents in the coalition).
Notably, it does not happen that eventually all utilities between pairs of agents are positive, and in this sense, the behavior of appreciative agents is not the contrary of the behavior of resentful agents.
In fact, slightly counterintuitively, only $56\%$ of agent pairs have a positive evaluation after convergence of the dynamics.
Consequently, agents (from the large coalition) often dislike other coalition members:
On average, an agent only values $59\%$ of her coalition members positively.
Nevertheless, the relationship of the produced outcome and the agent's original utilities is still quite low with $18.7$ agents for which individual rationality is violated and $22.21$ agents having an NS deviation.
For resentful-appreciative agents, the produced outcomes are in some sense between the two extremes for resentful agents and for appreciative agents:
Typically, several medium-size coalitions form (the average number of coalitions is $5.26$ and the maximum size is on average $18.43$).
Further, the average change of the utility values is $-0.13$ and only $51\%$ of agent pairs have a positive evaluation, implying that the utility changes caused by resent and by appreciation cancel out each other from an aggregated perspective.
However, on an individual level, utilities still change quite drastically, as the absolute difference between the initial utilities values and the values at the end of the dynamic is on average $12.15$.
Notably, the outcome produced by resentful-appreciative agents is also in some sense less ``degenerated'' as for the the two separately:
It consists of medium-size coalitions, utilities are structurally more similar to the initial utilities, and most importantly, the outcome is closer to stability in the original game (with only $2.33$ agents for which individual rationality is violated and only $10.15$ agents having an NS deviation).
\paragraph{Gaussian Utilities}
We now turn to Gaussian utilities, where the dynamics converge much quicker than for uniform utilities.
Moreover, the outcomes produced by our three dynamics are quite similar, which follows the intuition that the final utility profiles remain quite similar after the execution of ``few'' steps.
In general, NS outcomes produced by our dynamics typically consist of one large coalition containing roughly half of the agents (these are usually the agents with positive ground qualification), while other agents are placed into coalitions of size one or two.
Let us first focus on the second and third part of \Cref{table:experiment} presenting the results of $100$ games with $n=50$ and $n=25$ agents, respectively.
First, the outcomes for appreciative agents typically contain fewer coalitions than for resentful agents.
Interestingly, this is not achieved because of the size of the ``large'' coalition but due to a larger average size of the many small coalitions.
For resentful-appreciative agents, the produced outcomes are structurally similar to the ones for resentful agents with a slightly smaller number of coalitions (achieved by an increase of the size of the ``large'' coalition).
Second, for all three types of dynamics the produced outcomes are much closer to being stable in the original game than for uniform utilities (only around $10\%$ of the agents have an NS deviation).
In particular, for resentful-appreciative agents, the produced outcomes are closest to stability in the original game.
Lastly, considering the average utility of agents in the produced outcome, the three perception types produce quite similar results:
Naturally, for appreciative agents, the average utility of agents in the produced outcome is highest.
However, in both other dynamics, agents are only slightly less happy.
In the fourth part of the table, we depict statistics concerning the $13$ of our $100$ games with $n=25$ agents having Gaussian utilities for which an original NS dynamic converged (in the time limit).
In the first line, we show properties of the outcomes produced by the original dynamics.
The NS outcomes produced by the original NS dynamics are structurally quite similar to the ones shown in the third part of the table, indicating that the outcomes produced by our three dynamics on games with $25$ or $50$ agents having Gaussian utilities are quite ``natural'' and not degenerated.
The similarities become even more profound when comparing the outcomes produced by the original dynamics on the selected $13$ games to the outcomes produced by our three types of dynamics on the same $13$ games:
For resentful and resentful-appreciative agents,
the produced outcomes are very similar or even identical to the outcome produced by the original NS dynamics in all $13$ games (and are in particular always stable in the original games).
For appreciative agents, the ``large'' coalition in the outcome is typically quite similar or identical to the ``large'' coalition produced by the original dynamics; however, sometimes fewer small coalitions are produced (in particular, some of the produced outcomes are not stable in the original game).
Concerning the average utility in the final partition, resentful agents are only marginally less happy than in the original dynamics, indicating that only very few agents end up in a coalition with an agent they left at some point, whereas the average utility is slightly higher for appreciative agents and resentful-appreciative agents.
\begin{figure}[t]
\centering
\resizebox{0.4\textwidth}{!}{\input{./plots/Nash_gauss_indiv50sigma_comp.tex}}
\caption{Influence of the standard deviation of Gaussian utilities on the average convergence time. We only take into account dynamics converging within the time limit of $\num{100000}$ steps. For resentful agents, the NS dynamics did not converge in $7/23/48/63/75$ games for a standard deviation of $60/70/80/90/100$, respectively (for appreciative agents and for resentful-appreciative agents the dynamics always converged).} \label{fig:varying-sigma}
\end{figure}
\subsection{Influence of Standard Deviation for Gaussian Utilities}\label{sub:varying_sig}
In this section, we focus on Gaussian utilities and analyze the influence of the standard deviation $\sigma$ on convergence times.
Recalling the drastic differences in the behavior of the dynamics between Gaussian utilities (with $\sigma=10$) and uniform utilities observed in the previous subsections, it is to be expected that the convergence time increases with increasing $\sigma$ (as we are in some sense getting closer to uniform utilities for larger $\sigma$).
To analyze this effect in more detail, for $\sigma\in \{0,5,10,\dots, 95,100\}$, we sampled $100$ games with $n=50$ agents having Gaussian utilities with standard deviation $\sigma$, and measured the average convergence times of our three types of NS dynamics for a change coefficient $c=1$.
The results are shown in \Cref{fig:varying-sigma}, where we only show the average convergence time of all dynamics that converged in the time bound of $\num{100000}$ steps.
For resentful agents, the NS dynamics did not converge in $7/23/48/63/75$ games for a standard deviation of $60/70/80/90/100$, respectively (for appreciative agents and resentful-appreciative agents the dynamics always converged).
Overall, our hypothesis that increasing the standard deviation leads to an increased convergence time is confirmed clearly.
Slightly unexpected, for $\sigma\geq 80$, Gaussian utilities seem to be even ``harder'' than uniform utilities:
For resentful agents, the dynamics did not even converge for roughly half of the games and for appreciative agents the average convergence time is about twice as large.
The reason for this is that for large $\sigma$ utilities often fall out of the range $[-100,100]$ (from which we sample the agent's base qualification for Gaussian utilities and the utilities for uniform utilities).
In games which are ``far away'' from stability and for which resentful agents or appreciative agents produce degenerated outcomes (as described in the previous section) an increased range of the utility values clearly contributes to a higher convergence time:
For instance, for resentful agents, we have observed that the dynamics typically runs until all utility values are negative, which takes more time if some utility values are initially larger.
\subsection{Influence of the Number of Agents} \label{sub:varying_n}
We now briefly analyze the influence of the number of agents on the convergence time of NS dynamics with resentful and/or appreciative agents.
For this, for different numbers of agents, we generated $100$ games and executed NS dynamics with resentful and/or appreciative agents and a change coefficient of $c=1$.
We show the results for uniform utilities in \Cref{fig:varying_n-Uniform} and the results for Gaussian utilities in \Cref{fig:varying_n-Gauss}.
Overall, unsurprisingly, the higher the number of agents, the higher is the convergence time of our dynamics.
\begin{figure*}
\centering
\begin{subfigure}[t]{0.4\textwidth}
\centering
\resizebox{0.8\textwidth}{!}{\input{./plots/Nash_random_indivn_comp.tex}}
\caption{Uniform utilities}\label{fig:varying_n-Uniform}
\end{subfigure}~
\begin{subfigure}[t]{0.4\textwidth}
\centering
\resizebox{0.87\textwidth}{!}{\input{./plots/Nash_gauss_indivn_comp.tex}}
\caption{Gaussian utilities}\label{fig:varying_n-Gauss}
\end{subfigure
\caption{Influence of the number of agents on the average convergence time.}
\end{figure*}
For uniform utilities, the relation of the different types of dynamics is independent of the number of agents.
For appreciative agents, the average convergence time is the lowest, while
convergence is still faster for resentful agents than for resentful-appreciative agents.
The increase in the convergence time between $n=10$ and $n=60$ is almost linear for all three types.
However, the slope substantially depends on the considered type:
For resentful agents, comparing $n=10$ and $n=60$, the convergence time increases by a factor of $47$, for appreciative agents the factor is $11$, and for resentful-appreciative agents the factor is $38$.
Thereby, the difference between the three becomes larger with a growing number of agents.
This again highlights the different nature of the three types of NS dynamics for uniform utilities that we have observed above:
For resentful agents, for uniform utilities, all utility values need to become negative, which requires substantially, but linearly, more deviations the higher the number of agents.
In contrast, for appreciative agents, agents typically only join each other until almost everyone has a positive valuation for a very large coalition.
Naturally also this requires more deviations the higher the number of agents, yet with slower scaling.
For Gaussian utilities, we also see an almost linear increase of the average convergence time.
Moreover, for most considered agent numbers, dynamics for resentful-appreciative agents converge faster than the ones for resentful agents which in turn converge faster than the ones for appreciative agents.
However, in contrast to uniform utilities, here the difference between the three types of NS dynamics changes only slightly for different numbers of agents.
Furthermore, comparing $n=10$ and $n=60$, the convergence time of all three types of NS dynamics only increases by a factor of around $12$.
Lastly, for resentful agents, we can observe a slightly unexpected phenomenon, as for a smaller number of agents the convergence time does not steadily increase, e.g., for $n=10$ the average converge time is $425$ steps and for $n=15$ it is $204$ steps.
\section{Shortest Converge Sequences} \label{app:shortest}
In our simulations in \Cref{app:simulations}, we have analyzed how fast random executions of NS dynamics converge for resentful and/or appreciative agents.
An interesting related direction to shed further light on the power of resent and appreciation is to analyze the length of the \emph{shortest} converging execution of dynamics.
The corresponding computational problem is to decide whether in a given game (where a stable outcome is guaranteed to be reachable), there is a converging deviation sequence of a given length from some given starting partition.
Notably, this problem has not been addressed in the literature for classical dynamics, yet is of no less relevance in the general case.
While existing hardness results for deciding whether a game admits a stable outcome suggest the hardness of the shortest converge sequence problem for the general case, they do not directly imply hardness, as stable states might not be reachable from some initial partition via the allowed deviations.
Moreover, convergence might require exponential time from some initial partition \citep{BBT22a}.
We present three reductions showing that for ASHGs deciding whether we can converge in a given number of steps is NP-hard
for CS, IS, CNS, and NS dynamics for resentful, for appreciative, and for classical agents (that is, agents with constant utility functions over time).
More formally, for $\alpha\in \{NS,IS,CNS,CS\}$, we define the following decision problem:
\smallskip
\begin{center}
{\small
\begin{tabularx}{1.0\columnwidth}{ll}
\toprule
\multicolumn{2}{c}{\sc{resentful-ashg-$\alpha$-sequence}} \\
\midrule
{\bf Given:}& \parbox[t]{0.7\columnwidth}{
An additively separable hedonic game
with resentful agents and some integer~$k$.
\vspace*{1mm}} \\%[5mm]
{\bf Question:}& \parbox[t]{0.7\columnwidth}{
Is there an execution $(\pi^t)_{t\ge 0}$ of the $\alpha$ dynamics
that
starts from the singleton partition $\pi^0$
and
converges in at most $k$ steps?
\vspace*{.5mm}} \\
\bottomrule
\end{tabularx}
}
\end{center}
\smallskip
Defining {\sc appreciative-ashg-$\alpha$-sequence}
analogously
for appreciative agents,
we can show that these problems are
$\NP$-hard for NS, IS, CNS, and CS.
\begin{restatable}{theorem}{sequence}
\label{thm:sequence}
For $\alpha\in \{NS,IS,CNS,CS\}$, {\sc resentful-} and {\sc appreciative-ashg-$\alpha$-sequence} are $\NP$-hard.
\end{restatable}
Before turning to the proof of \Cref{thm:sequence}, we want to make a few remarks.
First, note that all our constructions in the following proofs
also work for normal agents with constant utilities over time.
Hence, our constructions also imply the hardness
of the respective decision problem for (time-independent) ASHGs.
Second, we want to discuss membership in $\NP$.
Note that the sequence of partitions leading to a stable partition is a certificate for a Yes-instance of size $\mathcal O(nk)$.
Hence, if $k$ is given in unary encoding, then this is a certificate of polynomial size.
Moreover, for the reduced instance in our proofs, it holds that $k\in \mathcal O(n)$, and therefore the hardness holds on a class of instances for which membership in $\NP$ is satisfied. Still, it is not clear whether {\sc resentful-} and {\sc appreciative-ashg-$\alpha$-sequence} are in $\NP$ for a general $k$ in binary encoding.
The proof of \Cref{thm:sequence} consists of three individual constructions.
We showcase the technique by proving the statement for NS and IS in \Cref{thm:sequence-NS-IS}.
The proofs for CNS and CS are similar, and are deferred to \Cref{thm:sequence-CNS,thm:sequence-CS} in the appendix.
\begin{lemma}\label{thm:sequence-NS-IS}
For $\alpha\in \{NS,IS\}$, {\sc resentful-} and {\sc appreciative-ashg-$\alpha$-Sequence} are $\NP$-hard.
\end{lemma}
\begin{proof}
We first show the statement for IS and resentful agents.
We reduce from \textsc{Restricted Exact Cover by 3-Sets (RX3C)} where we are given a finite universe $U=\{x_1,\dots, x_{3t}\}$ and a family $\mathcal{S}=\{S_1,\dots , S_{3t}\}$ of $3$-subsets of $U$ where each element from $U$ appears in exactly three sets from~$\mathcal{S}$.
The question is whether there is a family $\mathcal{S}'\subseteq \mathcal{S}$ which is an exact cover of $U$.
\textbf{Construction.}
Given
an instance $(U,\mathcal S)$ of \textsc{RX3C}, we
set $k=10t$ and
create the following additively separable hedonic game.
We add one \emph{element agent} $x$ for each element $x\in U$ and one \emph{set agent} $S$ for each set $S\in \mathcal{S}$. Moreover, we add $2t$ \emph{filling agents} $F=\{f_1,\ldots,f_{2t}\}$. Lastly, we add a penalizing gadget
consisting of $10t+1$ \emph{penalizing agents}
$\{p\}\cup Q$ with $Q=\{p_{i,j}\mid i\in[5t],j\in [2]\}$.
The resulting set of agents is $N=U\cup \mathcal{S}
\cup F \cup \{p\}\cup Q$.
The initial utilities of the players
are illustrated in Figure~\ref{fig:sequence-NS-IS}:
\begin{itemize}
\item Each element agent has utility zero for each other element agent and
utility~$1$ for each set agent.
\item Each filling agent has utility~$1$ for each set agent.
\item Each set agent $S\in \mathcal{S}$ has
utility $20t$ for the three element agents $x\in S$,
utility $60t$ for each filling agent,
utility~$60t$ for~$p$, and
utility zero for each penalizing agent in $Q$.
\item $p$ has
utility $10t$ for each set agent and
utility zero for each penalizing agent in $Q$.
\item Each penalizing agent $p_{i,j}\in Q$
has utility $30t$ for each set agent,
utility $30t$ for $p$,
utility $40t$ for her corresponding penalizing agent $p_{i,k}$ with $k\in [2], k\neq j$, and
utility zero for all remaining penalizing agents in $Q$.
\item All not explicitly mentioned utilities are $-1000t$.
\end{itemize}
\begin{figure}
\centering
\begin{tikzpicture}[
element/.style={shape=circle,draw, fill=white}
]
\pgfmathsetmacro\xdist{2}
\pgfmathsetmacro\ydist{-1}
\node (x1) at (0,0.4*\ydist) {${x_1}$};
\node (x3t) at (0,1.6*\ydist) {${x_{3t}}$};
\node at (barycentric cs:x1=1,x3t=.7) {$\vdots$};
\node (xphan) at (0,2.1*\ydist) {\phantom{${x_{3t}}$}};
\node (S1) at (\xdist,0.4*\ydist) {$S_1$};
\node (S3t) at (\xdist,1.6*\ydist) {$S_{3t}$};
\node at (barycentric cs:S1=1,S3t=.7) {$\vdots$};
\node (Sphan) at (\xdist,1.8*\ydist) {\phantom{$S_{3t}$}};
\node (Sphan2) at (0.9*\xdist,1.6*\ydist) {\phantom{$S_{3t}$}};
\node (f1) at (2*\xdist,0.4*\ydist) {$f_{1}$};
\node (f2t) at (2*\xdist,1.6*\ydist) {$f_{2t}$};
\node at (barycentric cs:f1=1,f2t=.7) {$\vdots$};
\node (fphan) at (2*\xdist,1.8*\ydist) {\phantom{$f_{2t}$}};
\node (p) at (1*\xdist,3.5*\ydist) {$p$};
\node (p11) at (-2,3*\ydist) {$p_{1,1}$};
\node (p12) at (0,3*\ydist) {$p_{1,2}$};
\node (p5t1) at (-2,4*\ydist) {$p_{5t,1}$};
\node (p5t2) at (0,4*\ydist) {$p_{5t,2}$};
\node (dotsp1) at (barycentric cs:p11=1,p5t1=.7) {$\vdots$};
\node (dotsp2) at (barycentric cs:p12=1,p5t2=.7) {$\vdots$};
\node (E) [draw, dashed, rounded corners=3pt, fit={(x1) (x3t)}] {};
\node at (x1) [above=0.35cm] {\footnotesize$0$};
\node (E) [draw, dashed, rounded corners=3pt, fit={(p11) (p5t2)}] {};
\node at (p11) [above=0.35cm] {\footnotesize$0$};
\draw[<->] (p11) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt, above] {\footnotesize $40t$} (p12);
\draw[<->] (p5t1) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt, above] {\footnotesize $40t$} (p5t2);
\draw[<->] (p5t1) edge (p5t2);
\draw[->, bend right=15] (p12) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt] {\footnotesize $30t$} (Sphan2);
\draw[->, bend right=15] (Sphan2) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt] {\footnotesize $0$} (p12);
\draw[->, bend right=15] (dotsp2) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt] {\footnotesize $30t$} (p);
\draw[->, bend right=15] (p) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt] {\footnotesize $0$} (dotsp2);
\draw[->, bend right=30] (Sphan) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt] {\footnotesize $60t$} (p);
\draw[<-,bend left=30] (Sphan) edge
node[fill=white,anchor=center, pos=0.5, inner sep =2pt] {\footnotesize $10t$} (p);
\draw[->] (0.2,0.65*\ydist) -- (0.8*\xdist,0.65*\ydist) node[fill=white,anchor=center, pos=0.5, inner sep =2pt] {\footnotesize $1$};
\draw[<-] (0.2,1.35*\ydist) -- (0.8*\xdist,1.35*\ydist) node[fill=white,anchor=center, pos=0.5, inner sep =2pt, above] {\footnotesize $20t$}
node[fill=white,anchor=center, pos=0.5, inner sep =2pt, below] {\footnotesize $x\in S$};
\draw[<-] (1.2*\xdist,0.8*\ydist) -- (1.8*\xdist,0.8*\ydist) node[fill=white,anchor=center, pos=0.5, inner sep =2pt] {\footnotesize $1$};
\draw[->] (1.2*\xdist,1.2*\ydist) -- (1.8*\xdist,1.2*\ydist) node[fill=white,anchor=center, pos=0.5, inner sep =2pt] {\footnotesize $60t$};
\end{tikzpicture}
\caption{Scheme of the additively separable hedonic games in \Cref{thm:sequence-NS-IS}.
All omitted utilities are $-1000t$.\label{fig:sequence-NS-IS}}
\end{figure}
We now show that there is an exact cover of $U$
if and only if there is a sequence starting with the singleton partition and reaching an IS partition after at most $k$ IS deviations, where agents are resentful.
{\bfseries ($\Rightarrow$)}
Given an exact cover $\mathcal{S}'\subseteq \mathcal{S}$, we let the agents deviate as follows.
For each $S\in \mathcal{S}\setminus \mathcal{S}'$, one filling agent deviates to $S$ (there are $2t$ of these sets and $2t$ filling agents).
For each $S\in \mathcal{S}'$, the three element agents $x$ with $x\in S$ deviate to~$S$.
As $\mathcal{S'}$ is an exact cover, each filling and each element agent deviate exactly once, leading to $5t$ deviations so far.
Furthermore, for $i\in[5t]$,
$p_{i,2}$ deviates to $p_{i,1}$.
Thus, we have $10t$ deviations in total.
If we order these deviations arbitrarily, then all deviations are NS deviations, as each agent deviates from the singleton coalition to a coalition for which she has positive utility.
Furthermore, these NS deviations are IS deviations as the agents
in the joined coalitions
have non-negative utilities for the deviators.
It remains to show that the resulting partition is NS (and thus also IS):
Observe that there is at most one set agent per coalition.
As element and filling agents only derive a positive utility from set agents and are in a coalition with a set agent, no element or filling agent has an NS deviation.
Agent~$p$ only has a positive utility for the set agents but
all set agents are accompanied by either element or filling agents
for which $p$ has a large negative utility.
Hence, $p$ has no NS deviation.
Agents $p_{i,1}$ and $p_{i,2}$ with $i\in[5t]$
do not want to deviate as they
have utility $40t$ for coalition $\{p_{i,1},p_{i,2}\}$ and value no other available coalition with more than $30t$.
Lastly, each set agent $S\in \mathcal{S}$ is in a coalition from which she derives utility $60t$.
All other coalitions are either the coalition just containing
$p$ (for which $S$ has utility $60t$ as well), coalitions containing other penalizing agents (for which $S$ has utility zero), or contain a different set agent (for which $S$ has large negative utility).
Thus, $S$ has no NS deviation either and the created partition is NS.
{\bfseries ($\Leftarrow$)}
Assume that we have a sequence of $\ell\leq k=10t$ IS deviations leading from the singleton partition $\pi^0$ to an IS partition $\pi^{\ell}$.
As a first observation, note that
in this sequence
no two agents who have utility $-1000t$ for each other can ever be
in the same coalition because they would never join each other.
Second, as we start from the singleton partition, the resent an agent has build up for the
other agents after $\ell$ deviations sums up to at most $\frac{\ell}{2}\leq 5t$.
Next, we show that,
in $\pi^{\ell}$, no set agent is in a joint coalition with~$p$.
For the sake of a contradiction,
assume that $p\in \pi^{\ell}(S)$ for some $S\in\mathcal{S}$.
By the first observation, this means that there is no other set agent,
no element agent, and no filling agent in $\pi^{\ell}(S)$.
Hence $\pi^{\ell}(S)\subseteq \{p,S\}\cup Q$.
Let $p_{i,j}\in Q$ be a penalizing agent who has not
performed any deviation, yet.
This agent has to exist because, otherwise, we would have needed at least $10t+1$ deviations to reach $\pi^{\ell}$.
Then, $p_{i,j}$
has a utility of at least
$u_{p_{i,j}}^0(S)+u_{p_{i,j}}^0(p)-5t= 55t$
for $\pi^{\ell}(S)$
and thus has a possible NS deviation to~$\pi^{\ell}(S)$.
(As $p_{i,j}$ has not deviated yet,
she can have a utility of at most $40t$ for $\pi^{\ell}(p_{i,j})$
if $p_{i,k}$ with $k\in [2], k\neq j$ has joined her.)
This NS deviation is also an IS deviation as, initially,
no agent from~$\pi^{\ell}(S)$ has a negative utility for $p_{i,j}$.
This is a contradiction to $\pi^{\ell}$ being~IS.
So, $\pi^{\ell}(p)\subseteq \{p\}\cup Q$.
As $\pi^{\ell}$ is IS, no set agent $S$ has any possible IS deviation
from $\pi^{\ell}(S)$ to $\pi^{\ell}(p)$.
As $p$ and all other penalizing agents would always allow $S$ to join her (note that they cannot have decreased their utility by more than $5t$ for $S$ until step $\ell$), $S$ has no NS deviation to join $\pi^{\ell}(p)$.
Since
(a) the resent that $S$ has build up for any agent sums up to at most $-5t$,
(b) $S$ initially has utilities zero for all penalizing agents $p_{i,j}\in \pi^{\ell}(p)$,
(c) $S$ initially has utility $60t$ for $p$, and
(d) $S$ does not want to move to $p$,
it follows that
$u^{\ell}_S(\pi^{\ell}(S))\geq 60t -5t=55t$.
Therefore, $\pi^{\ell}(S)$ contains at least one filling agent or three element agents $x$ with $x\in S$.
Since this holds for all set agents
and no two set agents are in one coalition,
the existence of an exact cover
(namely $\mathcal{S'}=\{S\in\mathcal{S}\mid S \textnormal{ is together with three element agents}\}$)
is implied.
By the same proof as above,
there is an exact cover of~$U$
exactly if there is a sequence of at most~$k$ NS deviations
leading to an NS partition for resentful agents.
For appreciative agents, we can use the same construction.
The proof of correctness is very similar.
\end{proof}
\section{Conclusion and Future Directions}\label{sec:discussion}
We have initiated the study of hedonic games with time-dependent utility functions, which are influenced by deviations in the past.
In this course, we have studied a dynamic model of hedonic games by considering sequences of partitions evolving through sequences of deviations.
Whenever a deviation is performed, some of the agents influenced by this deviation modify their utility.
In particular, we have considered resentful agents, which decrease their utility for agents who abandon them,
and appreciative agents, which increase their utility for agents who join them.
In our theoretical analysis, we have investigated whether the resentful or appreciative perception of other agents is sufficient to guarantee convergence for dynamics based on various deviation types.
To state our results in broad generality, we have proposed axioms for utility aggregation.
These consider the treatment of friends and enemies.
All of our axioms are satisfied for additively separable aggregation of utilities, while modified fractional utility aggregation satisfies all axioms except aversion to enemies.
For resentful agents, we have shown the convergence of dynamics based on all types of group and single-agent deviations under fairly general conditions.
However, some of these results also need the individual rationality of deviations.
By contrast, for appreciative agents, we can only guarantee convergence of the CNS dynamics in ASHGs, while we have found several possibilities for cycling for the other types of dynamics.
Resent and appreciation do not need to be expressed by the agents affected by a deviation, but they may also affect the deviator herself.
We have seen that deviator-resent can be a strong force for stability over time.
Apart from our theoretical analysis, we have also studied the effects of resent and appreciation by means of simulations.
This gives insight in the actual running time of the dynamics as well as in the structure of the partitions obtained after the convergence of the dynamics.
We have considered two utility models, namely utilities selected uniformly at random and according to Gaussian distributions.
It turned out that the produced outcomes are fairly degenerate under uniformly random utilities.
For resentful agents, the outcome is usually the singleton partition, while the outcome consists of one large hub coalition and a few smaller coalitions for appreciative agents.
A compromise and a seemingly more realistic result is obtained if agents are affected by both resent and appreciation.
Then, the outcomes consist of several medium-size coalitions, and seem to be more related to the original base game.
By contrast, under Gaussian utilities, the differences of the outcomes for different agent types are much less profound, which suggests that results by simulations may highly depend on the creation of the random games.
We complement the simulation results on the running time by a theoretical consideration of the problem of convergence within a given time limit.
There, we obtain hardness results for dynamics in ASHGs based on any stability concept considered in this paper.
Notably, these hardness results not only hold for resentful and appreciative agents but also for for normal agents (with time-independent utilities).
Based on our work, one research direction is to consider other effects that could affect agents' valuations over time and potentially contribute to additional convergence results.
Apart from this, we have also posed several specific open questions throughout the paper (even showing the equivalence of some of them in \Cref{co:equivalence}).
In particular, it remains open, whether we can extend our convergence results for resentful agents to the modified fractional aggregation without the restriction to individually rational deviations.
There, we only know that we may cycle for general NS dynamics.
Moreover, complementing our simulations, it would be interesting to theoretically analyze the effects of combining resent and appreciation.
A concrete open question here is whether CS dynamics are guaranteed to converge, which is the case for resentful agents but not for appreciative agents.
Finally, another path for future research is to consider fastest convergence in other classes of hedonic games apart from ASHGs.
\section*{Acknowledgments}
This work was partially supported by the Deutsche Forschungsgemeinschaft under grants NI 369/22, BR 2312/11-2, and BR 2312/12-1, and the NRW project \emph{Online Participation}.
We would like to thank the participants of the Dagstuhl seminar 21331 on \emph{Coalition Formation Games}, and especially Florian Brandl, Gr\'egory Bonnet, Edith Elkind, Bettina Klaus, Seckin \"Ozbilen, and Sanjukta Roy, for fruitful discussions.
| {'timestamp': '2022-12-01T02:19:35', 'yymm': '2211', 'arxiv_id': '2211.17169', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17169'} | arxiv |
\subsection{Notations}
Throughout this manuscript, vectors are denoted in lower case bold and matrices are denoted in upper case bold, unless otherwise specified. Vectors of all ones and zeros are denoted by $\mathbbold{1}_n, \mathbbold{0}_n \in \real^n$, respectively. The identity matrix is denoted by $\bm{I}_n\in\real^{n\times n}$.
We use $\mathcal{N}(\bm{A})$ to denote the null space of matrix $\bm{A}$. Given $n$ matrices $\bm{M}_i, i=1,\cdots,n$, we denote $[\bm{M}_1;\cdots;\bm{M}_n]:=[\bm{M}_1^\top \cdots \bm{M}_n^\top]^\top$.
Given a discrete-time signal $\bm{z}(t)\in \mathbb{R}^d$ for $t=0,1,\cdots$, we
use $\bm{z}_{[k, k+T]}\in\real^{Td}$ to denote the vector form of the sequence $\{\bm{z}(k), \ldots, \bm{z}(k+T)\}$,
and the Hankel matrix $\bm{Z}_{i, t, N}\in\real^{td\times N}$ as
\vspace{-0.1cm}
$$
\bm{Z}_{[k, k+T]}=\left[\begin{array}{c}
\bm{z}(k) \\
\vdots \\
\bm{z}(k+T)
\end{array}\right],
\bm{Z}_{i, t, N}=\left[\begin{array}{cccc}
\bm{z}(i) & \bm{z}(i+1) & \cdots & \bm{z}(i+N-1) \\
\bm{z}(i+1) & \bm{z}(i+2) & \cdots & \bm{z}(i+N) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{z}(i+t-1) & \bm{z}(i+t) & \cdots & \bm{z}(i+t+N-2)
\end{array}\right],
$$
where $k,i$ and are integers, and $t, N, T $ are natural numbers. The first subscript of $\bm{Z}_{i, t, N}$ denotes the time at which the first sample of the signal is taken, the second one the number of samples per each column, and the last one the number of signal samples per each row.
\subsection{Problem formulation}\label{subsec: problem}
We consider a discrete-time linear time-invariant system
\vspace{-0.1cm}
\begin{equation}\label{eq:sys_full}
\begin{aligned}
\bm{x}(k+1) &=\bm{A} \bm{x}(k)+\bm{B} \bm{u}(k) \\
\bm{y}(k) &=\bm{C} \bm{x}(k)
\end{aligned}
\end{equation}
with state $\bm{x} \in \mathbb{R}^n$, action $\bm{u} \in \mathbb{R}^m$, and output $\bm{y} \in \mathbb{R}^q$ (sometimes called observations in RL literature). If $\bm{C}$ is not of full (column) rank, we say that the states are not directly observed. Otherwise, we assume $\bm{C}=\bm{I}_n$ and the states are directly observed. We assume that $\bm{A}$ and $\bm{B}$ are not known. The matrix $\bm{C}$ is also unknown if the state is not directly observed. We also make the standard assumption that $\left(\bm{A},\bm{B}\right)$ is stabilizable and $\left(\bm{A},\bm{C}\right)$ observable~\citep{hespanha2009linear}.
A trajectory is a sequence of observations and actions of length $T$, given by $\bm{\tau}=\{\bm{y}(0), \bm{u}(0), \cdots \\ , \bm{y}(T-1), \bm{u}(T-1)\}$. The control action $\bm{u}(k)$ most commonly comes from the control policy conditioned on the observation at time $k$, written as $\bm{\pi}_{\bm{\theta}}\left(\bm{u}(k) \mid \bm{y}(k)\right)$ with $\bm{\theta}$ being the parameter for the control policy. Let $c\left(\bm{\tau}\right)$ be the cost defined over the trajectory $\bm{\tau}$. The goal is to optimize the control paramater $\bm{\theta}$ to minimize the expected cost over trajectories, written as:
\vspace{-0.1cm}
\begin{equation}\label{eq:Opt_obj}
J(\bm{\theta})=\mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}}c\left(\bm{\tau}\right) ,
\end{equation}
where $p_{\bm{\pi}_{\bm{\theta}}}$ is the probability distribution of trajectory subject to the policy $\bm{\pi}_{\bm{\theta}}$.
The definition of $c\left(\bm{\tau}\right)$ varies for different problems.
For linear control policy, quadratic costs are most commonly utilized to convert the optimization into classical linear quadratic problems~\citep{fazel2018global,zheng2021sample}. There are typically not closed-form solutions for~\eqref{eq:Opt_obj} for other cost functions, e.g., $c\left(\bm{\tau}\right)=\sum_{i=1}^n\max_{k=0,\cdots,K-1}|x_i(k)|$ for the frequency control problem in power systems~\citep{cui2022tps}. In this case, gradient-based methods can be utilized to update $\bm{\theta}$, but the lack of system parameters makes it difficult to compute the gradient $ \nabla_{\bm{\theta}} J(\bm{\theta})$.
\paragraph{Direct policy gradient methods.}
Reinforcement learning (RL) is proposed to update $\bm{\theta}$ through gradient descent, where the gradient $ \nabla_{\bm{\theta}} J(\bm{\theta})$ is approximated from trajectories of the system under the control policy $\bm{\pi}_{\bm{\theta}}$.
For example, the policy gradient methods in~\citep{Sutton2018RL} shows that the gradient $ \nabla_{\bm{\theta}} J(\bm{\theta})$ can be equivalently computed by
\vspace{-0.1cm}
\begin{equation}\label{eq: PG_grad}
\nabla_{\bm{\theta}} J(\bm{\theta}) = \mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})}\left[c(\bm{\tau})\sum_{k=0}^{K-1} \nabla_{\bm{\theta}} \log p_{\bm{\pi}_{\bm{\theta}}}\left(\bm{u}(k) \mid \bm{y}(k)\right)\right],
\end{equation}
where $K$ is the length of the trajectory. The terms inside the expectation can be computed purely from observations and actions in the trajectory.
If $\bm{C}=\bm{I}_n$ in~\eqref{eq:sys_full}, the states are directly measured and the control law is called state-feedback control. Otherwise, the control law is called output-feedback control.
Note that if $\bm{C}$ is not full column rank, then $(\bm{y}(t),\bm{u}(t))$ cannot uniquely determine $\bm{y}(t+1)$. Namely, the system is not a Markov decision process with respect to $(\bm{y}(t),\bm{u}(t))$ and it is difficult to use generic RL algorithms based on the quality function $Q((\bm{y}(t),\bm{u}(t))$~\citep{jin2020sample}.
For illustration purpose, this paper focus on the policy gradient algorithm~\eqref{eq: PG_grad}, and we consider both state and output feedback control.
\vspace{-0.1cm}
\subsection{Approximate gradients with sampled trajectories}
When online interactions with the system are limited, computing the expectation in~\eqref{eq: PG_grad} is not trivial even when the states are directly observed.
In training, the expectation in~\eqref{eq: PG_grad} is approximated by the sample average over a large number of trajectories $\bm{\tau}$ collected from the system under the control policy $\bm{\pi}_{\bm{\theta}}$. Since the distribution $p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})$ depends on the parameter $\bm{\theta}$, a new set of trajectories need to be collected after each iteration of updating $\bm{\theta}$. Thus, the number of samples increases with the batchsize (i.e., the number of trajectories in each episode) and the number of training episodes.
We seek to update the control policy using historical trajectories and thus do not need to interact with the system during training. Two challenges arise: \textit{(i) Distribution Shift.} If the control policy changes, the distribution of
the historical trajectories would be different from the true distribution $p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})$, potentially resulting in large errors when computing~\eqref{eq: PG_grad}.
\textit{(ii) Exploration.} Most RL methods need to add (sometimes large) perturbations on actions to encourage exploration, but training with a fixed set of historical trajectories may limit exploration.
\paragraph{End-to-End Trajectory Generation.} We propose to overcome the challenges of distribution shift and the lack of exploration through generating trajectories from historical data. In this paper, we focus on learning linear feedback control law $\bm{u}(k)=\bm{\theta} \bm{y}(k)$, with $\bm{\theta}\in\real^{m\times q}$ being the matrix of trainable parameters. For exploration,
the action during training follows the control policy with perturbations $\bm{w}(k)$ as additive noise, written as
\vspace{-0.1cm}
\begin{equation}\label{eq:control_policy}
\bm{\pi}_{\bm{\theta}}\left(\bm{u}(k) \mid \bm{y}(k)\right):=\left\{\bm{u}(k)=\bm{\theta} \bm{y}(k)+\bm{w}(k), \bm{w}(k)\sim\mathcal{D}\right\},
\end{equation}
where $\mathcal{D}$ is the prescribed distribution for the perturbations. The variance of $\mathcal{D}$ is typically initialized to be large and then shrink with the training episode to achieve exploration v.s. exploitation.
We provide a simple end-to-end approach to generate input-output trajectories without system identification, allowing it to extend to systems where the states are not directly observed (i.e., when $\bm{C}$ is not full column rank). The generated trajectories are guaranteed to have the same distribution as $p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})$
for all $\bm{\theta}$ and $\mathcal{D}$. We first show the trajectory generation algorithm for state-feedback control in Section~\ref{sec:TrajGen_FullState}, then generalize the results to output-feedback control in Section~\ref{sec: TrajGen_PartialState}.
\subsection{Fundamental Lemma}
By defining the the Hankel matrix as $\mathcal{H}:=\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{Y}_{0, T, L-T+1}
\end{bmatrix}\in\real^{(Tm+Tq)\times(L-T+1)}$, the following fundamental Lemma in terms of input-output trajectories holds.
\vspace{-0.1cm}
\begin{lemma}[Fundamental Lemma~\citet{willems2005note, markovsky2022identifiability} ]\label{lem:fundemental_partial}
If $\text{rank}\left[\begin{smallmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{Y}_{0, L-T+1}
\end{smallmatrix}\right]=n+Tm$,
then any length-$T$ input/output trajectory of system~\eqref{eq:sys_full} can be expressed as
$
\left[\begin{smallmatrix}
\bm{u}_{[0, T-1]} \\
\bm{y}_{[0, T-1]}
\end{smallmatrix}\right]
=\left[\frac{\bm{U}_{0, T, L-T+1}}{\bm{Y}_{0, T, L-T+1}}\right] \bm{g}
$
where $\bm{g} \in \mathbb{R}^{L-T+1}$.
\end{lemma}
When the rank condition in Lemma~\ref{lem:fundemental_partial} holds, linear combination of the columns of the Hankel matrix is an input/output trajectory of the system. We then generate trajectory of length $T$ using
\vspace{-0.1cm}
\begin{equation}\label{eq:Hankel_g1}
\left[\begin{array}{c}
\Tilde{\bm{u}}(0);
\cdots;
\Tilde{\bm{u}}(T-1);
\Tilde{\bm{y}}(0);
\cdots;
\Tilde{\bm{y}}(T-1)
\end{array}\right]=
\mathcal{H}\bm{g}.
\end{equation}
For convenience, we adopt the notation $\mathcal{H}_u=U_{0, T, L-T+1} $, $\mathcal{H}_u=Y_{0, T, L-T+1} $ in the following sections. To represent the lines of blocks starting from the time $k=0,\cdots,T-1$, $\mathcal{H}_u^k$ the same as in~\eqref{eq:H_u_k} and $\mathcal{H}_y^k :=[
y_d(k) \, \cdots\,y_d(L-T+k) ]. $ We also define the stacked blocks starting from $k_1, \cdots, k_2$ as $
\mathcal{H}_y^{k_1 : k_2} :=
\begin{bmatrix}
{H}_y^{k_1 };
{H}_y^{k_1 +1};
\cdots;
{H}_y^{k_2}
\end{bmatrix} $ and $
\mathcal{H}_u^{k_1 : k_2} :=
\begin{bmatrix}
{H}_u^{k_1 };
{H}_u^{k_1 +1};
\cdots;
{H}_u^{k_2}
\end{bmatrix}$.
\subsection{Trajectory generation}\label{subsec: TrajGenPartial}
Using the transition dynamics~\eqref{eq:sys_extended}, the probability density function of a length-$T$ trajectory is
\vspace{-0.1cm}
\begin{equation*}\label{eq:prob_traj_partial}
p_{\pi_{\bm{\theta}}}(\bm{\tau})= p\left(\mathcal{X}\left(T_0-1\right)\right) \prod_{k=T_0-1}^{T-1} p\left(\bm{\theta} \bm{y}(k)+\bm{w}(k)|\mathcal{X}(k)\right) p\left(\mathcal{X}(k+1)|\mathcal{X}(k), \bm{\theta} \bm{y}(k)+\bm{w}(k)\right),
\end{equation*}
which is uniquely determined by $\mathcal{X}\left(T_0-1\right)$ and the sequences $\bm{w}(T_0-1), \cdots, \bm{w}(T-1)$.
In analogy with the derivation in~\eqref{eq: costrains_w}, we aim to generate the trajectory starting from $\mathcal{X}\left(T_0-1\right)$ under perturbations on actions given by $\bm{w}(T_0-1),\cdots, \bm{w}(T-1)$. From the control policy $\bm{u}(k)=\bm{\theta} \bm{y}(k)+\bm{w}(k)$, the trajectory subject to the perturbations $\bm{w}(T_0), \cdots, \bm{w}(T-1)$ should satisfy
\vspace{-0.1cm}
\begin{equation}\label{eq: costrains_w_partial}
\begin{split}
&\begin{bmatrix}
\mathcal{H}_u^{T_0 -1: T-1}
\end{bmatrix}\bm{g}=\left(\bm{I}_{T-T_0}\otimes\bm{\theta}\right)
\begin{bmatrix}
\mathcal{H}_y^{T_0 -1: T-1}
\end{bmatrix}\bm{g}
+\begin{bmatrix}
\bm{w}(T_0-1) \\
\vdots\\
\bm{w}(T-1)\\
\end{bmatrix}.
\end{split}
\end{equation}
Note that the generated extended initial state is given by $\Tilde{\mathcal{X}}\left(T_0-1\right):=\begin{bmatrix}
\mathcal{H}_y^{0 : T_0-1} ;
\mathcal{H}_u^{0 : T_0-2}
\end{bmatrix}\bm{g}$. Together with the constraints in~\eqref{eq: costrains_w_partial} gives
\vspace{-0.1cm}
\begin{equation}\label{eq:traj_g_partial}
\begin{split}
\underbrace{\left[\begin{array}{c}
\mathcal{H}_u^{T_0 -1: T-1} -\left(\bm{I}_{T-T_0}\otimes\bm{\theta}\right)\mathcal{H}_y^{T_0 -1: T-1} \\
\hline
\mathcal{H}_y^{0 : T_0-1}\\
\mathcal{H}_u^{0 : T_0-2}\\
\end{array}\right]}_{G_\theta}\bm{g}
=
\underbrace{\left[\begin{array}{c}
\bm{w}(T_0-1) \\
\vdots\\
\bm{w}(T-1)\\
\hline
\mathcal{X}(T_0-1)
\end{array}\right]}_{\bm{R}}
\end{split}
\end{equation}
\vspace{-0.6cm}
Note that the matrix $\bm{G}_{\bm{\theta}}\in\real^{(Tm+T_0 d) \times (L-T+1)}$ is not a square matrix and there might be multiple solutions to~\eqref{eq:traj_g_partial}. Moreover, $\bm{G}_{\bm{\theta}}$ may not be full row rank and thus $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$ may not be invertible. Here, we compute the eigenvalue decomposition of $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$. Let $s$ be the number of nonzero eigenvalue of $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$. Let $\lambda_i$ be the $i$-th non-zero eigenvalue and $\bm{p}_i$ be the associated eigenvector of $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$. Denote $\bm{P}_{\bm{\theta}}:=\begin{bmatrix}
\bm{p}_1 & \bm{p}_2 &\cdots& \bm{p}_s
\end{bmatrix}$ and $\bm{\Lambda}=\text{diag}(\lambda_1,\lambda_2,\cdots,\lambda_s)$. Then clearly
$\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)=\bm{P}_{\bm{\theta}}\bm{\Lambda}\bm{P}_{\bm{\theta}}^\top$ and we compute the solution of~\eqref{eq:traj_g_partial} given by
\vspace{-0.1cm}
\begin{equation}\label{eq: g_star_partial}
\bm{g}^*=\bm{G}_{\bm{\theta}}^\top\bm{P}_{\bm{\theta}}\bm{\Lambda}^{-1}\bm{P}_{\bm{\theta}}^\top\left[\begin{array}{c}
\bm{w}(T_0-1);
\cdots;
\bm{w}(T-1);
\mathcal{X}(T_0-1)
\end{array}\right].
\end{equation}
\vspace{-0.6cm}
Next, we prove the existence and uniqueness of the trajectory generated by~\eqref{eq:traj_g_partial}. The goal is to show that given $\left(\bm{w}(T_0-1),\cdots ,\bm{w}(T-1), \mathcal{X}(T_0-1)\right)$ , any
$\bm{g} $ that satisfies~\eqref{eq:traj_g_partial} will generate the same trajectory using $\mathcal{H}\bm{g}$. So it is suffice to choose the closed-form solution in~\eqref{eq: g_star_partial}.
\begin{theorem}\label{thm: unque_trajectory0_partial}
If $\text{rank}(\mathcal{H})=n+Tm$, there exists at least one solution $\bm{g}^*$ such that~\eqref{eq:traj_g_partial} holds.
Given $\left(\bm{w}(T_0-1),\cdots ,\bm{w}(T-1), \mathcal{X}(T_0-1)\right)$ and any $\bm{g} $ that solves~\eqref{eq:traj_g_partial}, $\mathcal{H}\bm{g}^*$ generates the same unique trajectory under the control policy~\eqref{eq:control_policy} parameterized by $\bm{\theta}$.
\end{theorem}
The proof of Theorem~\ref{thm: unque_trajectory0_partial} is not as straightforward as Theorem~\ref{thm: unque_trajectory0}, because $\bm{G}_{\bm{\theta}}$ and $\bm{R}$ in~\eqref{eq:traj_g_partial} may not be full row-rank. The detailed proof is given in Appendix~\ref{app:thm_partial} and we sketch the proof as follows.
We use the mapping from $\bm{x}(0)$ to $\mathcal{X}(T_0-1)$ to show that the rank of $\bm{R}$ in~\eqref{eq:traj_g_partial} is at most $n+Tm$. Leveraging the relation in every $T_0$ blocks derived from~\eqref{eq:sys_extended}, we
show in Lemma~\ref{lem:null_partial} that $\text{rank}(\bm{G}_{\bm{\theta}})=n+Tm$ if $\text{rank}(\mathcal{H})=n+Tm$. The existence of a solution in~\eqref{eq:traj_g_partial} is therefore guaranteed by the same row-rank of the two sides. The uniqueness of the trajectory generated by $\mathcal{H}\bm{g}^*$ is proved by showing that the Null space $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$.
We can generate a trajectory $\mathcal{H}\bm{g}^*$ by randomly sampling $\mathcal{X}(T_0-1)$ and $\bm{w}(t)\in\mathcal{D}$ for $t=T_0-1,\cdots,T-1$. For the cost~\eqref{eq:Opt_obj} calculated on the trajectory of the length $K$, we setup $T=K+T_0-1$, and using the generated trajectory $\mathcal{H}\bm{g}^*$ from $T_0-1$ to $T-1$ to train the controller. The detailed algorithm can be found in Appendix~\ref{app:algorithm}.
\subsection{Span of historic trajectories}
Let $\bm{u}_{d,[0, L-1]}$ and $\bm{x}_{d,[0, L-1]}$ be the a length-$L$ input and state from past trajectory, and let the corresponding Hankel matrix $\mathcal{H}\in\real^{(Tm+Tn)\times (L-T+1})$ defined as
\vspace{-0.1cm}
\begin{equation}\label{eq:Hankel_u_x}
\begin{split}
&\underbrace{
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}
}_{\mathcal{H}}\quad
:=
\left[\begin{matrix}
\bm{u}_d(0) & \bm{u}_d(1) & \cdots & \bm{u}_d(L-T) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{u}_d(T-1) & \bm{u}_d(T) & \cdots & \bm{u}_d(L-1) \\
\hline \bm{x}_d(0) & \bm{x}_d(1) & \cdots & \bm{x}_d(L-T) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{x}_d(T-1) & \bm{x}_d(T) & \cdots & \bm{x}_d(L-1)
\end{matrix}\right].
\end{split}
\end{equation}
By the state-space version of Fundamental Lemma~\citep{de2019formulas} shown below, any linear combination of the columns of the Hankel matrix is a length-$T$ input-state trajectory of~\eqref{eq:sys_full}. The proof is provided in~\citep{de2019formulas} and we supplement it in Appendix~\ref{app: fundemental} for completeness.
\vspace{-0.1cm}
\begin{lemma}[ Fundamental Lemma]\label{lem:fundemental}
If $\text{rank}\left[\begin{smallmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, L-T+1}
\end{smallmatrix}\right]=n+Tm$,
then any length-$T$ input/state trajectory of system~\eqref{eq:sys_full} can be expressed as
$\left[\begin{smallmatrix}
\bm{u}_{[0, T-1]} \\
\bm{x}_{[0, T-1]}
\end{smallmatrix}\right]=\left[\frac{\bm{U}_{0, T, L-T+1}}{\bm{X}_{0, T, L-T+1}}\right] \bm{g}$,
where $\bm{g}\in \mathbb{R}^{L-T+1}$.
\end{lemma}
For the rank condition in Lemma~\ref{lem:fundemental} to hold, the minimum requirement on the length of the collected trajectory is $L-T+1=n+Tm$, namely, $L=(m+1)T-1+n$.
When the rank condition holds, linear combination of the columns of the Hankel matrix is also a length-$T$ trajectory of the system. Thus, we generate a trajectory of length $T$ using
\vspace{-0.1cm}
\begin{equation}\label{eq:Hankel_g0}
\begin{bmatrix}
\Tilde{\bm{u}}(0);
\cdots;
\Tilde{\bm{u}}(T-1);
\Tilde{\bm{x}}(0);
\cdots;
\Tilde{\bm{x}}(T-1)
\end{bmatrix}
=
\underbrace{
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}
}_{\mathcal{H}}\bm{g}.
\end{equation}
For convenience, we adopt the notation $\mathcal{H}_u=\bm{U}_{0, T, L-T+1} $, $\mathcal{H}_x=\bm{X}_{0, T, L-T+1} $ in the following sections. To represent the rows of blocks starting from the time $k=0,\cdots,T-1$, we denote
\vspace{-0.1cm}
\begin{equation}\label{eq:H_u_k}
\mathcal{H}_x^k :=
[
\bm{x}_d(k) \; \bm{x}_d(k+1)\, \cdots\, \bm{x}_d(L-T+k)
],\,
\mathcal{H}_u^k :=
[
\bm{u}_d(k) \; \bm{u}_d(k+1) \, \cdots \, \bm{u}_d(L-T+k)
].
\end{equation}
\subsection{Trajectory generation}
For generic RL algorithms, a trajectory is sampled from the system that starts from an initial state $\bm{x}(0)$ and subsequently implements the control policy $\bm{u}(k)=\bm{\theta} \bm{x}(k)+\bm{w}(k), \bm{w}(k)\sim\mathcal{D}$ for $k=0,\cdots,T-1$. Given $\bm{\theta}$, the probability density function of a trajectory is
\vspace{-0.1cm}
\begin{equation}\label{eq:pdf}
\begin{split}
p_{\pi_{\bm{\theta}}}(\bm{\tau})= p\left(\bm{x}(0)\right) \prod_{k=0}^{T-1} &p\left(\bm{\theta} \bm{x}(k)+\bm{w}(k)|\bm{x}(k)\right) p\left(\bm{x}(k+1) \mid \bm{x}(k), \bm{\theta} \bm{x}(k)+\bm{w}(k)\right),
\end{split}
\end{equation}
which is uniquely determined by $\bm{x}(0)$ and the sequence of perturbations $\bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1)$.
In the following, we generate trajectories for each updated $\bm{\theta}$ as if they truly come from the system starting from $\bm{x}(0)$ under perturbations on actions given by $\bm{w}(0),\cdots, \bm{w}(T-1)$.
Importantly, we use fixed historic trajectories $\left\{\bm{u}_d, \bm{y}_d\right\}$ where the Hankel matrix $\mathcal{H}$ in~\eqref{eq:Hankel_u_x} satisfies $\text{rank}(\mathcal{H})=n+Tm$, and $\bm{u}_d$ can come from controllers different from the control policy in~\eqref{eq:control_policy}.
The key is to use $\bm{x}(0)$ and $(\bm{w}(0),\allowbreak\cdots, \bm{w}(T-1))$ as extra constraints to find the $\bm{g}$ in~\eqref{eq:Hankel_g0} that generates the trajectory which follows the same distribution as~\eqref{eq:pdf}.
From the control policy $\bm{u}(k)=\bm{\theta} \bm{x}(k)+\bm{w}(k)$, the trajectory subject to the perturbations $\bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1)$ should satisfy
\vspace{-0.1cm}
\begin{equation}\label{eq: costrains_w}
\begin{split}
\left[\begin{array}{c}
\Tilde{\bm{u}}(0) \\
\vdots\\
\Tilde{\bm{u}}(T-1)\\
\end{array}\right]=
\underbrace{\begin{bmatrix}
\bm{\theta}& & & \\
& & \ddots& \\
& & & \bm{\theta} \\
\end{bmatrix}}_{\bm{I}_{T}\bigotimes\bm{\theta}}
\left[\begin{array}{c}
\Tilde{\bm{x}}(0)\\
\vdots\\
\Tilde{\bm{x}}(T-1)
\end{array}\right]
+\left[\begin{array}{c}
\bm{w}(0) \\
\vdots\\
\bm{w}(T-1)\\
\end{array}\right].
\end{split}
\end{equation}
Note that the generated initial state is given by $\Tilde{\bm{x}}(0)=\left[\begin{array}{cccc}
\mathcal{H}_x^0
\end{array}\right]\bm{g}$. Combining with~\eqref{eq: costrains_w} gives
\vspace{-0.1cm}
\begin{equation}\label{eq:traj_g0}
\underbrace{\begin{bmatrix}
\mathcal{H}_u-\left(\bm{I}_{T}\otimes\bm{\theta}\right) \mathcal{H}_x\\
\mathcal{H}_x^0
\end{bmatrix}}_{\bm{G}_{\bm{\theta}}}
\bm{g}=
\begin{bmatrix}
\bm{w}(0) \\
\vdots\\
\bm{w}(T-1)\\
\bm{x}(0)
\end{bmatrix}.
\end{equation}
Note that the matrix $\bm{G}_{\bm{\theta}}\in\real^{(Tm+n) \times (L-T+1)}$ is not a square matrix and its rank is determined by the length of historic trajectory $L$. When the trajectory is sufficiently long and $\text{rank}(\mathcal{H})=n+Tm$, we have $L-T+1>Tm+n$ and thus there might be multiple $\bm{g} $ where~\eqref{eq:traj_g0} holds.
We use the minimum-norm solution of~\eqref{eq:traj_g0} given by
\vspace{-0.1cm}
\begin{equation}\label{eq: g_star0}
\bm{g}^*=\bm{G}_{\bm{\theta}}^\top\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)^{-1}\left[\begin{array}{c}
\bm{w}(0);
\cdots;
\bm{w}(T-1);
\bm{x}(0)
\end{array}\right].
\end{equation}
In the next Theorem, we prove the existence and uniqueness of the trajectory generated by~\eqref{eq:traj_g0}. The goal is to show that given $\left(\bm{w}(0),\cdots ,\bm{w}(T-1), \bm{x}(0)\right)$, any $\bm{g} $ that satisfies~\eqref{eq:traj_g0} will generate the same trajectory using $\mathcal{H}\bm{g}$. So it is suffice to choose the closed-form solution in~\eqref{eq: g_star0}.
\vspace{-0.1cm}
\begin{theorem}\label{thm: unque_trajectory0}
If $\text{rank}(\mathcal{H})=n+Tm$, there exists at least one solution $\bm{g}$ such that~\eqref{eq:traj_g0} holds.
Given $\left(\bm{w}(0),\cdots ,\bm{w}(T-1), \bm{x}(0)\right)$ and any $\bm{g} $ that solves~\eqref{eq:traj_g0}, $\mathcal{H}\bm{g}^*$ generates the same unique trajectory under the control policy~\eqref{eq:control_policy} parameterized by $\bm{\theta}$.
\end{theorem}
Theorem~\ref{thm: unque_trajectory0} shows that $\mathcal{H}\bm{g}^*$ generates the unique trajectory that starts from an initial state $\bm{x}(0)$ and subsequently implements the control policy $\bm{u}(k)=\bm{\theta} \bm{x}(k)+\bm{w}(k), \bm{w}(k)\sim\mathcal{D}$. Hence, if we fix $\bm{\theta}$ in~\eqref{eq: g_star0} and sample $(\bm{x}(0), \bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1))$, then $\mathcal{H}\bm{g}^*$ will generate a batch of trajectories following the distribution~\eqref{eq:pdf} corresponding to the parameter $\bm{\theta}$. After the update of $\bm{\theta}$ in each episode of training, we generate a new batch of trajectories by updating $\bm{G}_{\bm{\theta}}$ in~\eqref{eq:traj_g0} and sampling new $(\bm{x}(0), \bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1))$. Thus, the generated trajectories adaptively follow the shifted distribution after updating $\bm{\theta}$. Importantly, it overcomes the negative perception in the field that there is no possibility to improve explorations beyond past trajectories~\citep{levine2020offline}. By sampling the noises $\bm{w}(k)\sim\mathcal{D}$, explorations can also be achieved through the generated trajectories. Hence, new trajectories are adaptively generated as if the system were being operated and explored under the updated control policies.
To prove Theorem~\ref{thm: unque_trajectory0}, we first show that the null space of $\bm{G}_{\bm{\theta}}$ is exactly the same as that of the Hankel matrix $\mathcal{H}$. Then, $\text{rank}(\mathcal{H})=n+Tm$ yields $\text{rank}(\bm{G}_{\bm{\theta}})=n+Tm$. The full row rank of $\bm{G}_{\bm{\theta}}$ implies that there exist at least one $\bm{g}$ where~\eqref{eq:traj_g0} holds. The uniqueness of trajectory generated by $\bm{g}$ follows from the fact that $\bm{G}_{\bm{\theta}}$ and $\mathcal{H}$ have the same null space. Details of the proof is given below.
\begin{proof}
We first prove that the null space $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$ from \textit{(i)} and \textit{(ii)} :
\textit{(i)} For all $\bm{q}\in \mathcal{N}(\mathcal{H})$, we have $[\mathcal{H}_x]\bm{q} =\mathbbold{0}_{Tn}$ and $[\mathcal{H}_u]\bm{q} =\mathbbold{0}_{Tm}$. Plugging in $\bm{G}_{\bm{\theta}}$ in~\eqref{eq:traj_g0} yields $\bm{G}_{\bm{\theta}}\bm{q} = \mathbbold{0}_{Tm+n} $. Namely, $\bm{q}\in\mathcal{N}(\bm{G}_{\bm{\theta}})$.
\textit{(ii)} For all $\bm{v}\in \mathcal{N}(\bm{G}_{\bm{\theta}})$, $\bm{G}_{\bm{\theta}}\bm{v}=\mathbbold{0}_{Tm+n}$ yields $\mathcal{H}_x^0\bm{v} =\mathbbold{0}_{n}$
and
$\mathcal{H}_u^k \bm{v}=\hat{\bm{\theta}}\mathcal{H}_x^k \bm{v} \text{ for } k=0,\cdots,T-1$. Thus, $\mathcal{H}_u^0 \bm{v}=\hat{\bm{\theta}}\mathcal{H}_x^0 \bm{v}=\mathbbold{0}_{m}$. From $\bm{x}(k+1) =\bm{A} \bm{x}(k)+\bm{B} \bm{u}(k)$, we have $\mathcal{H}_x^{k+1}=A \mathcal{H}_x^{k}+B \mathcal{H}_u^{k}.$ From $ \mathcal{H}_x^{0}=\mathbbold{0}_{n}$ and $ \mathcal{H}_u^{0}=\mathbbold{0}_{m}$, we
apply $\mathcal{H}_x^{k+1}=A \mathcal{H}_x^{k}+B \mathcal{H}_u^{k}$ and $\mathcal{H}_u^k \bm{v}=\hat{\bm{\theta}}\mathcal{H}_x^k \bm{v}$ alternately. This induces
$\mathcal{H}_x^k \bm{v} =\mathbbold{0}_{n}$ and $\mathcal{H}_u^k \bm{v} =\mathbbold{0}_{m}$ for $ k=0,\cdots,T-1$. Hence, $\mathcal{H}\bm{v} = \mathbbold{0}_{Tm+Tn} $.
Next, we prove the existence of the solution in~\eqref{eq:traj_g0}. Note that $\mathcal{H}\in\real^{(Tm+Tn) \times (L-T+1)}$. If $\text{rank}(\mathcal{H})=n+Tm$, then $\text{rank}(\mathcal{N}(\mathcal{H}))=(L-T+1)-(n+Tm)$.
Since $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$, then $\text{rank}(\mathcal{N}(\bm{G}_{\bm{\theta}}))=(L-T+1)-(n+Tm)$. It follows directly that $\text{rank}(\bm{G}_{\bm{\theta}})=(L-T+1)-\text{rank}(\mathcal{N}(\bm{G}_{\bm{\theta}}))=n+Tm$. Note that the number of rows of $\bm{G}_{\bm{\theta}}$ is $n+Tm$, then the full row-rank of $\text{rank}(\bm{G}_{\bm{\theta}})$ shows that there exists at least one solution such that~\eqref{eq:traj_g0} holds.
Lastly, we show the uniqueness of the generated trajectory. Suppose there exists $\bm{g}_1$ and $\bm{g}_2$, which are both solutions of~\eqref{eq:traj_g0} and $\mathcal{H}\bm{g}_1\neq \mathcal{H}\bm{g}_2$. Since $\bm{g}_1$ and $\bm{g}_2$ are both solution of~\eqref{eq:traj_g0}, then $\bm{G}_{\bm{\theta}}\bm{g}_1=\bm{G}_{\bm{\theta}}\bm{g}_1$ and thus $\left(\bm{g}_1-\bm{g}_2\right)\in\mathcal{N}(\bm{G}_{\bm{\theta}})$.
On the other hand, $\mathcal{H}\bm{g}_1\neq \mathcal{H}\bm{g}_2$ yields $\mathcal{H}\left(\bm{g}_1-\bm{g}_2\right)\neq 0$ and thus $\left(\bm{g}_1-\bm{g}_2\right)\notin\mathcal{N}(\mathcal{H})$. This contradicts that $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$. Hence, $\mathcal{H}\bm{g}_1= \mathcal{H}\bm{g}_2$, namely, the generated trajectories are identical.
\end{proof}
\vspace{-0.1cm}
\subsection{Algorithm}
By Theorem~\ref{thm: unque_trajectory0}, using historical data, given $\bm{x}(0)$ and perturbations on actions $\bm{w}(0),\cdots, \bm{w}(T-1)$,
a trajectory can be generated as if it comes from sampling the system with the current control policy.
The details of the algorithm is illustrated in Algorithm~\ref{alg: TrajGenFull}.
We also use REINFORCE policy gradient~\citep{Sutton2018RL} in Appendix~\ref{app: PG_state_feedback} as an example to show how to use the trajectory generation algorithm in RL methods.
The key benefit of Algorithm~\ref{alg: TrajGenFull}
is that it is adaptive to the updates of parameter $\bm{\theta}$ and $\bm{w}(t)$ for exploration. In particular, $\bm{w}(t)$ can be sampled from any distribution $\mathcal{D}$, making it versatile for different applications.
\begin{algorithm}[h]
\caption{Trajectory generation for state-feedback control }
\label{alg: TrajGenFull}
\begin{algorithmic}[1]
\renewcommand{\algorithmicrequire}{\textbf{Require: }}
\renewcommand{\algorithmicensure}{\textbf{Data collection:}}
\ENSURE Collect historic measurement of the system and stack each $T$-length input-output trajectory as Hankel matrix $\mathcal{H}$ shown in~\eqref{eq:Hankel_u_x} until $\text{rank}(\mathcal{H})=n+Tm$ \\
\renewcommand{\algorithmicensure}{\textbf{Data generation:}}
\ENSURE
\textit{Input} :Hankel matrix $\mathcal{H}$, weights $\bm{\theta}$ and the distribution $\mathcal{D}$ for the control policy, the batchsize $Q$ (number of the generated trajectories), the distribution $\mathcal{S}_x $ of the initial states\footnotemark \\
\SetKwFunction{FMain}{TrajectoryGen}
\SetKwProg{Fn}{Function}{:}{}
\Fn{\FMain{$\mathcal{H},\bm{\theta},\mathcal{D},Q, \mathcal{S}_x $}}{
Plug in $\bm{\theta}$ to compute $\bm{G}_{\bm{\theta}}=\begin{bmatrix}
\mathcal{H}_u-\left(\bm{I}_{T}\otimes\bm{\theta}\right) \mathcal{H}_x;
\mathcal{H}_x^0
\end{bmatrix}$
\For{$i = 1$ to $Q$}
{Sample $\bm{x}_i(0)$ from $\mathcal{S}_x $. Sample $\left\{\bm{w}_i(0),\cdots,\bm{w}_i(T-1)\right\}$ from $\mathcal{D}$.\\
Compute the coefficient $\bm{g}_i^*=\bm{G}_{\bm{\theta}}^\top\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)^{-1}\left[
\bm{w}_i(0);
\cdots;
\bm{w}_i(T-1);
\bm{x}_i(0)
\right]$.
\\
Generate the $i$-th trajectory $\bm{\tau}_i:=\left[
\Tilde{\bm{u}}_i(0);
\cdots;
\Tilde{\bm{u}}_i(T-1);
\Tilde{\bm{x}}_i(0);
\cdots;
\Tilde{\bm{x}}_i(T-1);
\right]=\mathcal{H}\bm{g}_i^*$.
}
\textbf{return} $ \left[\bm{\tau}_1,\cdots,\bm{\tau}_Q \right]$
}
\end{algorithmic}
\end{algorithm}
\footnotetext{The set of historic initial states in past trajectories can be used to estimate $\mathcal{S}_x $.}
\subsection{Notations}
Throughout this manuscript, vectors are denoted in lower case bold and matrices are denoted in upper case bold, unless otherwise specified. Vectors of all ones and zeros are denoted by $\mathbbold{1}_n, \mathbbold{0}_n \in \real^n$, respectively. The identity matrix is denoted by $\bm{I}_n\in\real^{n\times n}$.
We use $\mathcal{N}(\bm{A})$ to denote the null space of matrix $\bm{A}$. Given $n$ matrices $\bm{M}_i, i=1,\cdots,n$, we denote $[\bm{M}_1;\cdots;\bm{M}_n]:=[\bm{M}_1^\top \cdots \bm{M}_n^\top]^\top$.
Given a discrete-time signal $\bm{z}(t)\in \mathbb{R}^d$ for $t=0,1,\cdots$, we
use $\bm{z}_{[k, k+T]}\in\real^{Td}$ to denote the vector form of the sequence $\{\bm{z}(k), \ldots, \bm{z}(k+T)\}$,
and the Hankel matrix $\bm{Z}_{i, t, N}\in\real^{td\times N}$ as
\vspace{-0.1cm}
$$
\bm{Z}_{[k, k+T]}=\left[\begin{array}{c}
\bm{z}(k) \\
\vdots \\
\bm{z}(k+T)
\end{array}\right],
\bm{Z}_{i, t, N}=\left[\begin{array}{cccc}
\bm{z}(i) & \bm{z}(i+1) & \cdots & \bm{z}(i+N-1) \\
\bm{z}(i+1) & \bm{z}(i+2) & \cdots & \bm{z}(i+N) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{z}(i+t-1) & \bm{z}(i+t) & \cdots & \bm{z}(i+t+N-2)
\end{array}\right],
$$
where $k,i$ and are integers, and $t, N, T $ are natural numbers. The first subscript of $\bm{Z}_{i, t, N}$ denotes the time at which the first sample of the signal is taken, the second one the number of samples per each column, and the last one the number of signal samples per each row.
\subsection{Problem formulation}\label{subsec: problem}
We consider a discrete-time linear time-invariant system
\vspace{-0.1cm}
\begin{equation}\label{eq:sys_full}
\begin{aligned}
\bm{x}(k+1) &=\bm{A} \bm{x}(k)+\bm{B} \bm{u}(k) \\
\bm{y}(k) &=\bm{C} \bm{x}(k)
\end{aligned}
\end{equation}
with state $\bm{x} \in \mathbb{R}^n$, action $\bm{u} \in \mathbb{R}^m$, and output $\bm{y} \in \mathbb{R}^q$ (sometimes called observations in RL literature). If $\bm{C}$ is not of full (column) rank, we say that the states are not directly observed. Otherwise, we assume $\bm{C}=\bm{I}_n$ and the states are directly observed. We assume that $\bm{A}$ and $\bm{B}$ are not known. The matrix $\bm{C}$ is also unknown if the state is not directly observed. We also make the standard assumption that $\left(\bm{A},\bm{B}\right)$ is stabilizable and $\left(\bm{A},\bm{C}\right)$ observable~\citep{hespanha2009linear}.
A trajectory is a sequence of observations and actions of length $T$, given by $\bm{\tau}=\{\bm{y}(0), \bm{u}(0), \cdots \\ , \bm{y}(T-1), \bm{u}(T-1)\}$. The control action $\bm{u}(k)$ most commonly comes from the control policy conditioned on the observation at time $k$, written as $\bm{\pi}_{\bm{\theta}}\left(\bm{u}(k) \mid \bm{y}(k)\right)$ with $\bm{\theta}$ being the parameter for the control policy. Let $c\left(\bm{\tau}\right)$ be the cost defined over the trajectory $\bm{\tau}$. The goal is to optimize the control paramater $\bm{\theta}$ to minimize the expected cost over trajectories, written as:
\vspace{-0.1cm}
\begin{equation}\label{eq:Opt_obj}
J(\bm{\theta})=\mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}}c\left(\bm{\tau}\right) ,
\end{equation}
where $p_{\bm{\pi}_{\bm{\theta}}}$ is the probability distribution of trajectory subject to the policy $\bm{\pi}_{\bm{\theta}}$.
The definition of $c\left(\bm{\tau}\right)$ varies for different problems.
For linear control policy, quadratic costs are most commonly utilized to convert the optimization into classical linear quadratic problems~\citep{fazel2018global,zheng2021sample}. There are typically not closed-form solutions for~\eqref{eq:Opt_obj} for other cost functions, e.g., $c\left(\bm{\tau}\right)=\sum_{i=1}^n\max_{k=0,\cdots,K-1}|x_i(k)|$ for the frequency control problem in power systems~\citep{cui2022tps}. In this case, gradient-based methods can be utilized to update $\bm{\theta}$, but the lack of system parameters makes it difficult to compute the gradient $ \nabla_{\bm{\theta}} J(\bm{\theta})$.
\paragraph{Direct policy gradient methods.}
Reinforcement learning (RL) is proposed to update $\bm{\theta}$ through gradient descent, where the gradient $ \nabla_{\bm{\theta}} J(\bm{\theta})$ is approximated from trajectories of the system under the control policy $\bm{\pi}_{\bm{\theta}}$.
For example, the policy gradient methods in~\citep{Sutton2018RL} shows that the gradient $ \nabla_{\bm{\theta}} J(\bm{\theta})$ can be equivalently computed by
\vspace{-0.1cm}
\begin{equation}\label{eq: PG_grad}
\nabla_{\bm{\theta}} J(\bm{\theta}) = \mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})}\left[c(\bm{\tau})\sum_{k=0}^{K-1} \nabla_{\bm{\theta}} \log p_{\bm{\pi}_{\bm{\theta}}}\left(\bm{u}(k) \mid \bm{y}(k)\right)\right],
\end{equation}
where $K$ is the length of the trajectory. The terms inside the expectation can be computed purely from observations and actions in the trajectory.
If $\bm{C}=\bm{I}_n$ in~\eqref{eq:sys_full}, the states are directly measured and the control law is called state-feedback control. Otherwise, the control law is called output-feedback control.
Note that if $\bm{C}$ is not full column rank, then $(\bm{y}(t),\bm{u}(t))$ cannot uniquely determine $\bm{y}(t+1)$. Namely, the system is not a Markov decision process with respect to $(\bm{y}(t),\bm{u}(t))$ and it is difficult to use generic RL algorithms based on the quality function $Q((\bm{y}(t),\bm{u}(t))$~\citep{jin2020sample}.
For illustration purpose, this paper focus on the policy gradient algorithm~\eqref{eq: PG_grad}, and we consider both state and output feedback control.
\vspace{-0.1cm}
\subsection{Approximate gradients with sampled trajectories}
When online interactions with the system are limited, computing the expectation in~\eqref{eq: PG_grad} is not trivial even when the states are directly observed.
In training, the expectation in~\eqref{eq: PG_grad} is approximated by the sample average over a large number of trajectories $\bm{\tau}$ collected from the system under the control policy $\bm{\pi}_{\bm{\theta}}$. Since the distribution $p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})$ depends on the parameter $\bm{\theta}$, a new set of trajectories need to be collected after each iteration of updating $\bm{\theta}$. Thus, the number of samples increases with the batchsize (i.e., the number of trajectories in each episode) and the number of training episodes.
We seek to update the control policy using historical trajectories and thus do not need to interact with the system during training. Two challenges arise: \textit{(i) Distribution Shift.} If the control policy changes, the distribution of
the historical trajectories would be different from the true distribution $p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})$, potentially resulting in large errors when computing~\eqref{eq: PG_grad}.
\textit{(ii) Exploration.} Most RL methods need to add (sometimes large) perturbations on actions to encourage exploration, but training with a fixed set of historical trajectories may limit exploration.
\paragraph{End-to-End Trajectory Generation.} We propose to overcome the challenges of distribution shift and the lack of exploration through generating trajectories from historical data. In this paper, we focus on learning linear feedback control law $\bm{u}(k)=\bm{\theta} \bm{y}(k)$, with $\bm{\theta}\in\real^{m\times q}$ being the matrix of trainable parameters. For exploration,
the action during training follows the control policy with perturbations $\bm{w}(k)$ as additive noise, written as
\vspace{-0.1cm}
\begin{equation}\label{eq:control_policy}
\bm{\pi}_{\bm{\theta}}\left(\bm{u}(k) \mid \bm{y}(k)\right):=\left\{\bm{u}(k)=\bm{\theta} \bm{y}(k)+\bm{w}(k), \bm{w}(k)\sim\mathcal{D}\right\},
\end{equation}
where $\mathcal{D}$ is the prescribed distribution for the perturbations. The variance of $\mathcal{D}$ is typically initialized to be large and then shrink with the training episode to achieve exploration v.s. exploitation.
We provide a simple end-to-end approach to generate input-output trajectories without system identification, allowing it to extend to systems where the states are not directly observed (i.e., when $\bm{C}$ is not full column rank). The generated trajectories are guaranteed to have the same distribution as $p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})$
for all $\bm{\theta}$ and $\mathcal{D}$. We first show the trajectory generation algorithm for state-feedback control in Section~\ref{sec:TrajGen_FullState}, then generalize the results to output-feedback control in Section~\ref{sec: TrajGen_PartialState}.
\subsection{Fundamental Lemma}
By defining the the Hankel matrix as $\mathcal{H}:=\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{Y}_{0, T, L-T+1}
\end{bmatrix}\in\real^{(Tm+Tq)\times(L-T+1)}$, the following fundamental Lemma in terms of input-output trajectories holds.
\vspace{-0.1cm}
\begin{lemma}[Fundamental Lemma~\citet{willems2005note, markovsky2022identifiability} ]\label{lem:fundemental_partial}
If $\text{rank}\left[\begin{smallmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{Y}_{0, L-T+1}
\end{smallmatrix}\right]=n+Tm$,
then any length-$T$ input/output trajectory of system~\eqref{eq:sys_full} can be expressed as
$
\left[\begin{smallmatrix}
\bm{u}_{[0, T-1]} \\
\bm{y}_{[0, T-1]}
\end{smallmatrix}\right]
=\left[\frac{\bm{U}_{0, T, L-T+1}}{\bm{Y}_{0, T, L-T+1}}\right] \bm{g}
$
where $\bm{g} \in \mathbb{R}^{L-T+1}$.
\end{lemma}
When the rank condition in Lemma~\ref{lem:fundemental_partial} holds, linear combination of the columns of the Hankel matrix is an input/output trajectory of the system. We then generate trajectory of length $T$ using
\vspace{-0.1cm}
\begin{equation}\label{eq:Hankel_g1}
\left[\begin{array}{c}
\Tilde{\bm{u}}(0);
\cdots;
\Tilde{\bm{u}}(T-1);
\Tilde{\bm{y}}(0);
\cdots;
\Tilde{\bm{y}}(T-1)
\end{array}\right]=
\mathcal{H}\bm{g}.
\end{equation}
For convenience, we adopt the notation $\mathcal{H}_u=U_{0, T, L-T+1} $, $\mathcal{H}_u=Y_{0, T, L-T+1} $ in the following sections. To represent the lines of blocks starting from the time $k=0,\cdots,T-1$, $\mathcal{H}_u^k$ the same as in~\eqref{eq:H_u_k} and $\mathcal{H}_y^k :=[
y_d(k) \, \cdots\,y_d(L-T+k) ]. $ We also define the stacked blocks starting from $k_1, \cdots, k_2$ as $
\mathcal{H}_y^{k_1 : k_2} :=
\begin{bmatrix}
{H}_y^{k_1 };
{H}_y^{k_1 +1};
\cdots;
{H}_y^{k_2}
\end{bmatrix} $ and $
\mathcal{H}_u^{k_1 : k_2} :=
\begin{bmatrix}
{H}_u^{k_1 };
{H}_u^{k_1 +1};
\cdots;
{H}_u^{k_2}
\end{bmatrix}$.
\subsection{Trajectory generation}\label{subsec: TrajGenPartial}
Using the transition dynamics~\eqref{eq:sys_extended}, the probability density function of a length-$T$ trajectory is
\vspace{-0.1cm}
\begin{equation*}\label{eq:prob_traj_partial}
p_{\pi_{\bm{\theta}}}(\bm{\tau})= p\left(\mathcal{X}\left(T_0-1\right)\right) \prod_{k=T_0-1}^{T-1} p\left(\bm{\theta} \bm{y}(k)+\bm{w}(k)|\mathcal{X}(k)\right) p\left(\mathcal{X}(k+1)|\mathcal{X}(k), \bm{\theta} \bm{y}(k)+\bm{w}(k)\right),
\end{equation*}
which is uniquely determined by $\mathcal{X}\left(T_0-1\right)$ and the sequences $\bm{w}(T_0-1), \cdots, \bm{w}(T-1)$.
In analogy with the derivation in~\eqref{eq: costrains_w}, we aim to generate the trajectory starting from $\mathcal{X}\left(T_0-1\right)$ under perturbations on actions given by $\bm{w}(T_0-1),\cdots, \bm{w}(T-1)$. From the control policy $\bm{u}(k)=\bm{\theta} \bm{y}(k)+\bm{w}(k)$, the trajectory subject to the perturbations $\bm{w}(T_0), \cdots, \bm{w}(T-1)$ should satisfy
\vspace{-0.1cm}
\begin{equation}\label{eq: costrains_w_partial}
\begin{split}
&\begin{bmatrix}
\mathcal{H}_u^{T_0 -1: T-1}
\end{bmatrix}\bm{g}=\left(\bm{I}_{T-T_0}\otimes\bm{\theta}\right)
\begin{bmatrix}
\mathcal{H}_y^{T_0 -1: T-1}
\end{bmatrix}\bm{g}
+\begin{bmatrix}
\bm{w}(T_0-1) \\
\vdots\\
\bm{w}(T-1)\\
\end{bmatrix}.
\end{split}
\end{equation}
Note that the generated extended initial state is given by $\Tilde{\mathcal{X}}\left(T_0-1\right):=\begin{bmatrix}
\mathcal{H}_y^{0 : T_0-1} ;
\mathcal{H}_u^{0 : T_0-2}
\end{bmatrix}\bm{g}$. Together with the constraints in~\eqref{eq: costrains_w_partial} gives
\vspace{-0.1cm}
\begin{equation}\label{eq:traj_g_partial}
\begin{split}
\underbrace{\left[\begin{array}{c}
\mathcal{H}_u^{T_0 -1: T-1} -\left(\bm{I}_{T-T_0}\otimes\bm{\theta}\right)\mathcal{H}_y^{T_0 -1: T-1} \\
\hline
\mathcal{H}_y^{0 : T_0-1}\\
\mathcal{H}_u^{0 : T_0-2}\\
\end{array}\right]}_{G_\theta}\bm{g}
=
\underbrace{\left[\begin{array}{c}
\bm{w}(T_0-1) \\
\vdots\\
\bm{w}(T-1)\\
\hline
\mathcal{X}(T_0-1)
\end{array}\right]}_{\bm{R}}
\end{split}
\end{equation}
\vspace{-0.6cm}
Note that the matrix $\bm{G}_{\bm{\theta}}\in\real^{(Tm+T_0 d) \times (L-T+1)}$ is not a square matrix and there might be multiple solutions to~\eqref{eq:traj_g_partial}. Moreover, $\bm{G}_{\bm{\theta}}$ may not be full row rank and thus $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$ may not be invertible. Here, we compute the eigenvalue decomposition of $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$. Let $s$ be the number of nonzero eigenvalue of $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$. Let $\lambda_i$ be the $i$-th non-zero eigenvalue and $\bm{p}_i$ be the associated eigenvector of $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$. Denote $\bm{P}_{\bm{\theta}}:=\begin{bmatrix}
\bm{p}_1 & \bm{p}_2 &\cdots& \bm{p}_s
\end{bmatrix}$ and $\bm{\Lambda}=\text{diag}(\lambda_1,\lambda_2,\cdots,\lambda_s)$. Then clearly
$\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)=\bm{P}_{\bm{\theta}}\bm{\Lambda}\bm{P}_{\bm{\theta}}^\top$ and we compute the solution of~\eqref{eq:traj_g_partial} given by
\vspace{-0.1cm}
\begin{equation}\label{eq: g_star_partial}
\bm{g}^*=\bm{G}_{\bm{\theta}}^\top\bm{P}_{\bm{\theta}}\bm{\Lambda}^{-1}\bm{P}_{\bm{\theta}}^\top\left[\begin{array}{c}
\bm{w}(T_0-1);
\cdots;
\bm{w}(T-1);
\mathcal{X}(T_0-1)
\end{array}\right].
\end{equation}
\vspace{-0.6cm}
Next, we prove the existence and uniqueness of the trajectory generated by~\eqref{eq:traj_g_partial}. The goal is to show that given $\left(\bm{w}(T_0-1),\cdots ,\bm{w}(T-1), \mathcal{X}(T_0-1)\right)$ , any
$\bm{g} $ that satisfies~\eqref{eq:traj_g_partial} will generate the same trajectory using $\mathcal{H}\bm{g}$. So it is suffice to choose the closed-form solution in~\eqref{eq: g_star_partial}.
\begin{theorem}\label{thm: unque_trajectory0_partial}
If $\text{rank}(\mathcal{H})=n+Tm$, there exists at least one solution $\bm{g}^*$ such that~\eqref{eq:traj_g_partial} holds.
Given $\left(\bm{w}(T_0-1),\cdots ,\bm{w}(T-1), \mathcal{X}(T_0-1)\right)$ and any $\bm{g} $ that solves~\eqref{eq:traj_g_partial}, $\mathcal{H}\bm{g}^*$ generates the same unique trajectory under the control policy~\eqref{eq:control_policy} parameterized by $\bm{\theta}$.
\end{theorem}
The proof of Theorem~\ref{thm: unque_trajectory0_partial} is not as straightforward as Theorem~\ref{thm: unque_trajectory0}, because $\bm{G}_{\bm{\theta}}$ and $\bm{R}$ in~\eqref{eq:traj_g_partial} may not be full row-rank. The detailed proof is given in Appendix~\ref{app:thm_partial} and we sketch the proof as follows.
We use the mapping from $\bm{x}(0)$ to $\mathcal{X}(T_0-1)$ to show that the rank of $\bm{R}$ in~\eqref{eq:traj_g_partial} is at most $n+Tm$. Leveraging the relation in every $T_0$ blocks derived from~\eqref{eq:sys_extended}, we
show in Lemma~\ref{lem:null_partial} that $\text{rank}(\bm{G}_{\bm{\theta}})=n+Tm$ if $\text{rank}(\mathcal{H})=n+Tm$. The existence of a solution in~\eqref{eq:traj_g_partial} is therefore guaranteed by the same row-rank of the two sides. The uniqueness of the trajectory generated by $\mathcal{H}\bm{g}^*$ is proved by showing that the Null space $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$.
We can generate a trajectory $\mathcal{H}\bm{g}^*$ by randomly sampling $\mathcal{X}(T_0-1)$ and $\bm{w}(t)\in\mathcal{D}$ for $t=T_0-1,\cdots,T-1$. For the cost~\eqref{eq:Opt_obj} calculated on the trajectory of the length $K$, we setup $T=K+T_0-1$, and using the generated trajectory $\mathcal{H}\bm{g}^*$ from $T_0-1$ to $T-1$ to train the controller. The detailed algorithm can be found in Appendix~\ref{app:algorithm}.
\subsection{Span of historic trajectories}
Let $\bm{u}_{d,[0, L-1]}$ and $\bm{x}_{d,[0, L-1]}$ be the a length-$L$ input and state from past trajectory, and let the corresponding Hankel matrix $\mathcal{H}\in\real^{(Tm+Tn)\times (L-T+1})$ defined as
\vspace{-0.1cm}
\begin{equation}\label{eq:Hankel_u_x}
\begin{split}
&\underbrace{
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}
}_{\mathcal{H}}\quad
:=
\left[\begin{matrix}
\bm{u}_d(0) & \bm{u}_d(1) & \cdots & \bm{u}_d(L-T) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{u}_d(T-1) & \bm{u}_d(T) & \cdots & \bm{u}_d(L-1) \\
\hline \bm{x}_d(0) & \bm{x}_d(1) & \cdots & \bm{x}_d(L-T) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{x}_d(T-1) & \bm{x}_d(T) & \cdots & \bm{x}_d(L-1)
\end{matrix}\right].
\end{split}
\end{equation}
By the state-space version of Fundamental Lemma~\citep{de2019formulas} shown below, any linear combination of the columns of the Hankel matrix is a length-$T$ input-state trajectory of~\eqref{eq:sys_full}. The proof is provided in~\citep{de2019formulas} and we supplement it in Appendix~\ref{app: fundemental} for completeness.
\vspace{-0.1cm}
\begin{lemma}[ Fundamental Lemma]\label{lem:fundemental}
If $\text{rank}\left[\begin{smallmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, L-T+1}
\end{smallmatrix}\right]=n+Tm$,
then any length-$T$ input/state trajectory of system~\eqref{eq:sys_full} can be expressed as
$\left[\begin{smallmatrix}
\bm{u}_{[0, T-1]} \\
\bm{x}_{[0, T-1]}
\end{smallmatrix}\right]=\left[\frac{\bm{U}_{0, T, L-T+1}}{\bm{X}_{0, T, L-T+1}}\right] \bm{g}$,
where $\bm{g}\in \mathbb{R}^{L-T+1}$.
\end{lemma}
For the rank condition in Lemma~\ref{lem:fundemental} to hold, the minimum requirement on the length of the collected trajectory is $L-T+1=n+Tm$, namely, $L=(m+1)T-1+n$.
When the rank condition holds, linear combination of the columns of the Hankel matrix is also a length-$T$ trajectory of the system. Thus, we generate a trajectory of length $T$ using
\vspace{-0.1cm}
\begin{equation}\label{eq:Hankel_g0}
\begin{bmatrix}
\Tilde{\bm{u}}(0);
\cdots;
\Tilde{\bm{u}}(T-1);
\Tilde{\bm{x}}(0);
\cdots;
\Tilde{\bm{x}}(T-1)
\end{bmatrix}
=
\underbrace{
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}
}_{\mathcal{H}}\bm{g}.
\end{equation}
For convenience, we adopt the notation $\mathcal{H}_u=\bm{U}_{0, T, L-T+1} $, $\mathcal{H}_x=\bm{X}_{0, T, L-T+1} $ in the following sections. To represent the rows of blocks starting from the time $k=0,\cdots,T-1$, we denote
\vspace{-0.1cm}
\begin{equation}\label{eq:H_u_k}
\mathcal{H}_x^k :=
[
\bm{x}_d(k) \; \bm{x}_d(k+1)\, \cdots\, \bm{x}_d(L-T+k)
],\,
\mathcal{H}_u^k :=
[
\bm{u}_d(k) \; \bm{u}_d(k+1) \, \cdots \, \bm{u}_d(L-T+k)
].
\end{equation}
\subsection{Trajectory generation}
For generic RL algorithms, a trajectory is sampled from the system that starts from an initial state $\bm{x}(0)$ and subsequently implements the control policy $\bm{u}(k)=\bm{\theta} \bm{x}(k)+\bm{w}(k), \bm{w}(k)\sim\mathcal{D}$ for $k=0,\cdots,T-1$. Given $\bm{\theta}$, the probability density function of a trajectory is
\vspace{-0.1cm}
\begin{equation}\label{eq:pdf}
\begin{split}
p_{\pi_{\bm{\theta}}}(\bm{\tau})= p\left(\bm{x}(0)\right) \prod_{k=0}^{T-1} &p\left(\bm{\theta} \bm{x}(k)+\bm{w}(k)|\bm{x}(k)\right) p\left(\bm{x}(k+1) \mid \bm{x}(k), \bm{\theta} \bm{x}(k)+\bm{w}(k)\right),
\end{split}
\end{equation}
which is uniquely determined by $\bm{x}(0)$ and the sequence of perturbations $\bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1)$.
In the following, we generate trajectories for each updated $\bm{\theta}$ as if they truly come from the system starting from $\bm{x}(0)$ under perturbations on actions given by $\bm{w}(0),\cdots, \bm{w}(T-1)$.
Importantly, we use fixed historic trajectories $\left\{\bm{u}_d, \bm{y}_d\right\}$ where the Hankel matrix $\mathcal{H}$ in~\eqref{eq:Hankel_u_x} satisfies $\text{rank}(\mathcal{H})=n+Tm$, and $\bm{u}_d$ can come from controllers different from the control policy in~\eqref{eq:control_policy}.
The key is to use $\bm{x}(0)$ and $(\bm{w}(0),\allowbreak\cdots, \bm{w}(T-1))$ as extra constraints to find the $\bm{g}$ in~\eqref{eq:Hankel_g0} that generates the trajectory which follows the same distribution as~\eqref{eq:pdf}.
From the control policy $\bm{u}(k)=\bm{\theta} \bm{x}(k)+\bm{w}(k)$, the trajectory subject to the perturbations $\bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1)$ should satisfy
\vspace{-0.1cm}
\begin{equation}\label{eq: costrains_w}
\begin{split}
\left[\begin{array}{c}
\Tilde{\bm{u}}(0) \\
\vdots\\
\Tilde{\bm{u}}(T-1)\\
\end{array}\right]=
\underbrace{\begin{bmatrix}
\bm{\theta}& & & \\
& & \ddots& \\
& & & \bm{\theta} \\
\end{bmatrix}}_{\bm{I}_{T}\bigotimes\bm{\theta}}
\left[\begin{array}{c}
\Tilde{\bm{x}}(0)\\
\vdots\\
\Tilde{\bm{x}}(T-1)
\end{array}\right]
+\left[\begin{array}{c}
\bm{w}(0) \\
\vdots\\
\bm{w}(T-1)\\
\end{array}\right].
\end{split}
\end{equation}
Note that the generated initial state is given by $\Tilde{\bm{x}}(0)=\left[\begin{array}{cccc}
\mathcal{H}_x^0
\end{array}\right]\bm{g}$. Combining with~\eqref{eq: costrains_w} gives
\vspace{-0.1cm}
\begin{equation}\label{eq:traj_g0}
\underbrace{\begin{bmatrix}
\mathcal{H}_u-\left(\bm{I}_{T}\otimes\bm{\theta}\right) \mathcal{H}_x\\
\mathcal{H}_x^0
\end{bmatrix}}_{\bm{G}_{\bm{\theta}}}
\bm{g}=
\begin{bmatrix}
\bm{w}(0) \\
\vdots\\
\bm{w}(T-1)\\
\bm{x}(0)
\end{bmatrix}.
\end{equation}
Note that the matrix $\bm{G}_{\bm{\theta}}\in\real^{(Tm+n) \times (L-T+1)}$ is not a square matrix and its rank is determined by the length of historic trajectory $L$. When the trajectory is sufficiently long and $\text{rank}(\mathcal{H})=n+Tm$, we have $L-T+1>Tm+n$ and thus there might be multiple $\bm{g} $ where~\eqref{eq:traj_g0} holds.
We use the minimum-norm solution of~\eqref{eq:traj_g0} given by
\vspace{-0.1cm}
\begin{equation}\label{eq: g_star0}
\bm{g}^*=\bm{G}_{\bm{\theta}}^\top\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)^{-1}\left[\begin{array}{c}
\bm{w}(0);
\cdots;
\bm{w}(T-1);
\bm{x}(0)
\end{array}\right].
\end{equation}
In the next Theorem, we prove the existence and uniqueness of the trajectory generated by~\eqref{eq:traj_g0}. The goal is to show that given $\left(\bm{w}(0),\cdots ,\bm{w}(T-1), \bm{x}(0)\right)$, any $\bm{g} $ that satisfies~\eqref{eq:traj_g0} will generate the same trajectory using $\mathcal{H}\bm{g}$. So it is suffice to choose the closed-form solution in~\eqref{eq: g_star0}.
\vspace{-0.1cm}
\begin{theorem}\label{thm: unque_trajectory0}
If $\text{rank}(\mathcal{H})=n+Tm$, there exists at least one solution $\bm{g}$ such that~\eqref{eq:traj_g0} holds.
Given $\left(\bm{w}(0),\cdots ,\bm{w}(T-1), \bm{x}(0)\right)$ and any $\bm{g} $ that solves~\eqref{eq:traj_g0}, $\mathcal{H}\bm{g}^*$ generates the same unique trajectory under the control policy~\eqref{eq:control_policy} parameterized by $\bm{\theta}$.
\end{theorem}
Theorem~\ref{thm: unque_trajectory0} shows that $\mathcal{H}\bm{g}^*$ generates the unique trajectory that starts from an initial state $\bm{x}(0)$ and subsequently implements the control policy $\bm{u}(k)=\bm{\theta} \bm{x}(k)+\bm{w}(k), \bm{w}(k)\sim\mathcal{D}$. Hence, if we fix $\bm{\theta}$ in~\eqref{eq: g_star0} and sample $(\bm{x}(0), \bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1))$, then $\mathcal{H}\bm{g}^*$ will generate a batch of trajectories following the distribution~\eqref{eq:pdf} corresponding to the parameter $\bm{\theta}$. After the update of $\bm{\theta}$ in each episode of training, we generate a new batch of trajectories by updating $\bm{G}_{\bm{\theta}}$ in~\eqref{eq:traj_g0} and sampling new $(\bm{x}(0), \bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1))$. Thus, the generated trajectories adaptively follow the shifted distribution after updating $\bm{\theta}$. Importantly, it overcomes the negative perception in the field that there is no possibility to improve explorations beyond past trajectories~\citep{levine2020offline}. By sampling the noises $\bm{w}(k)\sim\mathcal{D}$, explorations can also be achieved through the generated trajectories. Hence, new trajectories are adaptively generated as if the system were being operated and explored under the updated control policies.
To prove Theorem~\ref{thm: unque_trajectory0}, we first show that the null space of $\bm{G}_{\bm{\theta}}$ is exactly the same as that of the Hankel matrix $\mathcal{H}$. Then, $\text{rank}(\mathcal{H})=n+Tm$ yields $\text{rank}(\bm{G}_{\bm{\theta}})=n+Tm$. The full row rank of $\bm{G}_{\bm{\theta}}$ implies that there exist at least one $\bm{g}$ where~\eqref{eq:traj_g0} holds. The uniqueness of trajectory generated by $\bm{g}$ follows from the fact that $\bm{G}_{\bm{\theta}}$ and $\mathcal{H}$ have the same null space. Details of the proof is given below.
\begin{proof}
We first prove that the null space $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$ from \textit{(i)} and \textit{(ii)} :
\textit{(i)} For all $\bm{q}\in \mathcal{N}(\mathcal{H})$, we have $[\mathcal{H}_x]\bm{q} =\mathbbold{0}_{Tn}$ and $[\mathcal{H}_u]\bm{q} =\mathbbold{0}_{Tm}$. Plugging in $\bm{G}_{\bm{\theta}}$ in~\eqref{eq:traj_g0} yields $\bm{G}_{\bm{\theta}}\bm{q} = \mathbbold{0}_{Tm+n} $. Namely, $\bm{q}\in\mathcal{N}(\bm{G}_{\bm{\theta}})$.
\textit{(ii)} For all $\bm{v}\in \mathcal{N}(\bm{G}_{\bm{\theta}})$, $\bm{G}_{\bm{\theta}}\bm{v}=\mathbbold{0}_{Tm+n}$ yields $\mathcal{H}_x^0\bm{v} =\mathbbold{0}_{n}$
and
$\mathcal{H}_u^k \bm{v}=\hat{\bm{\theta}}\mathcal{H}_x^k \bm{v} \text{ for } k=0,\cdots,T-1$. Thus, $\mathcal{H}_u^0 \bm{v}=\hat{\bm{\theta}}\mathcal{H}_x^0 \bm{v}=\mathbbold{0}_{m}$. From $\bm{x}(k+1) =\bm{A} \bm{x}(k)+\bm{B} \bm{u}(k)$, we have $\mathcal{H}_x^{k+1}=A \mathcal{H}_x^{k}+B \mathcal{H}_u^{k}.$ From $ \mathcal{H}_x^{0}=\mathbbold{0}_{n}$ and $ \mathcal{H}_u^{0}=\mathbbold{0}_{m}$, we
apply $\mathcal{H}_x^{k+1}=A \mathcal{H}_x^{k}+B \mathcal{H}_u^{k}$ and $\mathcal{H}_u^k \bm{v}=\hat{\bm{\theta}}\mathcal{H}_x^k \bm{v}$ alternately. This induces
$\mathcal{H}_x^k \bm{v} =\mathbbold{0}_{n}$ and $\mathcal{H}_u^k \bm{v} =\mathbbold{0}_{m}$ for $ k=0,\cdots,T-1$. Hence, $\mathcal{H}\bm{v} = \mathbbold{0}_{Tm+Tn} $.
Next, we prove the existence of the solution in~\eqref{eq:traj_g0}. Note that $\mathcal{H}\in\real^{(Tm+Tn) \times (L-T+1)}$. If $\text{rank}(\mathcal{H})=n+Tm$, then $\text{rank}(\mathcal{N}(\mathcal{H}))=(L-T+1)-(n+Tm)$.
Since $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$, then $\text{rank}(\mathcal{N}(\bm{G}_{\bm{\theta}}))=(L-T+1)-(n+Tm)$. It follows directly that $\text{rank}(\bm{G}_{\bm{\theta}})=(L-T+1)-\text{rank}(\mathcal{N}(\bm{G}_{\bm{\theta}}))=n+Tm$. Note that the number of rows of $\bm{G}_{\bm{\theta}}$ is $n+Tm$, then the full row-rank of $\text{rank}(\bm{G}_{\bm{\theta}})$ shows that there exists at least one solution such that~\eqref{eq:traj_g0} holds.
Lastly, we show the uniqueness of the generated trajectory. Suppose there exists $\bm{g}_1$ and $\bm{g}_2$, which are both solutions of~\eqref{eq:traj_g0} and $\mathcal{H}\bm{g}_1\neq \mathcal{H}\bm{g}_2$. Since $\bm{g}_1$ and $\bm{g}_2$ are both solution of~\eqref{eq:traj_g0}, then $\bm{G}_{\bm{\theta}}\bm{g}_1=\bm{G}_{\bm{\theta}}\bm{g}_1$ and thus $\left(\bm{g}_1-\bm{g}_2\right)\in\mathcal{N}(\bm{G}_{\bm{\theta}})$.
On the other hand, $\mathcal{H}\bm{g}_1\neq \mathcal{H}\bm{g}_2$ yields $\mathcal{H}\left(\bm{g}_1-\bm{g}_2\right)\neq 0$ and thus $\left(\bm{g}_1-\bm{g}_2\right)\notin\mathcal{N}(\mathcal{H})$. This contradicts that $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$. Hence, $\mathcal{H}\bm{g}_1= \mathcal{H}\bm{g}_2$, namely, the generated trajectories are identical.
\end{proof}
\vspace{-0.1cm}
\subsection{Algorithm}
By Theorem~\ref{thm: unque_trajectory0}, using historical data, given $\bm{x}(0)$ and perturbations on actions $\bm{w}(0),\cdots, \bm{w}(T-1)$,
a trajectory can be generated as if it comes from sampling the system with the current control policy.
The details of the algorithm is illustrated in Algorithm~\ref{alg: TrajGenFull}.
We also use REINFORCE policy gradient~\citep{Sutton2018RL} in Appendix~\ref{app: PG_state_feedback} as an example to show how to use the trajectory generation algorithm in RL methods.
The key benefit of Algorithm~\ref{alg: TrajGenFull}
is that it is adaptive to the updates of parameter $\bm{\theta}$ and $\bm{w}(t)$ for exploration. In particular, $\bm{w}(t)$ can be sampled from any distribution $\mathcal{D}$, making it versatile for different applications.
\begin{algorithm}[h]
\caption{Trajectory generation for state-feedback control }
\label{alg: TrajGenFull}
\begin{algorithmic}[1]
\renewcommand{\algorithmicrequire}{\textbf{Require: }}
\renewcommand{\algorithmicensure}{\textbf{Data collection:}}
\ENSURE Collect historic measurement of the system and stack each $T$-length input-output trajectory as Hankel matrix $\mathcal{H}$ shown in~\eqref{eq:Hankel_u_x} until $\text{rank}(\mathcal{H})=n+Tm$ \\
\renewcommand{\algorithmicensure}{\textbf{Data generation:}}
\ENSURE
\textit{Input} :Hankel matrix $\mathcal{H}$, weights $\bm{\theta}$ and the distribution $\mathcal{D}$ for the control policy, the batchsize $Q$ (number of the generated trajectories), the distribution $\mathcal{S}_x $ of the initial states\footnotemark \\
\SetKwFunction{FMain}{TrajectoryGen}
\SetKwProg{Fn}{Function}{:}{}
\Fn{\FMain{$\mathcal{H},\bm{\theta},\mathcal{D},Q, \mathcal{S}_x $}}{
Plug in $\bm{\theta}$ to compute $\bm{G}_{\bm{\theta}}=\begin{bmatrix}
\mathcal{H}_u-\left(\bm{I}_{T}\otimes\bm{\theta}\right) \mathcal{H}_x;
\mathcal{H}_x^0
\end{bmatrix}$
\For{$i = 1$ to $Q$}
{Sample $\bm{x}_i(0)$ from $\mathcal{S}_x $. Sample $\left\{\bm{w}_i(0),\cdots,\bm{w}_i(T-1)\right\}$ from $\mathcal{D}$.\\
Compute the coefficient $\bm{g}_i^*=\bm{G}_{\bm{\theta}}^\top\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)^{-1}\left[
\bm{w}_i(0);
\cdots;
\bm{w}_i(T-1);
\bm{x}_i(0)
\right]$.
\\
Generate the $i$-th trajectory $\bm{\tau}_i:=\left[
\Tilde{\bm{u}}_i(0);
\cdots;
\Tilde{\bm{u}}_i(T-1);
\Tilde{\bm{x}}_i(0);
\cdots;
\Tilde{\bm{x}}_i(T-1);
\right]=\mathcal{H}\bm{g}_i^*$.
}
\textbf{return} $ \left[\bm{\tau}_1,\cdots,\bm{\tau}_Q \right]$
}
\end{algorithmic}
\end{algorithm}
\footnotetext{The set of historic initial states in past trajectories can be used to estimate $\mathcal{S}_x $.}
\subsection{Span of historic trajectories}
Expanding the system transition dynamics gives the input-state response over $[0, T-1]$ as
$$
\left[\begin{array}{l}
\bm{u}_{[0, T-1]} \\
\bm{x}_{[0, T-1]}
\end{array}\right]=\left[\begin{array}{cc}
\bm{I}_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{array}\right]\left[\begin{array}{c}
\bm{u}_{[0, T-1]} \\
\bm{x}(0)
\end{array}\right]
$$
where $\bm{x}(0)$ is the system initial state, and
$$
\begin{aligned}
\mathcal{T}_{[0, T-1]} :=\left[\begin{array}{ccccc}
\bm{B} & \mathbbold{0}_{n\times m} & \mathbbold{0}_{n\times m} & \cdots & \mathbbold{0}_{n\times m} \\
\bm{A} \bm{B} & \bm{B} & \mathbbold{0}_{n\times m} & \cdots & \mathbbold{0}_{n\times m} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
\bm{A}^{T-2} \bm{B} & \bm{A}^{T-3} \bm{B} & \bm{A}^{T-4} \bm{B} & \cdots & \mathbbold{0}_{n\times m}
\end{array}\right]
\mathcal{O}_{[0, T-1]} :=\left[\begin{array}{c}
\bm{I}_{n} \\
\bm{A} \\
\vdots \\
\bm{A}^{T-1}
\end{array}\right]
\end{aligned}
$$
are the Toeplitz and observability matrices of order $T$.
Let now $\bm{u}_{d,[0, L-1]}$ and $\bm{x}_{d,[0, L-1]}$ be the $L$-length input-output data collected during an experiment, and let
\begin{equation}\label{eq:Hankel_u_x}
\begin{split}
&\left[\begin{array}{cccc}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{array}\right]\quad:=\left[\begin{array}{cccc}
\bm{u}_d(0) & \bm{u}_d(1) & \cdots & \bm{u}_d(L-T) \\
\bm{u}_d(1) & \bm{u}_d(2) & \cdots & \bm{u}_d(L-T+1) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{u}_d(T-1) & \bm{u}_d(T) & \cdots & \bm{u}_d(L-1) \\
\hline \bm{x}_d(0) & \bm{x}_d(1) & \cdots & \bm{x}_d(L-T) \\
\bm{x}_d(1) & \bm{x}_d(2) & \cdots & \bm{x}_d(L-T+1) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{x}_d(T-1) & \bm{x}_d(T) & \cdots & \bm{x}_d(L-1)
\end{array}\right]
\end{split}
\end{equation}
be the corresponding Hankel matrix $\mathcal{H}$.
Let
$$
\bm{X}_{0, L-T+1}:=\left[\begin{array}{llll}
\bm{x}_d(0) & \bm{x}_d(1) & \ldots & \bm{x}_d(L-T)
\end{array}\right].
$$
Then we have
\begin{equation}\label{eq:Hankel_u_\bm{x}(k)ransition}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}
=\begin{bmatrix}
I_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{bmatrix}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix}
\end{equation}
Follow this expression, the fundamental Lemma shows that any linear combination of the columns of the Hankel matrix is a T -long input/output trajectory of~\eqref{eq:sys_full}.
\begin{lemma}[Fundamental Lemma]\label{lem:fundemental}
If $\text{rank}\left[\begin{array}{cccc}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{array}\right]=n+Tm$,
then any $T$-long input/output trajectory of system~\eqref{eq:sys_full} can be expressed as
$$
\left[\begin{array}{l}
\bm{u}_{[0, T-1]} \\
\bm{x}_{[0, T-1]}
\end{array}\right]=\left[\frac{\bm{U}_{0, T, L-T+1} }{\bm{X}_{0, T, L-T+1} }\right] g
$$
where $g \in \mathbb{R}^{L-T+1}$.
Moreover, any linear combination of the columns of the Hankel matrix, that is
$$
\left[\begin{array}{c}
\bm{U}_{0, T, L-T+1} \\
\hline \bm{X}_{0, T, L-T+1}
\end{array}\right] g
$$
is a $T$-long input/output trajectory of~\eqref{eq:sys_full}.
\end{lemma}
To make the rank condition in Lemma~\ref{lem:fundemental} hold, the minimum requirement on the length of the collected data is $L-T+1=n+Tm$, namely, $L=(m+1)T-1+n$.
When the rank condition holds, linear combination of the columns of the Hankel matrix is also a $T$-length trajectory of the system. We generate a trajectory of length $T$ using
\begin{equation}\label{eq:Hankel_g0}
\left[\begin{array}{c}
\Tilde{\bm{u}}(0) \\
\vdots\\
\Tilde{\bm{u}}(T-1)\\
\Tilde{\bm{x}}(0)\\
\vdots\\
\Tilde{\bm{x}}(T-1)
\end{array}\right]=
\underbrace{ \left[\begin{array}{cccc}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{array}\right]}_{\mathcal{H}}g
\end{equation}
For convenience, we adopt the notation $\mathcal{H}_u=\bm{U}_{0, T, L-T+1} $, $\mathcal{H}_x=\bm{X}_{0, T, L-T+1} $ in the following sections. To represent the rows of blocks starting from the time $k=0,\cdots,T-1$, we denote
\begin{equation}
\mathcal{H}_x^k :=\left[\begin{array}{cccc}
\bm{x}_d(k) & \bm{x}_d(k+1) & \cdots & \bm{x}_d(L-T+k) \\
\end{array}\right]
\end{equation}
\begin{equation}
\mathcal{H}_u^k :=\left[\begin{array}{cccc}
\bm{u}_d(k) & \bm{u}_d(k+1) & \cdots & \bm{u}_d(L-T+k) \\
\end{array}\right].
\end{equation}
\subsection{Trajectory generation}
For generic policy gradient algorithm, a trajectory is collected from the system that start from a initial state $\bm{x}(0)$, subject to the control law $\bm{u}(k)=\bm{\theta} \bm{x}(k)+\bm{w}(k)$ for $k=0,\cdots,T-1$. The probability density function of a trajectory is given by
\begin{equation}\label{eq:pdf}
\begin{split}
p_{\pi_\theta}(\tau)= p\left(\bm{x}(0)\right) \prod_{k=0}^{T-1} &p\left(\bm{w}(k)\right) p\left(\bm{x}(k+1) \mid \bm{x}(k), u(k)\right),
\end{split}
\end{equation}
which is uniquely determined by $\bm{x}(0)$ and the sequence of perturbations $\bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1)$.
In the following, we show the algorithm to generate the trajectory subject to $\big\{\bm{x}(0),\bm{w}(0),\cdots, \allowbreak\bm{w}(T-1)\big\}$ from the Hankel matrix instead of truly implemented on the system.
The key is to use $\left\{\bm{x}(0),\bm{w}(0),\cdots, \bm{w}(T-1)\right\}$ as extra constraint to find the $g$ in~\eqref{eq:Hankel_g0} that generate the same trajectory as if it is sampled from the system.
The trajectory subject to the noise vector $\bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T)$ satisfy
\begin{equation}
\left[\begin{array}{c}
\Tilde{\bm{u}}(0) \\
\vdots\\
\Tilde{\bm{u}}(T)\\
\end{array}\right]=
\underbrace{\begin{bmatrix}
\theta& & & \\
& \theta& & \\
& & \ddots& \\
& & & \theta \\
\end{bmatrix}}_{I_{T}\bigotimes\theta}
\left[\begin{array}{c}
\Tilde{\bm{x}}(0)\\
\vdots\\
\Tilde{\bm{x}}(T)
\end{array}\right]
+\left[\begin{array}{c}
\bm{w}(0) \\
\vdots\\
\bm{w}(T)\\
\end{array}\right]
\end{equation}
This indicates
\begin{equation}
\begin{split}
&\left[\begin{array}{c}
\mathcal{H}_u
\end{array}\right]g\quad= \begin{bmatrix}
\theta& & & \\
& \theta& & \\
& & \ddots& \\
& & & \theta \\
\end{bmatrix}
\left[\begin{array}{cccc}
\mathcal{H}_x
\end{array}\right]g
+\left[\begin{array}{c}
\bm{w}(0) \\
\vdots\\
\bm{w}(T)\\
\end{array}\right]
\end{split}
\end{equation}
Note that
\begin{equation}
\left[\begin{array}{cccc}
\mathcal{H}_x^0
\end{array}\right]:=\left[\begin{array}{cccc}
\bm{x}_d(0) & \bm{x}_d(1) & \cdots & \bm{x}_d(L-T) \\
\end{array}\right],
\end{equation}
the generated initial state is given by
\begin{equation}
\Tilde{\bm{x}}(0)=\left[\begin{array}{cccc}
\mathcal{H}_x^0
\end{array}\right]g.
\end{equation}
The generated trajectory should satisfy
\begin{equation}\label{eq:traj_g0}
\underbrace{\begin{bmatrix}
\mathcal{H}_u-\left(I_{T}\otimes\theta\right) \mathcal{H}_x\\
\mathcal{H}_x^0
\end{bmatrix}}_{G_\theta}
g=
\begin{bmatrix}
\bm{w}(0) \\
\vdots\\
\bm{w}(T-1)\\
\bm{x}(0)
\end{bmatrix}.
\end{equation}
Note that the matrix $G_\theta\in\real^{(Tm+n) \times (L-T+1)}$ is not a square matrix and its rank is determined by the length of historic trajectory $L$. When there is sufficient length of trajectory such that $\text{rank}(\mathcal{H})=n+Tm$, we have $L-T+1>Tm+n$ and thus there might be multiple $g $ such that~\eqref{eq:traj_g0} holds. We show in the next Lemma that the Null space of $G_\theta$ is exactly the same as the Hankel matrix $\mathcal{H}$. Hence, any $g $ such that~\eqref{eq:traj_g0} holds will generate the unique trajectory subject to $\left\{\bm{x}(0),\bm{w}(0),\cdots, \bm{w}(T-1)\right\}$.
\begin{lemma}
The null space $\mathcal{N}(G_\theta)$ is the same as $\mathcal{N}(\mathcal{H})$. Moreover, if $\text{rank}(\mathcal{H})=n+Tm$, then the matrix $G_\theta\in\real^{(Tm+n) \times (L-T+1)}$ is full row rank. Namely, $\text{rank}(G_\theta)=n+Tm$.
\end{lemma}
\begin{proof}
For all $q\in \mathcal{N}(\mathcal{H})$, we have $[\mathcal{H}_x] q =\mathbbold{0}_{Tn}$ and $[\bm{U}_{0, T, L-T+1} ] q =\mathbbold{0}_{Tm}$. Plugging in the expression of $G_{\theta}$ yields $G_{\theta}q = \mathbbold{0}_{Tm+n} $. Namely, $q\in\mathcal{N}(G_{\theta})$.
For all $v\in \mathcal{N}(G_\theta)$, we have
\begin{equation}
\left[\begin{array}{c}
\mathcal{H}_u-\left(I_{T}\otimes\theta\right) \mathcal{H}_x\\
\mathcal{H}_x^0
\end{array}\right]v=\mathbbold{0}_{Tm+n}
\end{equation}
This gives
\begin{equation}\label{eq:fullC_null}
\begin{split}
&\mathcal{H}_u^k v=\hat{\theta}\mathcal{H}_x^k v \text{ for } k=0,\cdots,T-1\\
&\mathcal{H}_x^0v =\mathbbold{0}_{n}
\end{split}
\end{equation}
From $\bm{x}(k+1)=A \bm{x}(k)+B u(k)$, we have
\begin{equation}
\mathcal{H}_x^{k+1}=A \mathcal{H}_x^{k}+B \mathcal{H}_u^{k}
\end{equation}
Pluging in~\eqref{eq:fullC_null} yields
$\mathcal{H}_x^k v =\mathbbold{0}_{n}$ and $\mathcal{H}_u^k v =\mathbbold{0}_{m}$ for $ k=0,\cdots,T-1$. Hence, $\mathcal{H}v = \mathbbold{0}_{Tm+Tn} $. Namely, $v\in\mathcal{N}(\mathcal{H})$.
Note that $H\in\real^{(Tm+Tn) \times (L-T+1)}$. If $\text{rank}(\mathcal{H})=n+Tm$, then the rank of Null space is $\text{rank}(\mathcal{N}(\mathcal{H}))=(L-T+1)-(n+Tm)$.
Since $\mathcal{N}(G_\theta)$ is the same as $\mathcal{N}(\mathcal{H})$, then $\text{rank}(\mathcal{N}(G_\theta))=(L-T+1)-(n+Tm)$. It follows directly that $\text{rank}(\mathcal{H})=(L-T+1)-\text{rank}(\mathcal{N}(G_\theta))=n+Tm$.
\end{proof}
If $\text{rank}(G_\theta)=n+Tm$, then there exist at least one solution such that~\eqref{eq:traj_g0} holds. We pick the minimum-norm solution of~\eqref{eq:traj_g0} given by
\begin{equation}
g=G_\theta^\top\left(G_\theta G_\theta^\top\right)^{-1}\left[\begin{array}{c}
\bm{w}(0) \\
\vdots\\
\bm{w}(T-1)\\
\bm{x}(0)
\end{array}\right].
\end{equation}
The proposed trajectory generation algorithm is illustrated as follows
\begin{algorithm}
\caption{Policy Gradient with trajectory generation when the state is observable }
\begin{algorithmic}[1]
\renewcommand{\algorithmicrequire}{\textbf{Require: }}
\renewcommand{\algorithmicensure}{\textbf{Data collection:}}
\REQUIRE The length $T$ of trajectory to be generated, the dimension of state $n$, the dimension of action $m$, the learning rate $\alpha$
\ENSURE Collect historic measurement of the system and stack each $T$-length input-output trajectory as Hankel matrix $\mathcal{H}$ shown in~\eqref{eq:Hankel_u_x} until $\text{rank}(\mathcal{H})=n+Tm$ \\
\renewcommand{\algorithmicensure}{\textbf{Policy Gradient with Data generation:}}
\ENSURE
\textit{Initialisation} :Initial weights $\theta$ for control network
\FOR {$episode = 1$ to $I$}
\STATE Plug in $\theta$ to compute $G_\theta=\begin{bmatrix}
\mathcal{H}_u-\left(I_{T}\otimes\theta\right) \mathcal{H}_x\\
\mathcal{H}_x^0
\end{bmatrix}$
\FOR {$i = 1$ to $Q$}
\STATE Uniformly sample $x^i(0)$ from historic measurement of the system. Sample $\left\{w^i(0),\cdots,w^i(T-1)\right\}$ from the distribution $\mathcal{D}$.
\STATE Compute the coefficient $g_i=G_\theta^\top\left(G_\theta G_\theta^\top\right)^{-1}\left[
w^i(0)^\top
\cdots
w^i(T-1)^\top
x^i(0)^\top
\right]^\top$
\STATE Generate the $i$-th trajectory $\tau_i:=\left[
\Tilde{\bm{u}}^i(0)^\top
\cdots
\Tilde{\bm{u}}^i(T-1)^\top
\Tilde{\bm{x}}^i(0)^\top
\cdots
\Tilde{\bm{x}}^i(T-1)^\top
\right]^\top=\mathcal{H}g_i$
\ENDFOR
\STATE Compute the gradient $ \nabla J(\theta) = \frac{1}{Q}\sum_{i=1}^{Q} c(\tau_i)\sum_{t=1}^{T} \nabla_{\theta}\log\pi_{\theta} (\Tilde{\bm{u}}^i(t)|\Tilde{\bm{x}}^i(t)) $
\STATE Update weights in the neural network by gradient descent:
$\theta \leftarrow \theta-\alpha \nabla J(\theta) $
\ENDFOR
\end{algorithmic}
\end{algorithm}
\subsection{Fundemental Lemma}\label{app: fundemental}
For state feedback control, $\bm{y}(t)=\bm{x}(t)$ ($\bm{C}=\bm{I}_n$) and the system transition dynamics is reduced to $\bm{x}(k+1) =\bm{A} \bm{x}(k)+\bm{B} \bm{u}(k)$. Expanding the dynamics for $k=0, \cdots, T$ gives the input-state response over $[0, T-1]$ as
\begin{equation}\label{eq: stack_transition}
\begin{bmatrix}
\bm{u}_{[0, T-1]} \\
\bm{x}_{[0, T-1]}
\end{bmatrix}=\begin{bmatrix}
\bm{I}_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{bmatrix}
\begin{bmatrix}
\bm{u}_{[0, T-1]} \\
\bm{x}(0)
\end{bmatrix},
\end{equation}
where $\mathcal{T}_{[0, T-1]}$ and $\mathcal{O}_{[0, T-1]}$ are the Toeplitz and observability matrices of order $T$ represented as~\citep{de2019formulas}
$$
\begin{aligned}
\mathcal{T}_{[0, T-1]} :=\left[\begin{array}{ccccc}
\bm{B} & \mathbbold{0}_{n\times m} & \mathbbold{0}_{n\times m} & \cdots & \mathbbold{0}_{n\times m} \\
\bm{A} \bm{B} & \bm{B} & \mathbbold{0}_{n\times m} & \cdots & \mathbbold{0}_{n\times m} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
\bm{A}^{T-2} \bm{B} & \bm{A}^{T-3} \bm{B} & \bm{A}^{T-4} \bm{B} & \cdots & \mathbbold{0}_{n\times m}
\end{array}\right]
\quad\mathcal{O}_{[0, T-1]} :=\left[\begin{array}{c}
\bm{I}_{n} \\
\bm{A} \\
\vdots \\
\bm{A}^{T-1}
\end{array}\right].
\end{aligned}
$$
On this basis, the Hankel Matrix $\mathcal{H}$ can be represented as
\begin{equation}\label{eq:Hankel_u_x(k)ransition}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}
=\begin{bmatrix}
I_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{bmatrix}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix},
\end{equation}
where
$X_{0, L-T+1}:=\left[\begin{array}{llll}
\bm{x}_d(0) & \bm{x}_d(1) & \ldots & \bm{x}_d(L-T)
\end{array}\right].$
Now consider a trajectory $[
\hat{\bm{u}}_{[0, T-1]};
\hat{\bm{x}}_{[0, T-1]}
]$ starting from an initial state $\hat{\bm{x}}(0)$ and evolves with the sequence of actions $\hat{\bm{u}}_{[0, T-1]}$. If $\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix}$ is full row rank, namely $\text{rank}(\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix})=n+Tm$, then there exists $\hat{\bm{g}}\in\real^{L-T+1}$ such that $\begin{bmatrix}
\hat{\bm{u}}_{[0, T-1]} \\
\hat{\bm{x}}(0)
\end{bmatrix}=\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix}\hat{\bm{g}}$. By~\eqref{eq: stack_transition},
\begin{equation}
\begin{split}
\begin{bmatrix}
\hat{\bm{u}}_{[0, T-1]}\\
\hat{\bm{x}}_{[0, T-1]}
\end{bmatrix}
&=\begin{bmatrix}
\bm{I}_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{bmatrix}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix}\hat{\bm{g}}\\
&=\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}\hat{\bm{g}},
\end{split}
\end{equation}
where the second equation follows from the relation in~\eqref{eq:Hankel_u_x(k)ransition}. This complete the proof of Lemma~\eqref{lem:fundemental}.
\subsection{Policy gradient algorithm}\label{app: PG_state_feedback}
\begin{algorithm}[H]
\caption{Policy Gradient with trajectory generation }
\label{alg: PG}
\begin{algorithmic}[1]
\renewcommand{\algorithmicrequire}{\textbf{Require: }}
\renewcommand{\algorithmicensure}{\textbf{Data collection:}}
\REQUIRE The length $T$ of trajectory, the learning rate $\alpha$, total number of episode $I$\\
\renewcommand{\algorithmicensure}{\textbf{Policy Gradient with Data generation:}}
\ENSURE
\textit{Initialisation} :Initial weights $\bm{\theta}$ for control network
\FOR {$episode = 1$ to $I$}
\STATE Generate a batch of $Q$ trajectories $ \left[\bm{\tau}_1,\cdots,\bm{\tau}_Q \right]=$\texttt{TrajectoryGen}$\left(\mathcal{H},\bm{\theta},\mathcal{D},Q\right) $
\STATE Compute the gradient $ \nabla J(\bm{\theta}) = \frac{1}{Q}\sum_{i=1}^{Q} c(\bm{\tau}_i)\sum_{t=1}^{T} \nabla_{\bm{\theta}}\log\pi_{\bm{\theta}} (\Tilde{\bm{u}}_i(t)|\Tilde{\bm{x}}_i(t)) $
\STATE Update weights in the neural network by gradient descent:
$\bm{\theta} \leftarrow \bm{\theta}-\alpha \nabla J(\bm{\theta}) $
\ENDFOR
\end{algorithmic}
\end{algorithm}
\subsection{Transition dynamics with extended states}\label{app: transition_partial}
Expanding the transition dynamics in~\eqref{eq:sys_full} from time $0$ to $T_0$ gives
\begin{equation}\label{eq:y_u_traj_transition}
\bm{y}_{[0, T_0-1]}=\mathcal{O}_{[0, T_0-1]}\bm{x}(0)+\mathcal{T}_{[0, T_0-1]}\bm{u}_{[0, T_0-2]}\end{equation}
where $\mathcal{T}_{[0, T-1]}$ and $\mathcal{O}_{[0, T-1]}$ are the Toeplitz and observability matrices of order $T_0$ represented as
$$
\begin{aligned}
\mathcal{T}_{[0, T_0-1]} &:=\left[\begin{array}{ccccc}
\bm{C}\bm{B}&\mathbbold{0}_{d\times m}&\mathbbold{0}_{d\times m}& \cdots &\mathbbold{0}_{d\times m}\\
\bm{C} \bm{A}\bm{B}& \bm{C}\bm{B}&\mathbbold{0}_{d\times m}& \cdots &\mathbbold{0}_{d\times m}\\
\vdots & \vdots & \vdots & \ddots & \vdots \\
\bm{C} \bm{A}^{T_0-2}\bm{B}& \bm{C}\bm{A}^{T_0-3}\bm{B}& \bm{C}\bm{A}^{T_0-4}\bm{B}& \cdots & \mathbbold{0}_{d\times m}
\end{array}\right] \quad
\mathcal{O}_{[0, T_0-1]} :=\left[\begin{array}{c}
\bm{C} \\
\bm{C}\bm{A} \\
\vdots \\
\bm{C}\bm{A}^{T_0-1}
\end{array}\right].
\end{aligned}
$$
Since the system~\eqref{eq:sys_full} is observable, $\mathcal{O}_{[0, T_0-1]}$ is full column rank. Thus,
\begin{equation}
\bm{x}(0)=\underbrace{\left(\mathcal{O}_{[0, T_0-1]}^\top\mathcal{O}_{[0, T_0-1]}\right)^{-1}
\mathcal{O}_{[0, T_0-1]}^{\top}}_{\mathcal{O}_{[0, T_0-1]}^\dagger} \left(\bm{y}_{[0, T_0-1]}-\mathcal{T}_{[0, T_0-1]}\bm{u}_{[0, T_0-2]}\right)
\end{equation}
Then pluging in the expression of $\bm{y}(T_0)$ yields
\begin{equation}\label{eq:y_T_0}
\begin{split}
\bm{y}(T_0)&=\bm{C}\bm{A}^{T_0}\bm{x}(0)+\bm{C}\bm{A}^{T_0-1}\bm{B}\bm{u}(0)+\cdots+\bm{C}\bm{B}\bm{u}(T_0-1)\\
&=\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \left(\bm{y}_{[0, T_0-1]}-\mathcal{T}_{[0, T_0-1]}\bm{u}_{[0, T_0-2]}\right)+\mathcal{T}_{[T_0, T_0]}\bm{u}_{[0, T_0-2]}\\
&= \bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \bm{y}_{[0, T_0-1]}+\left(\mathcal{T}_{[T_0, T_0]}-\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \mathcal{T}_{[0, T_0-1]} \right)\bm{u}_{[0, T_0-2]}
\end{split}
\end{equation}
where
$$
\begin{aligned}
\mathcal{T}_{[T_0, T_0]} &:=\left[\begin{array}{ccccc}
\bm{C}\bm{A}^{T_0-1} \bm{B} & \bm{C}\bm{A}^{T_0-2} \bm{B} & \bm{C}\bm{A}^{T_0-3} \bm{B} & \cdots & \bm{C}\bm{B}\\
\end{array}\right].
\end{aligned}
$$
Stacking the observations and the outputs together yields
\begin{equation}
\left[\begin{array}{c}
\bm{y}(1)\\
\vdots \\
\bm{y}(T_0)\\
\bm{u}(1)\\
\vdots \\
\bm{u}(T_0-1)\\
\end{array}\right]=\Tilde{\bm{A}} \left[\begin{array}{c}
\bm{y}(0)\\
\vdots \\
\bm{y}(T_0-1)\\
\bm{u}(0)\\
\vdots \\
\bm{u}(T_0-2)\\
\end{array}\right]
+\Tilde{\bm{B}}\bm{u}(T_0-1),
\end{equation}
where
\begin{equation}
\begin{split}
&\Tilde{\bm{A}}=
\begin{pmatrix}
\begin{matrix}
\bm{0}& \bm{I}_d & \bm{0}& \bm{0}&\cdots & \bm{0}\\
\bm{0}& \bm{0}& \bm{I}_d & \bm{0}& \cdots & \bm{0}\\
\vdots & \vdots& \vdots & \vdots & \ddots & \vdots \\
\bm{0}& \bm{0} & \bm{0}& \bm{0}& \cdots & \bm{I}_d
\end{matrix}
& \hspace*{-\arraycolsep}\vline\hspace*{-\arraycolsep} & \mbox{\normalfont\Large\bfseries 0} \\
\hline
\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger& \hspace*{-\arraycolsep}\vline\hspace*{-\arraycolsep} & \mathcal{T}_{[T_0, T_0]}-\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \mathcal{T}_{[0, T_0-1]} \\
\hline
\mbox{\normalfont\Large\bfseries 0} & \hspace*{-\arraycolsep}\vline\hspace*{-\arraycolsep} &
\begin{matrix}
\bm{0}& \bm{I}_m & \bm{0}& \bm{0}&\cdots & \bm{0}\\
\bm{0}& 0& \bm{I}_m & \bm{0}& \cdots & \bm{0}\\
\vdots & \vdots& \vdots & \vdots & \ddots & \vdots \\
\bm{0}& 0& \bm{0}& \bm{0}& \cdots & \bm{I}_m \\
\end{matrix} \\
\hline
\mbox{\normalfont\Large\bfseries 0} & \hspace*{-\arraycolsep}\vline\hspace*{-\arraycolsep} & \mbox{\normalfont\Large\bfseries 0}
\end{pmatrix},
\Tilde{\bm{B}}=
\begin{pmatrix}
\begin{matrix}
\bm{0}\\
\bm{0}\\
\vdots \\
\bm{0}
\end{matrix}\\
\hline
\bm{0}\\
\hline
\begin{matrix}
\bm{0}\\
\bm{0}\\
\vdots \\
\bm{0}
\end{matrix}\\
\hline
\bm{I}_m
\end{pmatrix}.
\end{split}
\end{equation}
\subsection{Policy Gradient for Extended States }~\label{app:Policy Gradient}
The basic policy gradient algorithm is~\citet{Sutton2018RL}
\begin{equation}
\begin{split}
\nabla_{\bm{\theta}} \mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}}[c(\bm{\tau})] &=\nabla_{\bm{\theta}} \int \pi_{\bm{\theta}}(\bm{\tau}) c(\bm{\tau}) d \tau \\
&=\int \nabla_{\bm{\theta}} \pi_{\bm{\theta}}(\bm{\tau}) c(\bm{\tau}) d \tau \\
&=\int \pi_{\bm{\theta}}(\bm{\tau}) \nabla_{\bm{\theta}} \log \pi_{\bm{\theta}}(\bm{\tau}) c(\bm{\tau}) d \tau \\
&=\mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}}[c(\bm{\tau}) \nabla_{\bm{\theta}} \log \pi_{\bm{\theta}}(\bm{\tau})].
\end{split}
\end{equation}
The probability of a trajectory with length $T$ is
\begin{equation}\label{eq:prob_traj}
\pi_\theta(\bm{\tau})= p\left(\mathcal{X}\left(T_0\right)\right) \prod_{t=T_0}^{T-1} p_{\pi_{\bm{\theta}}}\left(\bm{u}(t)|\mathcal{X}(t)\right) p\left(\mathcal{X}(t+1)|\mathcal{X}(t), \bm{u}(t)\right) .
\end{equation}
Expanding the terms in~\eqref{eq:prob_traj} and canceling the transition probability independent of $\bm{\theta}$, we have
\begin{equation}
\nabla_{\bm{\theta}}\log \pi_\theta(\bm{\tau}) =\sum_{t=0}^{T-1} \nabla_{\bm{\theta}}\log p_{\bm{\pi}_{\bm{\theta}}}\left(\bm{u}(k) \mid \bm{y}(k)\right),
\end{equation}
and therefore,
\begin{equation}
\nabla_{\bm{\theta}}\mathbb{E}_{\pi_\theta}[c(\bm{\tau})] =\mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})}\left[c(\bm{\tau})\sum_{k=0}^{K-1} \nabla_{\bm{\theta}} \log p_{\bm{\pi}_{\bm{\theta}}}\left(\bm{u}(k) \mid \bm{y}(k)\right)\right]
\end{equation}
Hence, the policy gradient algorithm still holds for the output-feedback case.
\subsection{Proof of Theorem~\ref{thm: unque_trajectory0_partial}}\label{app:thm_partial}
To prove Theorem~\ref{thm: unque_trajectory0_partial}, we need to make use of the rank condition of $\bm{G}_{\bm{\theta}}$ and $\bm{R}$ in~\eqref{eq:traj_g_partial}. We first
show in Lemma~\ref{lem:null_partial} about the null space and rank condition induced from the condition $\text{rank}(\mathcal{H})=n+Tm$.
\begin{lemma}\label{lem:null_partial}
If the observability matrix $\mathcal{O}_{[0, T_0-1]}$ is
full column rank, then
the null space $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$. Moreover, if $\text{rank}(\mathcal{H})=n+Tm$, then $\text{rank}(\bm{G}_{\bm{\theta}})=n+Tm$.
\end{lemma}
\begin{proof}
We first prove that the null space $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$ from \textit{(i)} and \textit{(ii)} :
\textit{(i)} For all $\bm{q}\in \mathcal{N}(\mathcal{H})$, we have $[\mathcal{H}_y]\bm{q} =\mathbbold{0}_{Tn}$ and $[\mathcal{H}_u]\bm{q} =\mathbbold{0}_{Tm}$. Plugging in the expression of $\bm{G}_{\bm{\theta}}$ yields $\bm{G}_{\bm{\theta}}\bm{q} = \mathbbold{0}_{Tm+n} $. Namely, $\bm{q}\in\mathcal{N}(\bm{G}_{\bm{\theta}})$.
\textit{(ii)} For all $\bm{v}\in \mathcal{N}(\bm{G}_{\bm{\theta}})$, we have
\begin{equation}
\left[\begin{array}{c}
\mathcal{H}_u^{T_0 -1: T-1} -\left(\bm{I}_{T-T_0}\otimes \theta\right) \mathcal{H}_y^{T_0 -1: T-1} \\
\mathcal{H}_y^{0 : T_0-1}\\
\mathcal{H}_u^{0 : T_0-2}
\end{array}\right]\bm{v}=\mathbbold{0}_{Tm+T_0 d} \; ,
\end{equation}
which gives
\begin{equation}\label{eq:fullC_null2}
\begin{split}
&\mathcal{H}_u^k \bm{v}=\theta\mathcal{H}_y^k \bm{v} \text{ for } k=T_0,\cdots,T-1\\
&\mathcal{H}_y^{0 : T_0-1} \bm{v} =\mathbbold{0}_{T_0 d} \\
&\mathcal{H}_u^{0 : T_0-2} \bm{v} =\mathbbold{0}_{T_0 m} \;.
\end{split}
\end{equation}
From~\eqref{eq:y_T_0}, we have ,
\begin{equation}\label{eq:induction_y_u}
\begin{split}
\mathcal{H}_y^{k}
&=\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger\mathcal{H}_y^{k-T_0:k-1}+\left(\mathcal{T}_{[T_0, T_0]}-\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \mathcal{T}_{[0, T_0-1]} \right)\mathcal{H}_u^{k-T_0:k-2}
\end{split}
\end{equation}
for $k=T_0,\cdots,T-1$.
Plugging~\eqref{eq:fullC_null2} in~\eqref{eq:induction_y_u} induces
$\mathcal{H}_y^k \bm{v} =\mathbbold{0}_{d}$ and $\mathcal{H}_u^k \bm{v} =\mathbbold{0}_{m}$ for $ k=0,\cdots,T-1$. Hence, $\mathcal{H}\bm{v} = \mathbbold{0}_{Tm+Td} $. Namely, $\bm{v}\in\mathcal{N}(\mathcal{H})$.
Next, we prove the rank condition. Note that $\mathcal{H}\in\real^{(Tm+Tn) \times (L-T+1)}$. If $\text{rank}(\mathcal{H})=n+Tm$, then the rank of Null space is $\text{rank}(\mathcal{N}(\mathcal{H}))=(L-T+1)-(n+Tm)$.
Since $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$, then $\text{rank}(\mathcal{N}(\bm{G}_{\bm{\theta}}))=(L-T+1)-(n+Tm)$. It follows directly that $\text{rank}(\bm{G}_{\bm{\theta}})=(L-T+1)-\text{rank}(\mathcal{N}(\bm{G}_{\bm{\theta}}))=n+Tm$.
\end{proof}
Then, we are ready to prove Theorem~\ref{thm: unque_trajectory0_partial} as follows.
\begin{proof}
We first prove the existence of the solution in~\eqref{eq:traj_g_partial}. From~\eqref{eq:y_u_traj_transition}, we have
$$
\mathcal{X}(T_0-1):=\left[\begin{array}{l}
\bm{u}_{[0, T_0-2]} \\
\bm{y}_{[0, T_0-1]}
\end{array}\right]=\left[\begin{array}{cc}
I_{(T_0-1) m} & \mathbbold{0}_{(T_0-1) m \times n} \\
\mathcal{T}_{[0,T_0-1]} & \mathcal{O}_{[0,T_0-1]}
\end{array}\right]
\begin{bmatrix}
\bm{u}_{[0, T_0-2]} \\
\bm{x}(0)
\end{bmatrix}
$$
The number of element in the vector $[\bm{u}_{[0, T_0-2]}^\top, \bm{x}^\top(0)
]^\top$ is $n+m(T_0-1)$. Hence, the rank of $\mathcal{X}(T_0-1)$ is as most $n+m(T_0-1)$. Then the right side of~\eqref{eq:traj_g_partial} has the rank as most $n+m(T_0-1)+m(T-T_0+1)=n+Tm$. By Lemma~\ref{lem:null_partial}, $\text{rank}(\mathcal{H})=n+Tm$ yields $\text{rank}(\bm{G}_{\bm{\theta}})=n+Tm$. Hence, there exists at least one solution such that~\eqref{eq:traj_g0} holds.
Next, we show the uniqueness of the generated trajectory. Suppose there exists $\bm{g}_1$ and $\bm{g}_2$ are both solution of~\eqref{eq:traj_g0} and $\mathcal{H}\bm{g}_1\neq \mathcal{H}\bm{g}_2$. Since $\bm{g}_1$ and $\bm{g}_2$ are both solution of~\eqref{eq:traj_g0}, then $\bm{G}_{\bm{\theta}}\bm{g}_1=\bm{G}_{\bm{\theta}}\bm{g}_1$ and thus $\left(\bm{g}_1-\bm{g}_2\right)\in\mathcal{N}(\bm{G}_{\bm{\theta}})$.
On the other hand, $\mathcal{H}\bm{g}_1\neq \mathcal{H}\bm{g}_2$ yields $\mathcal{H}\left(\bm{g}_1-\bm{g}_2\right)\neq 0$ and thus $\left(\bm{g}_1-\bm{g}_2\right)\notin\mathcal{N}(\mathcal{H})$. This contradicts that $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$ proved in
Lemma~\ref{lem:null_partial}. Hence, $\mathcal{H}\bm{g}_1= \mathcal{H}\bm{g}_2$, namely, the generated trajectories are identical.
\end{proof}
\subsection{Trajectory generation algorithm for output-feedback control}\label{app:algorithm}
\begin{algorithm}[H]
\caption{Trajectory generation for output-feedback control}
\label{alg: TrajGenFull_partial}
\begin{algorithmic}[1]
\renewcommand{\algorithmicrequire}{\textbf{Require: }}
\renewcommand{\algorithmicensure}{\textbf{Data collection:}}
\ENSURE Collect historic measurement of the system and stack each $T$-length input-output trajectory as Hankel matrix $\mathcal{H}$ shown in~\eqref{eq:Hankel_u_x} until $\text{rank}(\mathcal{H})=n+Tm$ \\
\renewcommand{\algorithmicensure}{\textbf{Data generation:}}
\ENSURE
\textit{Input} :Hankel matrix $\mathcal{H}$, weights $\bm{\theta}$ and the distribution $\mathcal{D}$ for the control policy, the batchsize $Q$ for the generated trajectories, the set $\mathcal{S}_\mathcal{X}$ of historic initial extended state $\mathcal{X}(T_0-1) $ \\
\SetKwFunction{FMain}{TrajectoryGen}
\SetKwProg{Fn}{Function}{:}{}
\Fn{\FMain{$\mathcal{H},\bm{\theta},\mathcal{D},Q ,\mathcal{S}_\mathcal{X} $}}{
Plug in $\bm{\theta}$ to compute $\bm{G}_{\bm{\theta}}$ in~\eqref{eq:traj_g_partial}.\\
Conduct eigenvalue decomposition of $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$ to obtain $\bm{P}_{\bm{\theta}}:=\begin{bmatrix}
\bm{p}_1 & \bm{p}_2 &\cdots& \bm{p}_s
\end{bmatrix}$ and $\bm{\Lambda}=\text{diag}(\lambda_1,\lambda_2,\cdots,\lambda_s)$ with $\lambda_i$ being nonzero eigenvalues and $\bm{p}_i$ being orthonormal eigenvectors.\\
\For{$i = 1$ to $Q$}
{Sample $\mathcal{X}(T_0-1)$ from $\mathcal{S}_\mathcal{X} $. Sample $\left\{\bm{w}_i(T_0-1),\cdots,\bm{w}_i(T-1)\right\}$ from distribution $\mathcal{D}$.\\
Compute the coefficient $\bm{g}_i^*=\bm{G}_{\bm{\theta}}^\top\bm{P}_{\bm{\theta}}\bm{\Lambda}^{-1}\bm{P}_{\bm{\theta}}^\top\left[
\bm{w}_i(T_0-1)^\top
\cdots
\bm{w}_i(T-1)^\top
\mathcal{X}(T_0-1)^\top
\right]^\top$.
\\
Generate the $i$-th trajectory $\bm{\tau}_i:=\left[
\Tilde{\bm{u}}_i(T_0-1)^\top
\cdots
\Tilde{\bm{u}}_i(T-1)^\top
\Tilde{\bm{y}}_i(T_0-1)^\top
\cdots
\Tilde{\bm{y}}_i(T-1)^\top
\right]^\top=\begin{bmatrix}
\mathcal{H}_u^{T_0 -1: T-1}\\
\mathcal{H}_y^{T_0 -1: T-1}
\end{bmatrix}\bm{g}_i^*$.
}
\textbf{return} $ \left[\bm{\tau}_1,\cdots,\bm{\tau}_Q \right]$
}
\end{algorithmic}
\end{algorithm}
\subsection{Control of a batch reactor system }\label{app:exp_reactor}
We use the discretized version of a batch reactor system in~\citep{de2019formulas} as an illustrative example. The state transition matrix is given in~\eqref{eq:example_AB}, where $\bm{x}(t)\in\real^4, \bm{u}(t)\in\real^2$. We aim to train a linear feedback controller to minimize the cost $ J(\bm{\theta}) = \sum_{k=1}^{K}\left\| \bm{y}(k)\right\|_1 +0.1 \left\|\bm{u}_{\bm{\theta}}(k)\right\|_1$ for the trajectory in the time horizon $K=30$. The number of episode in training is $E=400$.
\begin{equation}\label{eq:example_AB}
[A \mid B]=\left[\begin{array}{cccc|cc}
1.178 & 0.001 & 0.511 & -0.403 & 0.004 & -0.087 \\
-0.051 & 0.661 & -0.011 & 0.061 & 0.467 & 0.001 \\
0.076 & 0.335 & 0.560 & 0.382 & 0.213 & -0.235 \\
0 & 0.335 & 0.089 & 0.849 & 0.213 & -0.016
\end{array}\right]
\end{equation}
\textbf{Case I: the state is directly observable.} We setup $T=K=30$ and collect historic trajectory of length $L = (m + 1)T -1 + n=93$. With a sampling period of 0.1s~\citep{de2019formulas}, the data collection takes 9.3s. Then we stack the data as a Hankel matrix~\eqref{eq:Hankel_u_x} and use Algorithm~\ref{alg: TrajGenFull} to generate trajectories with the batchsize 1200 in each training episode.
Figure~\ref{fig:Loss_AB_full_main}(a) and Figure~\ref{fig:Loss_AB_full_main}(b) shows the average batch loss along the training episodes and the testing loss, respectively.
PG-Sample-Q achieves both lower training loss and testing loss with larger batchsize Q. However, this improvement comes at the expense of an increased number of samples from the system, as shown in Figure~\ref{fig:Loss_AB_full_main}(c). By contrast,
PG-TrajectoryGen attains the same performance as PG-Sample-1200, since Theorem~\ref{thm: unque_trajectory0} guarantees that we generate trajectories as if they were truly sampled on the system. Moreover, the number of samples in PG-TrajectoryGen purely comes
from the fixed historic trajectory of the length $L=93$, which is even much smaller than PG-Sample-10 where the length of samples is 120000 (equals to $10\times30\times400$).
\textbf{Case II: only the first and the second element of the state is directly observed.} In this case, $\bm{y}(k)=(\bm{x}_1(k), \bm{x}_2(k))\in\real^2$. Then $T_0=2$ such that the observability matrix $\mathcal{O}_{[0, T_0]}(\bm{A}, \bm{C})$ is full column rank. According to the trajectory generation algorithm developed in Subsection~\ref{subsec: TrajGenPartial}, we setup $T=K+T_0-1=31$ and collect historic measurements of length $L = (m + 1)T -1 + n=96$. With a sampling period of 0.1s, the data collection takes 9.6s. Hence, the data collection does not scale significantly even when only half of the state is directly observed. Figure~\ref{fig:Loss_AB_full_main}(a)-(c) compares the training loss, testing loss and the number of samples, respectively. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples in the system.
\begin{figure}[H]
\centering
\subfigure[Training Loss]{\includegraphics[width=1.8in]{figure/Loss_ABpartial.png}}
\subfigure[Testing Loss]{\includegraphics[width=1.8in]{figure/Loss_ABpartial_batchVSLoss.png}}
\subfigure[Number of samples]{\includegraphics[width=1.8in]{figure/Loss_ABpartial_BatchVSsample.png}}
\caption{Performance of learning output-feedback controllers in the batch reactor system. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples on the system.}\label{fig:Loss_AB_partial}
\end{figure}
\subsection{Voltage control in power distribution networks}\label{app:exp_voltage}
To validate the performance of the proposed method on a larger system, we conduct experiments on the voltage control problem in IEEE 33bus test feeder~\citep{baran1989network}. We adopt the Lindisflow model where the dynamics of voltage is described by a linear transition model~\citep{ cui2022decentralized, zhu2015fast}. The state $\bm{x}(t)\in\real^{32}$ is voltage in all the buses apart from the reference bus (the voltage of the reference bus is fixed). The action is the reactive power in each bus. We assume that there is no real-time communication between buses during real-time implementation, so the action at each bus can only change with the local measurement of voltage. The goal is to train a linear decentralized feedback controller to minimize total voltage deviation as well as the control effort in the time horizon $K=20$, written as $ J(\bm{\theta}) = \sum_{k=1}^{K}\left\| \bm{y}(k)\right\|_1 +0.3 \left\|\bm{u}_{\bm{\theta}}(k)\right\|_1$. The number of training episode is $E=500$.
\textbf{Case I: the state is directly observed.} The state is directly observed so the action $\bm{u}(t)\in\real^{32}$. We setup $T=K=20$ and collect historic trajectory of the length $L = (m + 1)T -1 + n=691$. With a sampling period of 1s~\citep{chen2021enforcing}, the data collection takes 691s.
In each episode of training, we use Algorithm~\ref{alg: TrajGenFull} to generate trajectories with the batchsize 1000. Figure~\ref{fig:Loss_voltage_full}(a)-(c) compares the training loss, testing loss and the number of samples, respectively. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples on the system.
\textbf{Case II: only $20$ elements in the state is observed. } We assume only 20 buses are measured and controlled, so $\bm{y}(t),\bm{u}(t)\in\real^{20}$. The observability matrix $\mathcal{O}_{[0, T_0]}(\bm{A}, \bm{C})$ becomes full column rank when $T_0=3$. The time horizon of trajectory is $K=20$. According to the trajectory generation algorithm developed in Subsection~\ref{subsec: TrajGenPartial}, we setup $T=K+T_0-1=22$ and collect historic trajectory of length $L = (m + 1)T -1 + n=493$. With a sampling period of 1s~\citep{chen2021enforcing}, the data collection takes 493s. Figure~\ref{fig:Loss_voltage_partial_main}(a)-(c) compares the training loss, testing loss and the number of samples, respectively. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples on the system.
\begin{figure}[H]
\centering
\subfigure[Training Loss]{\includegraphics[width=1.8in]{figure/Loss_voltage.png}}
\subfigure[Testing Loss]{\includegraphics[width=1.8in]{figure/Loss_voltageFull_batchVSLoss.png}}
\subfigure[Number of samples]{\includegraphics[width=1.8in]{figure/Loss_voltageFull_BatchVSsample.png}}
\caption{Performance of learning state-feedback controllers in power distribution network. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples on the system.}\label{fig:Loss_voltage_full}
\end{figure}
\section{Introduction}\label{sec: intro}
\section{ Preliminaries and problem formulation}
\label{sec: background}
\input{Preliminaries.tex}
\section{Trajectory Generation}
\label{sec:traj}
\input{Trajectory_Generation}
\section{Partial Observation}
\label{sec: model}
\input{model.tex}
\section{Sample efficient algorithm}
\label{sec: sample}
\input{Sample_efficient.tex}
\section{Introduction}
Reinforcement learning (RL) is becoming increasingly popular for the controller design of dynamical systems, especially when the exact system model or parameters are not available~\citep{zheng2021sample,hu2022towards}. Much of the success in RL has relied on sampling-based algorithms such as the policy gradient algorithm~\citep{Sutton2018RL, fazel2018global}, which typically requires repeated online interactions with the system. Moreover, the control actions need to incorporate sufficient exploration for the learning algorithm to search for better policies~\citep{jin2021pessimism}. However, sampling large batch of trajectories is expensive in many real-world problems (e.g., in energy systems, robotics or healthcare), and the exploration requirement for safety-critical systems may be dangerous~\citep{levine2020offline, fujimoto2021minimalist}.
When the online interactions with the system are limited, two categories of RL methods are designed: off-policy RL and offline RL.
Off-policy RL methods (e.g., Q-learning and its variants) typically learn a quality function (i.e, Q function) leveraging past experience, but online interactions with explorations are still required after the update of the control policies~\citep{ghasemipour2021emaq}.
Offline RL seeks to learn from a
fixed dataset without interactions with environments~\citep{gulcehre2020rl, jin2021pessimism}. The fundamental challenge is that once the control policies have been updated, the trajectories of the system under the new policies would not have the same distribution as the historical data~\citep{fujimoto2021minimalist, ghasemipour2021emaq}. As a result, existing algorithms typically constrain the control policy to be close with the policy utilized in the fixed dataset~\citep{ ostrovski2021difficulty, fujimoto2021minimalist}.
Since most algorithms need to do some exploration, it is believed that past data is not helpful if high-reward regions are not covered in the collected trajectories~\citep{levine2020offline, jin2021pessimism}.
A fundamental reason behind the above challenges is that the training process is restricted to fixed trajectories in the historical data, hence RL algorithms need to be restricted to historical control policies. We look at the problem from the other direction: \textit{Using only historical data, can we generate trajectories that follow the same distribution induced by a new control policy?}
This paper proposes a trajectory generation algorithm for linear systems, which adaptively generates new trajectories as if the system were being operated and explored under the updated control policies.
The key insights come from the fundamental lemma for linear systems, which shows that any set of persistently exciting trajectories can be used to represent the input-output behavior of the system~\citep{willems2005note, de2019formulas, markovsky2022identifiability}. Inspired by this, we generate trajectories from linear combinations of historical trajectories, which can come from routine operations of the system. The set of linear combinations is derived from the updated control policy with perturbations on actions, such that the generated trajectory is the same as the trajectory sampled on the real system. This adaptive approach overcomes the challenges in distributional shift and lack of exploration. This is complementary to recent advances in learning linear feedback controllers for linear systems (See, for example,~\citep{fazel2018global,zheng2021sample,tang2021analysis,hu2022towards} and references within), where trajectories are sampled through online interactions.
Experiments
show that the proposed method significantly reduces the number of sampled data needed for RL algorithms.
We summarize the contributions as follows:
\begin{enumerate}[noitemsep,nolistsep,leftmargin=*, label=\arabic*)]
\item We propose a simple end-to-end approach to generate input-output trajectories for linear systems, which significantly reduces the burden of sample collection in RL methods. In Theorem~\ref{thm: unque_trajectory0},
we prove that the generated trajectories is adaptive to the distribution shift of any linear state-feedback controller with perturbations on actions for explorations. When the states are not directly observed, Theorem~\ref{thm: unque_trajectory0_partial} shows that this framework also applies to output-feedback control by defining an extended state from the observations.
\item The proposed trajectory generation algorithm is compatible with any RL methods that learns from trajectories. The number of samples needed to learn is independent to the batch size (the number of trajectories in each episode) and the number of training episodes.
\end{enumerate}
\section{ Preliminaries and problem formulation}
\label{sec: background}
\input{Preliminaries.tex}
\section{Trajectory Generation for State-Feedback Control}
\label{sec:TrajGen_FullState}
\input{TrajGen_FullState}
\section{Trajectory Generation for Output-Feedback Control}
\label{sec: TrajGen_PartialState}
\input{model.tex}
\input{Sample_efficient.tex}
\vspace{-0.5cm}
\section{Experiment}
\label{sec: experiment}
\input{experiment.tex}
\vspace{-1.2cm}
\section{Conclusions}
This paper proposes a trajectory generation algorithm for learning linear feedback controllers in linear systems.
We prove that the algorithm generates trajectories with the exact distribution as if they are sampled by interacting with the real system using the updated control policy. In particular, the algorithm extends to systems where the states are not directly observed. This is done by equivalently defining system transition dynamics using input-output trajectories. Experiments show that the proposed method significantly reduces the number of sampled data needed for RL algorithms.
\subsection{Extended states for constructing Markov decision process}
Let $
\mathcal{O}_{[0, \ell]}(\bm{A}, \bm{C}):=\operatorname{col}\left(\bm{C}, \bm{C} \bm{A}, \ldots, \bm{C} \bm{A}^{\ell-1}\right)
$ be the extended observability matrix.
The lag of the system~\eqref{eq:sys_full} is defined by the smallest integer $\ell\in \mathbb{Z}_{\geq 0}$ such that the observability matrix $\mathcal{O}_{[0, \ell]}(\bm{A}, \bm{C})$ has rank $n$, i.e., the state can be reconstructed from $\ell$ measurements~\citep{huang2021robust}.
Let $T_0\geq\ell$ be the length of a trajectory.
Define the extended states as
\vspace{-0.1cm}
\begin{equation}
\mathcal{X}(k-1) :=\left[\begin{array}{c}
\bm{y}(k-T_0);
\cdots ;
\bm{y}(k-1);
\bm{u}(k-T_0);
\cdots ;
\bm{u}(k-2)
\end{array}\right].
\end{equation}
Then extending the system transition from time step 0 to $T_0$ gives
\vspace{-0.1cm}
\begin{equation}\label{eq:sys_extended}
\mathcal{X}(k)=\Tilde{\bm{A}}\mathcal{X}(k-1)+\Tilde{\bm{B}}\bm{u}(k-1)
\text{ for } k\geq T_0, k\in\mathbb{Z},
\end{equation}
which is a Markov decision process in terms of the extended states. Detailed proof and the definition of system transition matrix $(\Tilde{\bm{A}},\Tilde{\bm{B}})$ is given in Appendix~\ref{app: transition_partial}.
For the output-feedback control law in~\eqref{eq:control_policy},
we have $ p\left(\bm{u}(k)|\mathcal{X}(k)\right)=p\left(\bm{u}(k)|\bm{y}(k)\right)
$ and it is straightforward to show that policy gradient algorithm using~\eqref{eq: PG_grad} still works. The proof is given in Appendix~\ref{app:Policy Gradient}.
\subsection{Span of historic trajectories}
Expanding the system transition dynamics gives the input-state response over $[0, T-1]$ as
$$
\left[\begin{array}{l}
\bm{u}_{[0, T-1]} \\
\bm{x}_{[0, T-1]}
\end{array}\right]=\left[\begin{array}{cc}
\bm{I}_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{array}\right]\left[\begin{array}{c}
\bm{u}_{[0, T-1]} \\
\bm{x}(0)
\end{array}\right]
$$
where $\bm{x}(0)$ is the system initial state, and
$$
\begin{aligned}
\mathcal{T}_{[0, T-1]} :=\left[\begin{array}{ccccc}
\bm{B} & \mathbbold{0}_{n\times m} & \mathbbold{0}_{n\times m} & \cdots & \mathbbold{0}_{n\times m} \\
\bm{A} \bm{B} & \bm{B} & \mathbbold{0}_{n\times m} & \cdots & \mathbbold{0}_{n\times m} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
\bm{A}^{T-2} \bm{B} & \bm{A}^{T-3} \bm{B} & \bm{A}^{T-4} \bm{B} & \cdots & \mathbbold{0}_{n\times m}
\end{array}\right]
\mathcal{O}_{[0, T-1]} :=\left[\begin{array}{c}
\bm{I}_{n} \\
\bm{A} \\
\vdots \\
\bm{A}^{T-1}
\end{array}\right]
\end{aligned}
$$
are the Toeplitz and observability matrices of order $T$.
Let now $\bm{u}_{d,[0, L-1]}$ and $\bm{x}_{d,[0, L-1]}$ be the $L$-length input-output data collected during an experiment, and let
\begin{equation}\label{eq:Hankel_u_x}
\begin{split}
&\left[\begin{array}{cccc}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{array}\right]\quad:=\left[\begin{array}{cccc}
\bm{u}_d(0) & \bm{u}_d(1) & \cdots & \bm{u}_d(L-T) \\
\bm{u}_d(1) & \bm{u}_d(2) & \cdots & \bm{u}_d(L-T+1) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{u}_d(T-1) & \bm{u}_d(T) & \cdots & \bm{u}_d(L-1) \\
\hline \bm{x}_d(0) & \bm{x}_d(1) & \cdots & \bm{x}_d(L-T) \\
\bm{x}_d(1) & \bm{x}_d(2) & \cdots & \bm{x}_d(L-T+1) \\
\vdots & \vdots & \ddots & \vdots \\
\bm{x}_d(T-1) & \bm{x}_d(T) & \cdots & \bm{x}_d(L-1)
\end{array}\right]
\end{split}
\end{equation}
be the corresponding Hankel matrix $\mathcal{H}$.
Let
$$
\bm{X}_{0, L-T+1}:=\left[\begin{array}{llll}
\bm{x}_d(0) & \bm{x}_d(1) & \ldots & \bm{x}_d(L-T)
\end{array}\right].
$$
Then we have
\begin{equation}\label{eq:Hankel_u_\bm{x}(k)ransition}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}
=\begin{bmatrix}
I_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{bmatrix}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix}
\end{equation}
Follow this expression, the fundamental Lemma shows that any linear combination of the columns of the Hankel matrix is a T -long input/output trajectory of~\eqref{eq:sys_full}.
\begin{lemma}[Fundamental Lemma]\label{lem:fundemental}
If $\text{rank}\left[\begin{array}{cccc}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{array}\right]=n+Tm$,
then any $T$-long input/output trajectory of system~\eqref{eq:sys_full} can be expressed as
$$
\left[\begin{array}{l}
\bm{u}_{[0, T-1]} \\
\bm{x}_{[0, T-1]}
\end{array}\right]=\left[\frac{\bm{U}_{0, T, L-T+1} }{\bm{X}_{0, T, L-T+1} }\right] g
$$
where $g \in \mathbb{R}^{L-T+1}$.
Moreover, any linear combination of the columns of the Hankel matrix, that is
$$
\left[\begin{array}{c}
\bm{U}_{0, T, L-T+1} \\
\hline \bm{X}_{0, T, L-T+1}
\end{array}\right] g
$$
is a $T$-long input/output trajectory of~\eqref{eq:sys_full}.
\end{lemma}
To make the rank condition in Lemma~\ref{lem:fundemental} hold, the minimum requirement on the length of the collected data is $L-T+1=n+Tm$, namely, $L=(m+1)T-1+n$.
When the rank condition holds, linear combination of the columns of the Hankel matrix is also a $T$-length trajectory of the system. We generate a trajectory of length $T$ using
\begin{equation}\label{eq:Hankel_g0}
\left[\begin{array}{c}
\Tilde{\bm{u}}(0) \\
\vdots\\
\Tilde{\bm{u}}(T-1)\\
\Tilde{\bm{x}}(0)\\
\vdots\\
\Tilde{\bm{x}}(T-1)
\end{array}\right]=
\underbrace{ \left[\begin{array}{cccc}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{array}\right]}_{\mathcal{H}}g
\end{equation}
For convenience, we adopt the notation $\mathcal{H}_u=\bm{U}_{0, T, L-T+1} $, $\mathcal{H}_x=\bm{X}_{0, T, L-T+1} $ in the following sections. To represent the rows of blocks starting from the time $k=0,\cdots,T-1$, we denote
\begin{equation}
\mathcal{H}_x^k :=\left[\begin{array}{cccc}
\bm{x}_d(k) & \bm{x}_d(k+1) & \cdots & \bm{x}_d(L-T+k) \\
\end{array}\right]
\end{equation}
\begin{equation}
\mathcal{H}_u^k :=\left[\begin{array}{cccc}
\bm{u}_d(k) & \bm{u}_d(k+1) & \cdots & \bm{u}_d(L-T+k) \\
\end{array}\right].
\end{equation}
\subsection{Trajectory generation}
For generic policy gradient algorithm, a trajectory is collected from the system that start from a initial state $\bm{x}(0)$, subject to the control law $\bm{u}(k)=\bm{\theta} \bm{x}(k)+\bm{w}(k)$ for $k=0,\cdots,T-1$. The probability density function of a trajectory is given by
\begin{equation}\label{eq:pdf}
\begin{split}
p_{\pi_\theta}(\tau)= p\left(\bm{x}(0)\right) \prod_{k=0}^{T-1} &p\left(\bm{w}(k)\right) p\left(\bm{x}(k+1) \mid \bm{x}(k), u(k)\right),
\end{split}
\end{equation}
which is uniquely determined by $\bm{x}(0)$ and the sequence of perturbations $\bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T-1)$.
In the following, we show the algorithm to generate the trajectory subject to $\big\{\bm{x}(0),\bm{w}(0),\cdots, \allowbreak\bm{w}(T-1)\big\}$ from the Hankel matrix instead of truly implemented on the system.
The key is to use $\left\{\bm{x}(0),\bm{w}(0),\cdots, \bm{w}(T-1)\right\}$ as extra constraint to find the $g$ in~\eqref{eq:Hankel_g0} that generate the same trajectory as if it is sampled from the system.
The trajectory subject to the noise vector $\bm{w}(0), \bm{w}(1),\cdots, \bm{w}(T)$ satisfy
\begin{equation}
\left[\begin{array}{c}
\Tilde{\bm{u}}(0) \\
\vdots\\
\Tilde{\bm{u}}(T)\\
\end{array}\right]=
\underbrace{\begin{bmatrix}
\theta& & & \\
& \theta& & \\
& & \ddots& \\
& & & \theta \\
\end{bmatrix}}_{I_{T}\bigotimes\theta}
\left[\begin{array}{c}
\Tilde{\bm{x}}(0)\\
\vdots\\
\Tilde{\bm{x}}(T)
\end{array}\right]
+\left[\begin{array}{c}
\bm{w}(0) \\
\vdots\\
\bm{w}(T)\\
\end{array}\right]
\end{equation}
This indicates
\begin{equation}
\begin{split}
&\left[\begin{array}{c}
\mathcal{H}_u
\end{array}\right]g\quad= \begin{bmatrix}
\theta& & & \\
& \theta& & \\
& & \ddots& \\
& & & \theta \\
\end{bmatrix}
\left[\begin{array}{cccc}
\mathcal{H}_x
\end{array}\right]g
+\left[\begin{array}{c}
\bm{w}(0) \\
\vdots\\
\bm{w}(T)\\
\end{array}\right]
\end{split}
\end{equation}
Note that
\begin{equation}
\left[\begin{array}{cccc}
\mathcal{H}_x^0
\end{array}\right]:=\left[\begin{array}{cccc}
\bm{x}_d(0) & \bm{x}_d(1) & \cdots & \bm{x}_d(L-T) \\
\end{array}\right],
\end{equation}
the generated initial state is given by
\begin{equation}
\Tilde{\bm{x}}(0)=\left[\begin{array}{cccc}
\mathcal{H}_x^0
\end{array}\right]g.
\end{equation}
The generated trajectory should satisfy
\begin{equation}\label{eq:traj_g0}
\underbrace{\begin{bmatrix}
\mathcal{H}_u-\left(I_{T}\otimes\theta\right) \mathcal{H}_x\\
\mathcal{H}_x^0
\end{bmatrix}}_{G_\theta}
g=
\begin{bmatrix}
\bm{w}(0) \\
\vdots\\
\bm{w}(T-1)\\
\bm{x}(0)
\end{bmatrix}.
\end{equation}
Note that the matrix $G_\theta\in\real^{(Tm+n) \times (L-T+1)}$ is not a square matrix and its rank is determined by the length of historic trajectory $L$. When there is sufficient length of trajectory such that $\text{rank}(\mathcal{H})=n+Tm$, we have $L-T+1>Tm+n$ and thus there might be multiple $g $ such that~\eqref{eq:traj_g0} holds. We show in the next Lemma that the Null space of $G_\theta$ is exactly the same as the Hankel matrix $\mathcal{H}$. Hence, any $g $ such that~\eqref{eq:traj_g0} holds will generate the unique trajectory subject to $\left\{\bm{x}(0),\bm{w}(0),\cdots, \bm{w}(T-1)\right\}$.
\begin{lemma}
The null space $\mathcal{N}(G_\theta)$ is the same as $\mathcal{N}(\mathcal{H})$. Moreover, if $\text{rank}(\mathcal{H})=n+Tm$, then the matrix $G_\theta\in\real^{(Tm+n) \times (L-T+1)}$ is full row rank. Namely, $\text{rank}(G_\theta)=n+Tm$.
\end{lemma}
\begin{proof}
For all $q\in \mathcal{N}(\mathcal{H})$, we have $[\mathcal{H}_x] q =\mathbbold{0}_{Tn}$ and $[\bm{U}_{0, T, L-T+1} ] q =\mathbbold{0}_{Tm}$. Plugging in the expression of $G_{\theta}$ yields $G_{\theta}q = \mathbbold{0}_{Tm+n} $. Namely, $q\in\mathcal{N}(G_{\theta})$.
For all $v\in \mathcal{N}(G_\theta)$, we have
\begin{equation}
\left[\begin{array}{c}
\mathcal{H}_u-\left(I_{T}\otimes\theta\right) \mathcal{H}_x\\
\mathcal{H}_x^0
\end{array}\right]v=\mathbbold{0}_{Tm+n}
\end{equation}
This gives
\begin{equation}\label{eq:fullC_null}
\begin{split}
&\mathcal{H}_u^k v=\hat{\theta}\mathcal{H}_x^k v \text{ for } k=0,\cdots,T-1\\
&\mathcal{H}_x^0v =\mathbbold{0}_{n}
\end{split}
\end{equation}
From $\bm{x}(k+1)=A \bm{x}(k)+B u(k)$, we have
\begin{equation}
\mathcal{H}_x^{k+1}=A \mathcal{H}_x^{k}+B \mathcal{H}_u^{k}
\end{equation}
Pluging in~\eqref{eq:fullC_null} yields
$\mathcal{H}_x^k v =\mathbbold{0}_{n}$ and $\mathcal{H}_u^k v =\mathbbold{0}_{m}$ for $ k=0,\cdots,T-1$. Hence, $\mathcal{H}v = \mathbbold{0}_{Tm+Tn} $. Namely, $v\in\mathcal{N}(\mathcal{H})$.
Note that $H\in\real^{(Tm+Tn) \times (L-T+1)}$. If $\text{rank}(\mathcal{H})=n+Tm$, then the rank of Null space is $\text{rank}(\mathcal{N}(\mathcal{H}))=(L-T+1)-(n+Tm)$.
Since $\mathcal{N}(G_\theta)$ is the same as $\mathcal{N}(\mathcal{H})$, then $\text{rank}(\mathcal{N}(G_\theta))=(L-T+1)-(n+Tm)$. It follows directly that $\text{rank}(\mathcal{H})=(L-T+1)-\text{rank}(\mathcal{N}(G_\theta))=n+Tm$.
\end{proof}
If $\text{rank}(G_\theta)=n+Tm$, then there exist at least one solution such that~\eqref{eq:traj_g0} holds. We pick the minimum-norm solution of~\eqref{eq:traj_g0} given by
\begin{equation}
g=G_\theta^\top\left(G_\theta G_\theta^\top\right)^{-1}\left[\begin{array}{c}
\bm{w}(0) \\
\vdots\\
\bm{w}(T-1)\\
\bm{x}(0)
\end{array}\right].
\end{equation}
The proposed trajectory generation algorithm is illustrated as follows
\begin{algorithm}
\caption{Policy Gradient with trajectory generation when the state is observable }
\begin{algorithmic}[1]
\renewcommand{\algorithmicrequire}{\textbf{Require: }}
\renewcommand{\algorithmicensure}{\textbf{Data collection:}}
\REQUIRE The length $T$ of trajectory to be generated, the dimension of state $n$, the dimension of action $m$, the learning rate $\alpha$
\ENSURE Collect historic measurement of the system and stack each $T$-length input-output trajectory as Hankel matrix $\mathcal{H}$ shown in~\eqref{eq:Hankel_u_x} until $\text{rank}(\mathcal{H})=n+Tm$ \\
\renewcommand{\algorithmicensure}{\textbf{Policy Gradient with Data generation:}}
\ENSURE
\textit{Initialisation} :Initial weights $\theta$ for control network
\FOR {$episode = 1$ to $I$}
\STATE Plug in $\theta$ to compute $G_\theta=\begin{bmatrix}
\mathcal{H}_u-\left(I_{T}\otimes\theta\right) \mathcal{H}_x\\
\mathcal{H}_x^0
\end{bmatrix}$
\FOR {$i = 1$ to $Q$}
\STATE Uniformly sample $x^i(0)$ from historic measurement of the system. Sample $\left\{w^i(0),\cdots,w^i(T-1)\right\}$ from the distribution $\mathcal{D}$.
\STATE Compute the coefficient $g_i=G_\theta^\top\left(G_\theta G_\theta^\top\right)^{-1}\left[
w^i(0)^\top
\cdots
w^i(T-1)^\top
x^i(0)^\top
\right]^\top$
\STATE Generate the $i$-th trajectory $\tau_i:=\left[
\Tilde{\bm{u}}^i(0)^\top
\cdots
\Tilde{\bm{u}}^i(T-1)^\top
\Tilde{\bm{x}}^i(0)^\top
\cdots
\Tilde{\bm{x}}^i(T-1)^\top
\right]^\top=\mathcal{H}g_i$
\ENDFOR
\STATE Compute the gradient $ \nabla J(\theta) = \frac{1}{Q}\sum_{i=1}^{Q} c(\tau_i)\sum_{t=1}^{T} \nabla_{\theta}\log\pi_{\theta} (\Tilde{\bm{u}}^i(t)|\Tilde{\bm{x}}^i(t)) $
\STATE Update weights in the neural network by gradient descent:
$\theta \leftarrow \theta-\alpha \nabla J(\theta) $
\ENDFOR
\end{algorithmic}
\end{algorithm}
\subsection{Fundemental Lemma}\label{app: fundemental}
For state feedback control, $\bm{y}(t)=\bm{x}(t)$ ($\bm{C}=\bm{I}_n$) and the system transition dynamics is reduced to $\bm{x}(k+1) =\bm{A} \bm{x}(k)+\bm{B} \bm{u}(k)$. Expanding the dynamics for $k=0, \cdots, T$ gives the input-state response over $[0, T-1]$ as
\begin{equation}\label{eq: stack_transition}
\begin{bmatrix}
\bm{u}_{[0, T-1]} \\
\bm{x}_{[0, T-1]}
\end{bmatrix}=\begin{bmatrix}
\bm{I}_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{bmatrix}
\begin{bmatrix}
\bm{u}_{[0, T-1]} \\
\bm{x}(0)
\end{bmatrix},
\end{equation}
where $\mathcal{T}_{[0, T-1]}$ and $\mathcal{O}_{[0, T-1]}$ are the Toeplitz and observability matrices of order $T$ represented as~\citep{de2019formulas}
$$
\begin{aligned}
\mathcal{T}_{[0, T-1]} :=\left[\begin{array}{ccccc}
\bm{B} & \mathbbold{0}_{n\times m} & \mathbbold{0}_{n\times m} & \cdots & \mathbbold{0}_{n\times m} \\
\bm{A} \bm{B} & \bm{B} & \mathbbold{0}_{n\times m} & \cdots & \mathbbold{0}_{n\times m} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
\bm{A}^{T-2} \bm{B} & \bm{A}^{T-3} \bm{B} & \bm{A}^{T-4} \bm{B} & \cdots & \mathbbold{0}_{n\times m}
\end{array}\right]
\quad\mathcal{O}_{[0, T-1]} :=\left[\begin{array}{c}
\bm{I}_{n} \\
\bm{A} \\
\vdots \\
\bm{A}^{T-1}
\end{array}\right].
\end{aligned}
$$
On this basis, the Hankel Matrix $\mathcal{H}$ can be represented as
\begin{equation}\label{eq:Hankel_u_x(k)ransition}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}
=\begin{bmatrix}
I_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{bmatrix}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix},
\end{equation}
where
$X_{0, L-T+1}:=\left[\begin{array}{llll}
\bm{x}_d(0) & \bm{x}_d(1) & \ldots & \bm{x}_d(L-T)
\end{array}\right].$
Now consider a trajectory $[
\hat{\bm{u}}_{[0, T-1]};
\hat{\bm{x}}_{[0, T-1]}
]$ starting from an initial state $\hat{\bm{x}}(0)$ and evolves with the sequence of actions $\hat{\bm{u}}_{[0, T-1]}$. If $\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix}$ is full row rank, namely $\text{rank}(\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix})=n+Tm$, then there exists $\hat{\bm{g}}\in\real^{L-T+1}$ such that $\begin{bmatrix}
\hat{\bm{u}}_{[0, T-1]} \\
\hat{\bm{x}}(0)
\end{bmatrix}=\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix}\hat{\bm{g}}$. By~\eqref{eq: stack_transition},
\begin{equation}
\begin{split}
\begin{bmatrix}
\hat{\bm{u}}_{[0, T-1]}\\
\hat{\bm{x}}_{[0, T-1]}
\end{bmatrix}
&=\begin{bmatrix}
\bm{I}_{T m} & \mathbbold{0}_{T m \times n} \\
\mathcal{T}_{[0,T-1]} & \mathcal{O}_{[0,T-1]}
\end{bmatrix}
\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
X_{0, L-T+1}
\end{bmatrix}\hat{\bm{g}}\\
&=\begin{bmatrix}
\bm{U}_{0, T, L-T+1} \\
\bm{X}_{0, T, L-T+1}
\end{bmatrix}\hat{\bm{g}},
\end{split}
\end{equation}
where the second equation follows from the relation in~\eqref{eq:Hankel_u_x(k)ransition}. This complete the proof of Lemma~\eqref{lem:fundemental}.
\subsection{Policy gradient algorithm}\label{app: PG_state_feedback}
\begin{algorithm}[H]
\caption{Policy Gradient with trajectory generation }
\label{alg: PG}
\begin{algorithmic}[1]
\renewcommand{\algorithmicrequire}{\textbf{Require: }}
\renewcommand{\algorithmicensure}{\textbf{Data collection:}}
\REQUIRE The length $T$ of trajectory, the learning rate $\alpha$, total number of episode $I$\\
\renewcommand{\algorithmicensure}{\textbf{Policy Gradient with Data generation:}}
\ENSURE
\textit{Initialisation} :Initial weights $\bm{\theta}$ for control network
\FOR {$episode = 1$ to $I$}
\STATE Generate a batch of $Q$ trajectories $ \left[\bm{\tau}_1,\cdots,\bm{\tau}_Q \right]=$\texttt{TrajectoryGen}$\left(\mathcal{H},\bm{\theta},\mathcal{D},Q\right) $
\STATE Compute the gradient $ \nabla J(\bm{\theta}) = \frac{1}{Q}\sum_{i=1}^{Q} c(\bm{\tau}_i)\sum_{t=1}^{T} \nabla_{\bm{\theta}}\log\pi_{\bm{\theta}} (\Tilde{\bm{u}}_i(t)|\Tilde{\bm{x}}_i(t)) $
\STATE Update weights in the neural network by gradient descent:
$\bm{\theta} \leftarrow \bm{\theta}-\alpha \nabla J(\bm{\theta}) $
\ENDFOR
\end{algorithmic}
\end{algorithm}
\subsection{Transition dynamics with extended states}\label{app: transition_partial}
Expanding the transition dynamics in~\eqref{eq:sys_full} from time $0$ to $T_0$ gives
\begin{equation}\label{eq:y_u_traj_transition}
\bm{y}_{[0, T_0-1]}=\mathcal{O}_{[0, T_0-1]}\bm{x}(0)+\mathcal{T}_{[0, T_0-1]}\bm{u}_{[0, T_0-2]}\end{equation}
where $\mathcal{T}_{[0, T-1]}$ and $\mathcal{O}_{[0, T-1]}$ are the Toeplitz and observability matrices of order $T_0$ represented as
$$
\begin{aligned}
\mathcal{T}_{[0, T_0-1]} &:=\left[\begin{array}{ccccc}
\bm{C}\bm{B}&\mathbbold{0}_{d\times m}&\mathbbold{0}_{d\times m}& \cdots &\mathbbold{0}_{d\times m}\\
\bm{C} \bm{A}\bm{B}& \bm{C}\bm{B}&\mathbbold{0}_{d\times m}& \cdots &\mathbbold{0}_{d\times m}\\
\vdots & \vdots & \vdots & \ddots & \vdots \\
\bm{C} \bm{A}^{T_0-2}\bm{B}& \bm{C}\bm{A}^{T_0-3}\bm{B}& \bm{C}\bm{A}^{T_0-4}\bm{B}& \cdots & \mathbbold{0}_{d\times m}
\end{array}\right] \quad
\mathcal{O}_{[0, T_0-1]} :=\left[\begin{array}{c}
\bm{C} \\
\bm{C}\bm{A} \\
\vdots \\
\bm{C}\bm{A}^{T_0-1}
\end{array}\right].
\end{aligned}
$$
Since the system~\eqref{eq:sys_full} is observable, $\mathcal{O}_{[0, T_0-1]}$ is full column rank. Thus,
\begin{equation}
\bm{x}(0)=\underbrace{\left(\mathcal{O}_{[0, T_0-1]}^\top\mathcal{O}_{[0, T_0-1]}\right)^{-1}
\mathcal{O}_{[0, T_0-1]}^{\top}}_{\mathcal{O}_{[0, T_0-1]}^\dagger} \left(\bm{y}_{[0, T_0-1]}-\mathcal{T}_{[0, T_0-1]}\bm{u}_{[0, T_0-2]}\right)
\end{equation}
Then pluging in the expression of $\bm{y}(T_0)$ yields
\begin{equation}\label{eq:y_T_0}
\begin{split}
\bm{y}(T_0)&=\bm{C}\bm{A}^{T_0}\bm{x}(0)+\bm{C}\bm{A}^{T_0-1}\bm{B}\bm{u}(0)+\cdots+\bm{C}\bm{B}\bm{u}(T_0-1)\\
&=\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \left(\bm{y}_{[0, T_0-1]}-\mathcal{T}_{[0, T_0-1]}\bm{u}_{[0, T_0-2]}\right)+\mathcal{T}_{[T_0, T_0]}\bm{u}_{[0, T_0-2]}\\
&= \bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \bm{y}_{[0, T_0-1]}+\left(\mathcal{T}_{[T_0, T_0]}-\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \mathcal{T}_{[0, T_0-1]} \right)\bm{u}_{[0, T_0-2]}
\end{split}
\end{equation}
where
$$
\begin{aligned}
\mathcal{T}_{[T_0, T_0]} &:=\left[\begin{array}{ccccc}
\bm{C}\bm{A}^{T_0-1} \bm{B} & \bm{C}\bm{A}^{T_0-2} \bm{B} & \bm{C}\bm{A}^{T_0-3} \bm{B} & \cdots & \bm{C}\bm{B}\\
\end{array}\right].
\end{aligned}
$$
Stacking the observations and the outputs together yields
\begin{equation}
\left[\begin{array}{c}
\bm{y}(1)\\
\vdots \\
\bm{y}(T_0)\\
\bm{u}(1)\\
\vdots \\
\bm{u}(T_0-1)\\
\end{array}\right]=\Tilde{\bm{A}} \left[\begin{array}{c}
\bm{y}(0)\\
\vdots \\
\bm{y}(T_0-1)\\
\bm{u}(0)\\
\vdots \\
\bm{u}(T_0-2)\\
\end{array}\right]
+\Tilde{\bm{B}}\bm{u}(T_0-1),
\end{equation}
where
\begin{equation}
\begin{split}
&\Tilde{\bm{A}}=
\begin{pmatrix}
\begin{matrix}
\bm{0}& \bm{I}_d & \bm{0}& \bm{0}&\cdots & \bm{0}\\
\bm{0}& \bm{0}& \bm{I}_d & \bm{0}& \cdots & \bm{0}\\
\vdots & \vdots& \vdots & \vdots & \ddots & \vdots \\
\bm{0}& \bm{0} & \bm{0}& \bm{0}& \cdots & \bm{I}_d
\end{matrix}
& \hspace*{-\arraycolsep}\vline\hspace*{-\arraycolsep} & \mbox{\normalfont\Large\bfseries 0} \\
\hline
\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger& \hspace*{-\arraycolsep}\vline\hspace*{-\arraycolsep} & \mathcal{T}_{[T_0, T_0]}-\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \mathcal{T}_{[0, T_0-1]} \\
\hline
\mbox{\normalfont\Large\bfseries 0} & \hspace*{-\arraycolsep}\vline\hspace*{-\arraycolsep} &
\begin{matrix}
\bm{0}& \bm{I}_m & \bm{0}& \bm{0}&\cdots & \bm{0}\\
\bm{0}& 0& \bm{I}_m & \bm{0}& \cdots & \bm{0}\\
\vdots & \vdots& \vdots & \vdots & \ddots & \vdots \\
\bm{0}& 0& \bm{0}& \bm{0}& \cdots & \bm{I}_m \\
\end{matrix} \\
\hline
\mbox{\normalfont\Large\bfseries 0} & \hspace*{-\arraycolsep}\vline\hspace*{-\arraycolsep} & \mbox{\normalfont\Large\bfseries 0}
\end{pmatrix},
\Tilde{\bm{B}}=
\begin{pmatrix}
\begin{matrix}
\bm{0}\\
\bm{0}\\
\vdots \\
\bm{0}
\end{matrix}\\
\hline
\bm{0}\\
\hline
\begin{matrix}
\bm{0}\\
\bm{0}\\
\vdots \\
\bm{0}
\end{matrix}\\
\hline
\bm{I}_m
\end{pmatrix}.
\end{split}
\end{equation}
\subsection{Policy Gradient for Extended States }~\label{app:Policy Gradient}
The basic policy gradient algorithm is~\citet{Sutton2018RL}
\begin{equation}
\begin{split}
\nabla_{\bm{\theta}} \mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}}[c(\bm{\tau})] &=\nabla_{\bm{\theta}} \int \pi_{\bm{\theta}}(\bm{\tau}) c(\bm{\tau}) d \tau \\
&=\int \nabla_{\bm{\theta}} \pi_{\bm{\theta}}(\bm{\tau}) c(\bm{\tau}) d \tau \\
&=\int \pi_{\bm{\theta}}(\bm{\tau}) \nabla_{\bm{\theta}} \log \pi_{\bm{\theta}}(\bm{\tau}) c(\bm{\tau}) d \tau \\
&=\mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}}[c(\bm{\tau}) \nabla_{\bm{\theta}} \log \pi_{\bm{\theta}}(\bm{\tau})].
\end{split}
\end{equation}
The probability of a trajectory with length $T$ is
\begin{equation}\label{eq:prob_traj}
\pi_\theta(\bm{\tau})= p\left(\mathcal{X}\left(T_0\right)\right) \prod_{t=T_0}^{T-1} p_{\pi_{\bm{\theta}}}\left(\bm{u}(t)|\mathcal{X}(t)\right) p\left(\mathcal{X}(t+1)|\mathcal{X}(t), \bm{u}(t)\right) .
\end{equation}
Expanding the terms in~\eqref{eq:prob_traj} and canceling the transition probability independent of $\bm{\theta}$, we have
\begin{equation}
\nabla_{\bm{\theta}}\log \pi_\theta(\bm{\tau}) =\sum_{t=0}^{T-1} \nabla_{\bm{\theta}}\log p_{\bm{\pi}_{\bm{\theta}}}\left(\bm{u}(k) \mid \bm{y}(k)\right),
\end{equation}
and therefore,
\begin{equation}
\nabla_{\bm{\theta}}\mathbb{E}_{\pi_\theta}[c(\bm{\tau})] =\mathbb{E}_{\bm{\tau} \sim p_{\bm{\pi}_{\bm{\theta}}}(\bm{\tau})}\left[c(\bm{\tau})\sum_{k=0}^{K-1} \nabla_{\bm{\theta}} \log p_{\bm{\pi}_{\bm{\theta}}}\left(\bm{u}(k) \mid \bm{y}(k)\right)\right]
\end{equation}
Hence, the policy gradient algorithm still holds for the output-feedback case.
\subsection{Proof of Theorem~\ref{thm: unque_trajectory0_partial}}\label{app:thm_partial}
To prove Theorem~\ref{thm: unque_trajectory0_partial}, we need to make use of the rank condition of $\bm{G}_{\bm{\theta}}$ and $\bm{R}$ in~\eqref{eq:traj_g_partial}. We first
show in Lemma~\ref{lem:null_partial} about the null space and rank condition induced from the condition $\text{rank}(\mathcal{H})=n+Tm$.
\begin{lemma}\label{lem:null_partial}
If the observability matrix $\mathcal{O}_{[0, T_0-1]}$ is
full column rank, then
the null space $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$. Moreover, if $\text{rank}(\mathcal{H})=n+Tm$, then $\text{rank}(\bm{G}_{\bm{\theta}})=n+Tm$.
\end{lemma}
\begin{proof}
We first prove that the null space $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$ from \textit{(i)} and \textit{(ii)} :
\textit{(i)} For all $\bm{q}\in \mathcal{N}(\mathcal{H})$, we have $[\mathcal{H}_y]\bm{q} =\mathbbold{0}_{Tn}$ and $[\mathcal{H}_u]\bm{q} =\mathbbold{0}_{Tm}$. Plugging in the expression of $\bm{G}_{\bm{\theta}}$ yields $\bm{G}_{\bm{\theta}}\bm{q} = \mathbbold{0}_{Tm+n} $. Namely, $\bm{q}\in\mathcal{N}(\bm{G}_{\bm{\theta}})$.
\textit{(ii)} For all $\bm{v}\in \mathcal{N}(\bm{G}_{\bm{\theta}})$, we have
\begin{equation}
\left[\begin{array}{c}
\mathcal{H}_u^{T_0 -1: T-1} -\left(\bm{I}_{T-T_0}\otimes \theta\right) \mathcal{H}_y^{T_0 -1: T-1} \\
\mathcal{H}_y^{0 : T_0-1}\\
\mathcal{H}_u^{0 : T_0-2}
\end{array}\right]\bm{v}=\mathbbold{0}_{Tm+T_0 d} \; ,
\end{equation}
which gives
\begin{equation}\label{eq:fullC_null2}
\begin{split}
&\mathcal{H}_u^k \bm{v}=\theta\mathcal{H}_y^k \bm{v} \text{ for } k=T_0,\cdots,T-1\\
&\mathcal{H}_y^{0 : T_0-1} \bm{v} =\mathbbold{0}_{T_0 d} \\
&\mathcal{H}_u^{0 : T_0-2} \bm{v} =\mathbbold{0}_{T_0 m} \;.
\end{split}
\end{equation}
From~\eqref{eq:y_T_0}, we have ,
\begin{equation}\label{eq:induction_y_u}
\begin{split}
\mathcal{H}_y^{k}
&=\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger\mathcal{H}_y^{k-T_0:k-1}+\left(\mathcal{T}_{[T_0, T_0]}-\bm{C}\bm{A}^{T_0}\mathcal{O}_{[0, T_0-1]}^\dagger \mathcal{T}_{[0, T_0-1]} \right)\mathcal{H}_u^{k-T_0:k-2}
\end{split}
\end{equation}
for $k=T_0,\cdots,T-1$.
Plugging~\eqref{eq:fullC_null2} in~\eqref{eq:induction_y_u} induces
$\mathcal{H}_y^k \bm{v} =\mathbbold{0}_{d}$ and $\mathcal{H}_u^k \bm{v} =\mathbbold{0}_{m}$ for $ k=0,\cdots,T-1$. Hence, $\mathcal{H}\bm{v} = \mathbbold{0}_{Tm+Td} $. Namely, $\bm{v}\in\mathcal{N}(\mathcal{H})$.
Next, we prove the rank condition. Note that $\mathcal{H}\in\real^{(Tm+Tn) \times (L-T+1)}$. If $\text{rank}(\mathcal{H})=n+Tm$, then the rank of Null space is $\text{rank}(\mathcal{N}(\mathcal{H}))=(L-T+1)-(n+Tm)$.
Since $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$, then $\text{rank}(\mathcal{N}(\bm{G}_{\bm{\theta}}))=(L-T+1)-(n+Tm)$. It follows directly that $\text{rank}(\bm{G}_{\bm{\theta}})=(L-T+1)-\text{rank}(\mathcal{N}(\bm{G}_{\bm{\theta}}))=n+Tm$.
\end{proof}
Then, we are ready to prove Theorem~\ref{thm: unque_trajectory0_partial} as follows.
\begin{proof}
We first prove the existence of the solution in~\eqref{eq:traj_g_partial}. From~\eqref{eq:y_u_traj_transition}, we have
$$
\mathcal{X}(T_0-1):=\left[\begin{array}{l}
\bm{u}_{[0, T_0-2]} \\
\bm{y}_{[0, T_0-1]}
\end{array}\right]=\left[\begin{array}{cc}
I_{(T_0-1) m} & \mathbbold{0}_{(T_0-1) m \times n} \\
\mathcal{T}_{[0,T_0-1]} & \mathcal{O}_{[0,T_0-1]}
\end{array}\right]
\begin{bmatrix}
\bm{u}_{[0, T_0-2]} \\
\bm{x}(0)
\end{bmatrix}
$$
The number of element in the vector $[\bm{u}_{[0, T_0-2]}^\top, \bm{x}^\top(0)
]^\top$ is $n+m(T_0-1)$. Hence, the rank of $\mathcal{X}(T_0-1)$ is as most $n+m(T_0-1)$. Then the right side of~\eqref{eq:traj_g_partial} has the rank as most $n+m(T_0-1)+m(T-T_0+1)=n+Tm$. By Lemma~\ref{lem:null_partial}, $\text{rank}(\mathcal{H})=n+Tm$ yields $\text{rank}(\bm{G}_{\bm{\theta}})=n+Tm$. Hence, there exists at least one solution such that~\eqref{eq:traj_g0} holds.
Next, we show the uniqueness of the generated trajectory. Suppose there exists $\bm{g}_1$ and $\bm{g}_2$ are both solution of~\eqref{eq:traj_g0} and $\mathcal{H}\bm{g}_1\neq \mathcal{H}\bm{g}_2$. Since $\bm{g}_1$ and $\bm{g}_2$ are both solution of~\eqref{eq:traj_g0}, then $\bm{G}_{\bm{\theta}}\bm{g}_1=\bm{G}_{\bm{\theta}}\bm{g}_1$ and thus $\left(\bm{g}_1-\bm{g}_2\right)\in\mathcal{N}(\bm{G}_{\bm{\theta}})$.
On the other hand, $\mathcal{H}\bm{g}_1\neq \mathcal{H}\bm{g}_2$ yields $\mathcal{H}\left(\bm{g}_1-\bm{g}_2\right)\neq 0$ and thus $\left(\bm{g}_1-\bm{g}_2\right)\notin\mathcal{N}(\mathcal{H})$. This contradicts that $\mathcal{N}(\bm{G}_{\bm{\theta}})$ is the same as $\mathcal{N}(\mathcal{H})$ proved in
Lemma~\ref{lem:null_partial}. Hence, $\mathcal{H}\bm{g}_1= \mathcal{H}\bm{g}_2$, namely, the generated trajectories are identical.
\end{proof}
\subsection{Trajectory generation algorithm for output-feedback control}\label{app:algorithm}
\begin{algorithm}[H]
\caption{Trajectory generation for output-feedback control}
\label{alg: TrajGenFull_partial}
\begin{algorithmic}[1]
\renewcommand{\algorithmicrequire}{\textbf{Require: }}
\renewcommand{\algorithmicensure}{\textbf{Data collection:}}
\ENSURE Collect historic measurement of the system and stack each $T$-length input-output trajectory as Hankel matrix $\mathcal{H}$ shown in~\eqref{eq:Hankel_u_x} until $\text{rank}(\mathcal{H})=n+Tm$ \\
\renewcommand{\algorithmicensure}{\textbf{Data generation:}}
\ENSURE
\textit{Input} :Hankel matrix $\mathcal{H}$, weights $\bm{\theta}$ and the distribution $\mathcal{D}$ for the control policy, the batchsize $Q$ for the generated trajectories, the set $\mathcal{S}_\mathcal{X}$ of historic initial extended state $\mathcal{X}(T_0-1) $ \\
\SetKwFunction{FMain}{TrajectoryGen}
\SetKwProg{Fn}{Function}{:}{}
\Fn{\FMain{$\mathcal{H},\bm{\theta},\mathcal{D},Q ,\mathcal{S}_\mathcal{X} $}}{
Plug in $\bm{\theta}$ to compute $\bm{G}_{\bm{\theta}}$ in~\eqref{eq:traj_g_partial}.\\
Conduct eigenvalue decomposition of $\left(\bm{G}_{\bm{\theta}} \bm{G}_{\bm{\theta}}^\top\right)$ to obtain $\bm{P}_{\bm{\theta}}:=\begin{bmatrix}
\bm{p}_1 & \bm{p}_2 &\cdots& \bm{p}_s
\end{bmatrix}$ and $\bm{\Lambda}=\text{diag}(\lambda_1,\lambda_2,\cdots,\lambda_s)$ with $\lambda_i$ being nonzero eigenvalues and $\bm{p}_i$ being orthonormal eigenvectors.\\
\For{$i = 1$ to $Q$}
{Sample $\mathcal{X}(T_0-1)$ from $\mathcal{S}_\mathcal{X} $. Sample $\left\{\bm{w}_i(T_0-1),\cdots,\bm{w}_i(T-1)\right\}$ from distribution $\mathcal{D}$.\\
Compute the coefficient $\bm{g}_i^*=\bm{G}_{\bm{\theta}}^\top\bm{P}_{\bm{\theta}}\bm{\Lambda}^{-1}\bm{P}_{\bm{\theta}}^\top\left[
\bm{w}_i(T_0-1)^\top
\cdots
\bm{w}_i(T-1)^\top
\mathcal{X}(T_0-1)^\top
\right]^\top$.
\\
Generate the $i$-th trajectory $\bm{\tau}_i:=\left[
\Tilde{\bm{u}}_i(T_0-1)^\top
\cdots
\Tilde{\bm{u}}_i(T-1)^\top
\Tilde{\bm{y}}_i(T_0-1)^\top
\cdots
\Tilde{\bm{y}}_i(T-1)^\top
\right]^\top=\begin{bmatrix}
\mathcal{H}_u^{T_0 -1: T-1}\\
\mathcal{H}_y^{T_0 -1: T-1}
\end{bmatrix}\bm{g}_i^*$.
}
\textbf{return} $ \left[\bm{\tau}_1,\cdots,\bm{\tau}_Q \right]$
}
\end{algorithmic}
\end{algorithm}
\subsection{Control of a batch reactor system }\label{app:exp_reactor}
We use the discretized version of a batch reactor system in~\citep{de2019formulas} as an illustrative example. The state transition matrix is given in~\eqref{eq:example_AB}, where $\bm{x}(t)\in\real^4, \bm{u}(t)\in\real^2$. We aim to train a linear feedback controller to minimize the cost $ J(\bm{\theta}) = \sum_{k=1}^{K}\left\| \bm{y}(k)\right\|_1 +0.1 \left\|\bm{u}_{\bm{\theta}}(k)\right\|_1$ for the trajectory in the time horizon $K=30$. The number of episode in training is $E=400$.
\begin{equation}\label{eq:example_AB}
[A \mid B]=\left[\begin{array}{cccc|cc}
1.178 & 0.001 & 0.511 & -0.403 & 0.004 & -0.087 \\
-0.051 & 0.661 & -0.011 & 0.061 & 0.467 & 0.001 \\
0.076 & 0.335 & 0.560 & 0.382 & 0.213 & -0.235 \\
0 & 0.335 & 0.089 & 0.849 & 0.213 & -0.016
\end{array}\right]
\end{equation}
\textbf{Case I: the state is directly observable.} We setup $T=K=30$ and collect historic trajectory of length $L = (m + 1)T -1 + n=93$. With a sampling period of 0.1s~\citep{de2019formulas}, the data collection takes 9.3s. Then we stack the data as a Hankel matrix~\eqref{eq:Hankel_u_x} and use Algorithm~\ref{alg: TrajGenFull} to generate trajectories with the batchsize 1200 in each training episode.
Figure~\ref{fig:Loss_AB_full_main}(a) and Figure~\ref{fig:Loss_AB_full_main}(b) shows the average batch loss along the training episodes and the testing loss, respectively.
PG-Sample-Q achieves both lower training loss and testing loss with larger batchsize Q. However, this improvement comes at the expense of an increased number of samples from the system, as shown in Figure~\ref{fig:Loss_AB_full_main}(c). By contrast,
PG-TrajectoryGen attains the same performance as PG-Sample-1200, since Theorem~\ref{thm: unque_trajectory0} guarantees that we generate trajectories as if they were truly sampled on the system. Moreover, the number of samples in PG-TrajectoryGen purely comes
from the fixed historic trajectory of the length $L=93$, which is even much smaller than PG-Sample-10 where the length of samples is 120000 (equals to $10\times30\times400$).
\textbf{Case II: only the first and the second element of the state is directly observed.} In this case, $\bm{y}(k)=(\bm{x}_1(k), \bm{x}_2(k))\in\real^2$. Then $T_0=2$ such that the observability matrix $\mathcal{O}_{[0, T_0]}(\bm{A}, \bm{C})$ is full column rank. According to the trajectory generation algorithm developed in Subsection~\ref{subsec: TrajGenPartial}, we setup $T=K+T_0-1=31$ and collect historic measurements of length $L = (m + 1)T -1 + n=96$. With a sampling period of 0.1s, the data collection takes 9.6s. Hence, the data collection does not scale significantly even when only half of the state is directly observed. Figure~\ref{fig:Loss_AB_full_main}(a)-(c) compares the training loss, testing loss and the number of samples, respectively. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples in the system.
\begin{figure}[H]
\centering
\subfigure[Training Loss]{\includegraphics[width=1.8in]{figure/Loss_ABpartial.png}}
\subfigure[Testing Loss]{\includegraphics[width=1.8in]{figure/Loss_ABpartial_batchVSLoss.png}}
\subfigure[Number of samples]{\includegraphics[width=1.8in]{figure/Loss_ABpartial_BatchVSsample.png}}
\caption{Performance of learning output-feedback controllers in the batch reactor system. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples on the system.}\label{fig:Loss_AB_partial}
\end{figure}
\subsection{Voltage control in power distribution networks}\label{app:exp_voltage}
To validate the performance of the proposed method on a larger system, we conduct experiments on the voltage control problem in IEEE 33bus test feeder~\citep{baran1989network}. We adopt the Lindisflow model where the dynamics of voltage is described by a linear transition model~\citep{ cui2022decentralized, zhu2015fast}. The state $\bm{x}(t)\in\real^{32}$ is voltage in all the buses apart from the reference bus (the voltage of the reference bus is fixed). The action is the reactive power in each bus. We assume that there is no real-time communication between buses during real-time implementation, so the action at each bus can only change with the local measurement of voltage. The goal is to train a linear decentralized feedback controller to minimize total voltage deviation as well as the control effort in the time horizon $K=20$, written as $ J(\bm{\theta}) = \sum_{k=1}^{K}\left\| \bm{y}(k)\right\|_1 +0.3 \left\|\bm{u}_{\bm{\theta}}(k)\right\|_1$. The number of training episode is $E=500$.
\textbf{Case I: the state is directly observed.} The state is directly observed so the action $\bm{u}(t)\in\real^{32}$. We setup $T=K=20$ and collect historic trajectory of the length $L = (m + 1)T -1 + n=691$. With a sampling period of 1s~\citep{chen2021enforcing}, the data collection takes 691s.
In each episode of training, we use Algorithm~\ref{alg: TrajGenFull} to generate trajectories with the batchsize 1000. Figure~\ref{fig:Loss_voltage_full}(a)-(c) compares the training loss, testing loss and the number of samples, respectively. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples on the system.
\textbf{Case II: only $20$ elements in the state is observed. } We assume only 20 buses are measured and controlled, so $\bm{y}(t),\bm{u}(t)\in\real^{20}$. The observability matrix $\mathcal{O}_{[0, T_0]}(\bm{A}, \bm{C})$ becomes full column rank when $T_0=3$. The time horizon of trajectory is $K=20$. According to the trajectory generation algorithm developed in Subsection~\ref{subsec: TrajGenPartial}, we setup $T=K+T_0-1=22$ and collect historic trajectory of length $L = (m + 1)T -1 + n=493$. With a sampling period of 1s~\citep{chen2021enforcing}, the data collection takes 493s. Figure~\ref{fig:Loss_voltage_partial_main}(a)-(c) compares the training loss, testing loss and the number of samples, respectively. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples on the system.
\begin{figure}[H]
\centering
\subfigure[Training Loss]{\includegraphics[width=1.8in]{figure/Loss_voltage.png}}
\subfigure[Testing Loss]{\includegraphics[width=1.8in]{figure/Loss_voltageFull_batchVSLoss.png}}
\subfigure[Number of samples]{\includegraphics[width=1.8in]{figure/Loss_voltageFull_BatchVSsample.png}}
\caption{Performance of learning state-feedback controllers in power distribution network. PG-TrajectoryGen achieves the same training and testing loss as PG-Sample-1000 with much smaller number of samples on the system.}\label{fig:Loss_voltage_full}
\end{figure}
\section{Introduction}\label{sec: intro}
\section{ Preliminaries and problem formulation}
\label{sec: background}
\input{Preliminaries.tex}
\section{Trajectory Generation}
\label{sec:traj}
\input{Trajectory_Generation}
\section{Partial Observation}
\label{sec: model}
\input{model.tex}
\section{Sample efficient algorithm}
\label{sec: sample}
\input{Sample_efficient.tex}
\section{Introduction}
Reinforcement learning (RL) is becoming increasingly popular for the controller design of dynamical systems, especially when the exact system model or parameters are not available~\citep{zheng2021sample,hu2022towards}. Much of the success in RL has relied on sampling-based algorithms such as the policy gradient algorithm~\citep{Sutton2018RL, fazel2018global}, which typically requires repeated online interactions with the system. Moreover, the control actions need to incorporate sufficient exploration for the learning algorithm to search for better policies~\citep{jin2021pessimism}. However, sampling large batch of trajectories is expensive in many real-world problems (e.g., in energy systems, robotics or healthcare), and the exploration requirement for safety-critical systems may be dangerous~\citep{levine2020offline, fujimoto2021minimalist}.
When the online interactions with the system are limited, two categories of RL methods are designed: off-policy RL and offline RL.
Off-policy RL methods (e.g., Q-learning and its variants) typically learn a quality function (i.e, Q function) leveraging past experience, but online interactions with explorations are still required after the update of the control policies~\citep{ghasemipour2021emaq}.
Offline RL seeks to learn from a
fixed dataset without interactions with environments~\citep{gulcehre2020rl, jin2021pessimism}. The fundamental challenge is that once the control policies have been updated, the trajectories of the system under the new policies would not have the same distribution as the historical data~\citep{fujimoto2021minimalist, ghasemipour2021emaq}. As a result, existing algorithms typically constrain the control policy to be close with the policy utilized in the fixed dataset~\citep{ ostrovski2021difficulty, fujimoto2021minimalist}.
Since most algorithms need to do some exploration, it is believed that past data is not helpful if high-reward regions are not covered in the collected trajectories~\citep{levine2020offline, jin2021pessimism}.
A fundamental reason behind the above challenges is that the training process is restricted to fixed trajectories in the historical data, hence RL algorithms need to be restricted to historical control policies. We look at the problem from the other direction: \textit{Using only historical data, can we generate trajectories that follow the same distribution induced by a new control policy?}
This paper proposes a trajectory generation algorithm for linear systems, which adaptively generates new trajectories as if the system were being operated and explored under the updated control policies.
The key insights come from the fundamental lemma for linear systems, which shows that any set of persistently exciting trajectories can be used to represent the input-output behavior of the system~\citep{willems2005note, de2019formulas, markovsky2022identifiability}. Inspired by this, we generate trajectories from linear combinations of historical trajectories, which can come from routine operations of the system. The set of linear combinations is derived from the updated control policy with perturbations on actions, such that the generated trajectory is the same as the trajectory sampled on the real system. This adaptive approach overcomes the challenges in distributional shift and lack of exploration. This is complementary to recent advances in learning linear feedback controllers for linear systems (See, for example,~\citep{fazel2018global,zheng2021sample,tang2021analysis,hu2022towards} and references within), where trajectories are sampled through online interactions.
Experiments
show that the proposed method significantly reduces the number of sampled data needed for RL algorithms.
We summarize the contributions as follows:
\begin{enumerate}[noitemsep,nolistsep,leftmargin=*, label=\arabic*)]
\item We propose a simple end-to-end approach to generate input-output trajectories for linear systems, which significantly reduces the burden of sample collection in RL methods. In Theorem~\ref{thm: unque_trajectory0},
we prove that the generated trajectories is adaptive to the distribution shift of any linear state-feedback controller with perturbations on actions for explorations. When the states are not directly observed, Theorem~\ref{thm: unque_trajectory0_partial} shows that this framework also applies to output-feedback control by defining an extended state from the observations.
\item The proposed trajectory generation algorithm is compatible with any RL methods that learns from trajectories. The number of samples needed to learn is independent to the batch size (the number of trajectories in each episode) and the number of training episodes.
\end{enumerate}
\section{ Preliminaries and problem formulation}
\label{sec: background}
\input{Preliminaries.tex}
\section{Trajectory Generation for State-Feedback Control}
\label{sec:TrajGen_FullState}
\input{TrajGen_FullState}
\section{Trajectory Generation for Output-Feedback Control}
\label{sec: TrajGen_PartialState}
\input{model.tex}
\input{Sample_efficient.tex}
\vspace{-0.5cm}
\section{Experiment}
\label{sec: experiment}
\input{experiment.tex}
\vspace{-1.2cm}
\section{Conclusions}
This paper proposes a trajectory generation algorithm for learning linear feedback controllers in linear systems.
We prove that the algorithm generates trajectories with the exact distribution as if they are sampled by interacting with the real system using the updated control policy. In particular, the algorithm extends to systems where the states are not directly observed. This is done by equivalently defining system transition dynamics using input-output trajectories. Experiments show that the proposed method significantly reduces the number of sampled data needed for RL algorithms.
\subsection{Extended states for constructing Markov decision process}
Let $
\mathcal{O}_{[0, \ell]}(\bm{A}, \bm{C}):=\operatorname{col}\left(\bm{C}, \bm{C} \bm{A}, \ldots, \bm{C} \bm{A}^{\ell-1}\right)
$ be the extended observability matrix.
The lag of the system~\eqref{eq:sys_full} is defined by the smallest integer $\ell\in \mathbb{Z}_{\geq 0}$ such that the observability matrix $\mathcal{O}_{[0, \ell]}(\bm{A}, \bm{C})$ has rank $n$, i.e., the state can be reconstructed from $\ell$ measurements~\citep{huang2021robust}.
Let $T_0\geq\ell$ be the length of a trajectory.
Define the extended states as
\vspace{-0.1cm}
\begin{equation}
\mathcal{X}(k-1) :=\left[\begin{array}{c}
\bm{y}(k-T_0);
\cdots ;
\bm{y}(k-1);
\bm{u}(k-T_0);
\cdots ;
\bm{u}(k-2)
\end{array}\right].
\end{equation}
Then extending the system transition from time step 0 to $T_0$ gives
\vspace{-0.1cm}
\begin{equation}\label{eq:sys_extended}
\mathcal{X}(k)=\Tilde{\bm{A}}\mathcal{X}(k-1)+\Tilde{\bm{B}}\bm{u}(k-1)
\text{ for } k\geq T_0, k\in\mathbb{Z},
\end{equation}
which is a Markov decision process in terms of the extended states. Detailed proof and the definition of system transition matrix $(\Tilde{\bm{A}},\Tilde{\bm{B}})$ is given in Appendix~\ref{app: transition_partial}.
For the output-feedback control law in~\eqref{eq:control_policy},
we have $ p\left(\bm{u}(k)|\mathcal{X}(k)\right)=p\left(\bm{u}(k)|\bm{y}(k)\right)
$ and it is straightforward to show that policy gradient algorithm using~\eqref{eq: PG_grad} still works. The proof is given in Appendix~\ref{app:Policy Gradient}.
| {'timestamp': '2022-12-02T02:20:05', 'yymm': '2211', 'arxiv_id': '2211.17249', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17249'} | arxiv |
\section{Introduction}
\label{sec:intro}
Electronic health records (EHR) are collected as part of routine medical care, and include demographic information, disease diagnoses, laboratory results, medication prescriptions, etc., providing a patient’s clinical state over time. Recent machine learning techniques have been used to exploit the richness of EHR data at scale for diagnosis, prognosis, treatment and understanding of disease \citep{https://doi.org/10.48550/arxiv.1907.09538, STEINBERG2021103637}. Many medical terminologies are used across clinical data sets, and the standard practice involves mapping clinical terms across different resources \citep{https://doi.org/10.48550/arxiv.1907.09538, HASSAINE2020103606} or onto common data models \citep{10.7326/0003-4819-153-9-201011020-00010}.
Here, we propose sEHR-CE (language modelling of \textbf{S}tructured \textbf{EHR} data for patient \textbf{C}ohort \textbf{E}xpansion), a novel framework based on transformers to enable the integrated analysis of multiple clinical resources without relying on any manual curation and mapping. Using text descriptions of concepts as input, our method generalises across data modalities and terminologies, i.e. text and structured EHR. This enables us to leverage a plethora of pre-trained language models like PubMedBERT \citep{pubmedbert} to encode each patient’s medical record. We ask the model to learn representations of clinical histories from diagnosed patients (cases) to predict phenotypes (such as diseases). In the absence of a directly comparable model, we evaluate the performance of our model against that of \citet{https://doi.org/10.48550/arxiv.1907.09538}, as the state-of-the-art approach for learning clinical term embeddings for future disease prediction. See Appendix \ref{sec:related_work} for a more complete survey.
In our validation experiments, we will show that the model can then identify individuals with missing diagnoses (controls) that share a similar clinical history with cases, indicating they might have the disease or be at risk of developing it. The contributions of our paper are \textbf{(i)} the presentation of a cohort expansion method that provides phenotype predictions outperforming non-text and single terminology approaches, and \textbf{(ii)} an in-depth qualitative evaluation demonstrating that positively predicted controls share similar clinical representations with cases, providing a high degree of evidence that these may be previously undiagnosed or misdiagnosed individuals. Finally, we demonstrate our method’s potential for patient stratification by disease severity.
\section{Methods}
\label{sec:method}
\textbf{Input Generation}. For each EHR source and associated ontology $a \in \mathcal{A}$, we denote the set of concepts (e.g. clinical terms) as $\Theta_a$, and the set of text descriptions as $\Xi_a$. The total vocabulary of concepts and text descriptions across all ontologies is denoted by $\Theta = \bigcup\limits_{a \in \mathcal{A}} \Theta_a$ and $\Xi = \bigcup\limits_{a \in \mathcal{A}} \Xi_a$, respectively. For each patient, we define their full clinical history through time and across sources by the concatenation of sequences of clinical descriptions $(\xi_{\theta_1}, \ldots ,\xi_{\theta_t})$, $\xi_{\theta_i} \in \Xi$, $i=1, \ldots, t$, ordered in time. More details and an example can be found in Appendix \ref{fusing}, and Figure \ref{figure:hosp_gp}. To form the input, we process the raw text sequence of descriptions into tokens (e.g. words and sub-words) $X = W(\xi_{\theta_1},\ldots,\xi_{\theta_t}) = (x_1,\ldots,x_{n})$ under a fixed size vocabulary $V$ with the WordPiece tokenizer $W$ \citep{https://doi.org/10.48550/arxiv.1609.08144}.
\textbf{Label Generation}. Let $\Delta=(d_1, \ldots , d_D)$ denote an ordered set of clinical outcomes or events, in our case disease phenotypes $d_i$. For each phenotype $d_i\in\Delta$, we let $\mathbf{1}_{d_i}$ be an indicator function that assigns a binary label to individuals according to the presence or absence of $d_i$. To define $\mathbf{1}_{d_i}$, we rely on external oracles or phenotype definitions, such as CALIBER (Appendix \ref{labelling}). Figure \ref{figure:labelling} shows a schematic of input and label generation for a given patient.
\begin{figure}[ht]
\centering
\includegraphics[width=10cm]{oracle_tagger.png}
\caption{Schematic of mapping a unified clinical history to an input text sequence with multi-label target vector using an oracle annotation \protect\footnotemark.}
\label{figure:labelling}
\end{figure}
\footnotetext{Any patient data shown is simulated and does not represent data of real patients.}
\textbf{Model Design}. Let $X^{(p)} = (x^{(p)}_1, \ldots ,x^{(p)}_{n})$ denote the tokenized input sequence of individual $p$. It forms the input to an encoding function
$\mathbf{x}^{(p)}_1, \ldots, \mathbf{x}^{(p)}_n$ = \textit{Encoder}$(X^{(p)})$, where each $\mathbf{x}_i$ is a fixed-length vector representation of each input token $x_i$. Let $\mathbf{y}^{(p)}=(y^{(p)}_1, \ldots, y^{(p)}_D)$, $y^{(p)}_i\in \{0,1\}$, be labels denoting presence or absence of phenotypes $d_1,\ldots, d_D$. Given a learned representation over inputs, we decode over $\mathbf{y}^{(p)}$ under the predictive model $\mathbf{P}(\mathbf{y}^{(p)}|X^{(p)})$. We calculate the probability of each phenotype $d_i$ given the input sequence encoding $\mathbf{P}(y^{(p)}_i|\textbf{x}^{(p)}_1,\dots, \textbf{x}^{(p)}_n)$ via a decoder module. Specifically, we decode the representation into logits per phenotype $z^{(p)}_1, \dots, z^{(p)}_D =$ \textit{Decoder}$(\textbf{x}^{(p)}_1,\dots, \textbf{x}^{(p)}_n)$ and calculate the probability per phenotype as $\mathbf{P}(y^{(p)}_d|\textbf{x}^{(p)}_1,\dots, \textbf{x}^{(p)}_n) = \sigma(z^{(p)}_d)$, where $\sigma$ denotes the sigmoid function (Figure \ref{figure:model_diagram_small}). We will omit the superscript $(p)$ denoting the sample index in the remainder of the text.
\subsection{Data Augmentation}\label{data_augmentation}
\textbf{Clinical Masking}. We mask input descriptions $\xi_{\theta}$ from term-description pairs $(\theta, \xi_{\theta})$ with $\mathbf{1}_{d}(\theta, \xi_{\theta})=1$ for $d \in \Delta$ using the following clinical masking strategy during training and validation as in \citet{DBLP:journals/corr/abs-1810-04805, https://doi.org/10.48550/arxiv.1901.11196}: \textbf{Remove} $\xi_{\theta}$ with 80\% probability, \textbf{retain} $\xi_{\theta}$ with
10\% probability, and \textbf{replace} $\xi_{\theta}$ with a randomly selected description from the corpus with 10\% probability.
Figure \ref{figure:augment} displays a worked example. During testing, these term-description pairs are fully removed from the input sequence.
\begin{figure*}[h]
\setlength{\belowcaptionskip}{-5pt}
\centering
\includegraphics[width=14cm]{masking_hf.png}
\caption{Example of clinical masking strategy for a given patient history with \textbf{Heart Failure}.}
\label{figure:augment}
\end{figure*}
\textbf{Comorbidities}. This masking approach is straightforward if an individual has only one positive label, but many people have comorbidities, e.g. co-occurring conditions. To allow for a sample with multiple positive labels $d_{i_1}, \ldots , d_{i_n}$, we create $n$ input samples by replicating both the input sequence and target vector of phenotype labels. Consider the $j$th replicated input sequence, and let $d = d_{i_j}$. We mask this replicated input sequence with the masking strategy for phenotype $d$ described in the previous section; e.g. $\xi_{\theta}$ is masked if $\mathbf{1}_{d}(\theta, \xi_{\theta})=1$ (Figure \ref{figure:masking_comorbidities}).
\subsection{Defining a Loss Function in the Presence of Comorbidities and varying Prevalences}\label{loss_weights}
\textbf{Loss weights}. The data augmentation approach for comorbidities may lead to our model overfitting when an input sequence contains the descriptions associated with an existing phenotype $d$ that is not masked. To account for the contribution of the target vector $\mathbf{y}$ to the loss function in these scenario, we define a binary masking vector $\mathbf{\gamma}^{j}=(\gamma^{j}_1, \ldots, \gamma^{j}_D)$ where $\gamma^{j}_j=1$ and $\gamma^{j}_k=0$, $k=1,\ldots,D$, $k\not=j$. Individuals with no positive phenotype labels are assigned an all-zero masking vector (Figure \ref{figure:masking_comorbidities}). Then, for a given input text sequence $X$, target label vector $\mathbf{y}=(y_1, \ldots, y_D)$ and masking vector $\mathbf{\gamma}=(\gamma_{1}, \ldots, \gamma_{D})$, we define the loss weights by setting $\omega_{d} = 0$ if $y_{d} = 1$ and $\gamma_d = 0$, and $\omega_{d} = 1$ if $y_{d} = 0$ or $y_{d} = 1$ and $\gamma_d = 1$.
\begin{figure*}[h!]
\centering
\setlength{\belowcaptionskip}{-10pt}
\includegraphics[width=11cm]{masking_comorbidities.png}
\caption{ Example of an input sequence containing descriptions relevant to two positive phenotype labels in the target vector $y$. The input sequence is duplicated, and each phenotype is masked once and a loss weights vector is defined. Clinical terms relating to a directly associated phenotype $d$ remain in the input data ($y_d=1$ and $\gamma_d=0$) but get assigned a loss weight $w_d=0$ and so do not contribute to the loss function.}
\label{figure:masking_comorbidities}
\end{figure*}
\textbf{Positive weights}. Because some diseases are very rare, whereas others are very common, our prediction classes are expected to be highly imbalanced in the practical setting. For cohort expansion, we want to increase recall while balancing a decline in precision. For $d\in\Delta$, let $TN_d$ and $TP_d$ denote the total number of negative and positive examples of $d$ in the training set. We define the positive weight $\rho_d$ as $\rho_d=TN_d/TP_d$, for all d $\in\Delta.$
Our loss function is defined as a mean-reduced binary cross-entropy loss function over phenotypes, where disease prevalence and comorbidities are handled with loss and positive weights:
\begin{equation}\label{lossfunction}
\mathcal{L}^{(p)}= -\frac{1}{|\Delta|} \sum_{d \in \Delta} \omega_{d}^{(p)} (\rho_dy_{d}^{(p)} \log \sigma({z_{d}^{(p)}}) \\ + (1-y_{d}^{(p)}) \log \sigma(1-z_{d}^{(p)})),
\end{equation}
where $\sigma$ denotes the sigmoid function, $\omega_d$ the comorbidity-derived loss weight, $\rho_d$ the positive weight, and $z_{d}^{(p)}$ the predicted probability for phenotype $d\in \Delta$ for sample (e.g. individual) $p$.
\section{Experiments and Results}
\label{sec:results}
\textbf{Data.} This research has been conducted using the UK Biobank (UKBB) Resource under Application Number 43138, a large-scale research study of around $500$k individuals \citep{10.1371/journal.pmed.1001779}. We restrict the data set to those that have entries in both hospital and GP records, reducing our cohort to $155$k. To assess the quality of our model predictions, we choose four diseases that differ in terms of prevalence and clinical characteristics (Appendix \ref{apd:model}): Type 2 diabetes mellitus (T2DM), Heart failure (HF), Breast Cancer, and Prostate Cancer. We use validated phenotype definitions from CALIBER \citet{kuan2019chronological} to label patients with each of the diseases (Appendix \ref{apd:data_proc}). We test the performance of our model on its ability to diagnose known cases, compare it to other methods, and evaluate associations of clinical features with predictions on T2DM.
\textbf{sEHR-CE.} We use the pre-trained language model PubMedBERT \citep{pubmedbert} as the encoder of the tokenised input sequences of clinical term descriptions. Since our input systematically differs from the general scientific text on which PubMedBERT was trained, we fine-tune on the masked-language modeling (MLM) task using the full UKBB cohort. The proposed model sEHR-CE uses the fine-tuned encoder and a fully connected linear layer as the decoder. To train on the multi-label classification task of outcome prediction, we split our data set into five equally sampled folds \textit{$f_0$,...$f_4$} containing unique patients, and mask the data according to our strategy (Section \ref{data_augmentation}, Figure \ref{figure:input_diagram}). We train a total of five models on three folds, holding back folds $f_i$ for validation and $f_{(i+1)\bmod{5}}$ for testing for model $i$, $i=1,\ldots,5$ (Figure \ref{figure:folds_diagram}). All results presented are predictions on the independent test set. For masking and training details, see Appendix \ref{apd:training}.
\textbf{Baseline Models}. We compare the performance of our model sEHR-CE to BEHRT \citep{https://doi.org/10.48550/arxiv.1907.09538}, which takes a tokenised sequence of clinical terms, age and position embeddings as input. Ontologies from hospital and GP records are mapped to CALIBER definitions, removing unmapped terms (more details in Appendix \ref{apd:eval}). We train five such BEHRT models to predict an individual developing the four phenotypes on the same five data splits as sEHR-CE. Similarly, we train five sEHR-CE models restricted to CALIBER tokens (denoted sEHR-CE-codes) for comparison. Figure \ref{figure:disease_dist_all} shows the distributions of predicted probabilites for all phenotypes across all methods. sEHR-CE shows the best performance across all four phenotypes in terms of recall at $0.5$ and AUC on the test set (Table \ref{table:results_SOTA}, Figure \ref{figure:auprc}). BEHRT performs slightly better than sEHR-CE-codes, indicating a benefit of adding visit position and age. Performance varies across phenotypes, presumably due to different clinical characteristics making some diseases easier to predict than others.
\begin{table*}[h]
\centering
\small
\addtolength{\tabcolsep}{-1pt}
\begin{tabular*}{\textwidth}{l|clclclclcl}
\hline
& \multicolumn{2}{c}{T2D} & \multicolumn{2}{c}{HF} & \multicolumn{2}{c}{Breast Cancer} & \multicolumn{2}{c}{Prostate Cancer} & \multicolumn{2}{c}{Average} \\
& \multicolumn{1}{l}{Recall} & PRC & \multicolumn{1}{l}{Recall} & PRC & \multicolumn{1}{l}{Recall} & PRC & \multicolumn{1}{l}{Recall} & PRC & \multicolumn{1}{l}{Recall, std} & PRC \\ \hline
sEHR-CE-codes & 0.64 & 0.70 & 0.76 & 0.60 & 0.42 & 0.45 & 0.36 & 0.26 & 0.55 $\pm$ 0.19 & 0.50 \\
BEHRT & 0.66 & 0.70 & 0.78 & 0.61 & 0.48 & 0.53 & 0.41 & 0.29 & 0.58 $\pm$ 0.17 & 0.53 \\
\textbf{sEHR-CE} & \textbf{0.74} & 0.74 & \textbf{0.85} & 0.69 & \textbf{0.55} & 0.55 & \textbf{0.57} & 0.47 & \textbf{0.68 $\pm$ 0.14} & 0.61 \\ \hline
\end{tabular*}
\caption{Average and phenotype specific recall and AUCPR at $0.5$ on the test sets.}
\label{table:results_SOTA}
\end{table*}
\subsection{Clinical evaluation on Type 2 Diabetes Mellitus}
T2DM lends itself as a use case to qualitatively evaluate the predictions of missed cases, as it is a well-studied, slowly developing disease with varying disease severity. We used thresholds based on the 98$^{th}$, 90$^{th}$ and 12$^{th}$ percentiles of sEHR-CE's predicted probabilities (Figure \ref{figure:disease_dist_all}) to define five different groups (Table \ref{table:patient_groups}): regular cases, cases predicted with high probability, cases predicted with low probability, regular controls and controls predicted with high probability (missed cases).
\textbf{Measures of Disease Severity}. Haemoglobin A1c (HbA1c) is a blood biomarker used to diagnose and monitor diabetes. A level of 48mmol/mol or higher is considered diabetes; while a value between 42 and 48 mmol/mol is considered pre-diabetes. The input data did not include such biomarker data, so we use it here for evaluation.
We aggregated HbA1c measurements taken in primary care (GP) of each individual by taking the $95$-th percentile value. Figure \ref{figure:hba1c} shows that cases predicted with high probability had the highest HbA1c mean levels. Cases identified with low probability were in the prediabetic range of HbA1c levels, indicating a less severe state. Missed cases had elevated HbA1c levels close to the prediabetic stage, representing individuals at risk of developing T2DM. We further investigated the association of the T2DM predicted probabilities with other measures of disease severity, expanded in Appendix \ref{apd:t2dm_eval}. Taken together, our results demonstrate that sEHR-CE's predicted probabilities of being diagnosed with T2DM are associated with disease severity.
\textbf{Polygenic risk scores}. Genetic risk for complex diseases like T2DM arises from many genetic changes that, when taken together, can increase an individual's risk of developing the disease, which can be defined by polygenic risk scores (PRS). \cite{Sinnott-Armstrong660506} developed PRS based on the UK Biobank participants for a set of diseases, including T2DM. We computed and standardised T2DM PRS across all individuals in our cohort \citep{prs_use}. Figure \ref{figure:prs} demonstrates that higher predicted probability of T2DM was associated with a higher genetic risk.
\begin{figure}
\centering
\begin{subfigure}[t]{0.49\textwidth}
\includegraphics[width=\textwidth]{hba1c.png}
\caption{}
\label{figure:hba1c}
\end{subfigure}
\begin{subfigure}[t]{0.49\textwidth}
\includegraphics[width=\textwidth]{prs.png}
\caption{}
\label{figure:prs}
\end{subfigure}
\caption{\ref{figure:hba1c} HbA1c distribution across groups in the test sets with diabetes diagnosis ranges shown as dashed lines. Significant p-values are indicated with *** (t-test, $\alpha = .001$). \ref{figure:prs} Median T2DM prediction of individuals in the test sets grouped by the percentiles of the polygenic risk score.}
\end{figure}
\section{Conclusion}\label{sec:conclusion}
We presented a data-driven method for cohort expansion based on language modelling. Our approach fuses primary and secondary care data via text, and we propose a data augmentation approach to allow for comorbidities in a patient's history. Our method predicts disease phenotype labels more accurately than non-text and single terminology approaches. We presented a high degree of evidence that our model identifies previously undiagnosed individuals that can extend the original cohort for downstream analysis. Future work will consider methods that are less restrictive on sequence length \citep{transformer, longformer} and allow for irregular time steps \citep{shukla2021multitime} and age \citep{time2vec}, as well as adding more data sources (e.g. medications).
\section{Acknowledgements}
This research has been conducted using the UK Biobank Resource under Application Number 43138. Using real patient data is crucial for clinical research and to find the right treatment for the right patient. We would like to thank all participants who are part of the UK Biobank, who volunteered to give their primary and secondary care and genotyping data for the purpose of research. UK Biobank is generously supported by its founding funders the Wellcome Trust and UK Medical Research Council, as well as the British Heart Foundation, Cancer Research UK, Department of Health, Northwest Regional Development Agency and Scottish Government.
We are particularly grateful to Prof. Spiros Denaxas, and Drs. Aaron Sim, Andrea Rodriguez-Martinez, Nicola Richmond, Sam Abujudeh, and Julien Fauqueur for their feedback, insightful comments and the many inspiring conversations.
| {'timestamp': '2022-12-01T02:18:23', 'yymm': '2211', 'arxiv_id': '2211.17121', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17121'} | arxiv |
\section{Summary}\label{summary}}
QMKPy provides a Python framework for modeling and solving the quadratic
multiple knapsack problem (QMKP). It is primarily aimed at researchers
who develop new solution algorithms for the QMKP. QMKPy therefore mostly
functions as a testbed to quickly implement novel algorithms and compare
their results with existing ones. However, the package also already
includes implementations of established algorithms for those who only
need to solve a QMKP as part of their research.
The QMKP is a type of knapsack problem which has first been analyzed by
Hiley \& Julstrom (\protect\hyperlink{ref-Hiley2006}{2006}). For a basic
overview of other types of knapsack problems see, e.g., Kellerer et al.
(\protect\hyperlink{ref-Kellerer2004}{2004}). As in the regular multiple
knapsack problem, the goal is to assign \(N\in\mathbb{N}\) items with
given weights \(w_i\in\mathbb{R}_{+}\) and (non-negative) profit values
\(p_i\in\mathbb{R}_{+}\) to \(K\in\mathbb{N}\) knapsacks with given
weight capacities \(c_u\in\mathbb{R}_{+}\), such that a total profit is
maximized. In the QMKP, there exist additional joint profits
\(p_{ij}\in\mathbb{R}_{+}\) which are yielded when items \(i\) and \(j\)
are packed into the same knapsack.
Mathematically, the QMKP is described by the following optimization
problem \begin{subequations}
\begin{alignat}{3}
\max\quad & \sum_{u\in\mathcal{K}}\Bigg(\sum_{i\in\mathcal{A}_u} p_{i} &+&\sum_{\substack{j\in\mathcal{A}_u \\ j\neq i}} p_{ij}\Bigg)\\
\mathrm{s.t.}\quad & \sum_{i\in\mathcal{A}_u} w_{i} \leq c_u & \quad & \forall u\in\mathcal{K} \\
& \sum_{u=1}^{K} a_{iu} \leq 1 & & \forall i\in\{1, 2, \dots{}, N\}
\end{alignat}
\end{subequations} where \(\mathcal{K}=\{1, 2, \dots{}, K\}\) describes
the set of knapsacks, \(\mathcal{A}_u\subseteq\{1, 2, \dots{}, N\}\) is
the set of items that are assigned to knapsack \(u\) and
\(a_{iu}\in\{0,1\}\) is a binary variable indicating whether item \(i\)
is assigned to knapsack \(u\).
\hypertarget{statement-of-need}{%
\section{Statement of need}\label{statement-of-need}}
The QMKP is an NP-hard optimization problem and therefore, there exists
a variety of (heuristic) algorithms to find good solutions for it. While
Python frameworks already exist for the standard (multiple) knapsack
problem and the quadratic knapsack problem, they do not consider the
\emph{quadratic multiple} knapsack problem. However, this type of
problem arises in many areas of research. In addition to the typical
problems in Operations Research, it also occurs in distributed computing
(\protect\hyperlink{ref-Rust2020}{Rust et al., 2020}) and in the area of
wireless communications (\protect\hyperlink{ref-Besser2022wiopt}{Besser
et al., 2022}).
For the classic knapsack problem and the quadratic \emph{single}
knapsack problem, many well-known optimization frameworks like Gurobi
(\protect\hyperlink{ref-gurobi}{Gurobi Optimization, LLC, 2022}) and
OR-Tools (\protect\hyperlink{ref-ortools}{Perron \& Furnon, 2022})
provide solution routines. However, they are not directly applicable to
the QMKP. Furthermore, it can be difficult for researchers to reproduce
results that rely on commerical software.
Therefore, QMKPy aims to close that gap by providing an open source
testbed to easily implement and compare solution algorithms.
Additionally, Python is widely used among researchers and enables easy
to read implementations. This further supports the goal of QMKPy to
promote sharable and reproducible solution algorithms.
For initial comparisons, the software already implements multiple
solution algorithms for the QMKP, including a \emph{constructive
procedure (CP)} based on Algorithm 1 from Aïder et al.
(\protect\hyperlink{ref-Aider2022}{2022}) and the greedy heuristic from
Hiley \& Julstrom (\protect\hyperlink{ref-Hiley2006}{2006}). A second
algorithm that is included is the \emph{fix and complete solution (FCS)
procedure} from Algorithm 2 in Aïder et al.
(\protect\hyperlink{ref-Aider2022}{2022}). Additionally, a collection of
reference QMKP instances that can be used with QMKPy is provided at
(\protect\hyperlink{ref-QMKPyDatasets}{Besser, 2022}). This dataset
includes the well-known reference problems from Hiley \& Julstrom
(\protect\hyperlink{ref-Hiley2006}{2006}), which in turn are based on
the quadratic single knapsack problems from Billionnet \& Soutif
(\protect\hyperlink{ref-Billionnet2004}{2004}).
The open source nature of QMKPy and its aim at researchers encourages
the implementation of more algorithms for solving the QMKP that can
become part of the QMKPy framework.
The most notable benefits when implementing an algorithm using QMKPy are
the following:
\begin{itemize}
\tightlist
\item
No additional overhead is required. Only a single function with the
novel solution algorithm needs to be implemented.
\item
Generic unit tests are available to make sure that the novel algorithm
fulfills the set of basic criteria.
\item
The ability of loading and saving problem instances allows for quick
and easy testing of any algorithm against reference datasets. This
enables reproducible research and creates a high degree of
comparability between different algorithms.
\end{itemize}
\hypertarget{references}{%
\section*{References}\label{references}}
\addcontentsline{toc}{section}{References}
\hypertarget{refs}{}
\begin{CSLReferences}{1}{0}
\leavevmode\vadjust pre{\hypertarget{ref-Aider2022}{}}%
Aïder, M., Gacem, O., \& Hifi, M. (2022). Branch and solve
strategies-based algorithm for the quadratic multiple knapsack problem.
\emph{Journal of the Operational Research Society}, \emph{73}(3),
540–557. \url{https://doi.org/10.1080/01605682.2020.1843982}
\leavevmode\vadjust pre{\hypertarget{ref-QMKPyDatasets}{}}%
Besser, K.-L. (2022). \emph{QMKPy datasets} (Version v1.0) {[}Computer
software{]}. Zenodo. \url{https://doi.org/10.5281/ZENODO.7157144}
\leavevmode\vadjust pre{\hypertarget{ref-Besser2022wiopt}{}}%
Besser, K.-L., Jorswieck, E. A., \& Coon, J. P. (2022, September).
Multi-user frequency assignment for ultra-reliable {mmWave} two-ray
channels. \emph{20th International Symposium on Modeling and
Optimization in Mobile, Ad Hoc, and Wireless Networks (WiOpt)}.
\leavevmode\vadjust pre{\hypertarget{ref-Billionnet2004}{}}%
Billionnet, A., \& Soutif, Éric. (2004). Using a mixed integer
programming tool for solving the 0–1 quadratic knapsack problem.
\emph{INFORMS Journal on Computing}, \emph{16}(2), 188–197.
\url{https://doi.org/10.1287/ijoc.1030.0029}
\leavevmode\vadjust pre{\hypertarget{ref-gurobi}{}}%
Gurobi Optimization, LLC. (2022). \emph{{Gurobi Optimizer Reference
Manual}}. \url{https://www.gurobi.com}
\leavevmode\vadjust pre{\hypertarget{ref-Hiley2006}{}}%
Hiley, A., \& Julstrom, B. A. (2006). The quadratic multiple knapsack
problem and three heuristic approaches to it. \emph{Proceedings of the
8th Annual Conference on Genetic and Evolutionary Computation - GECCO
’06}, 547–552. \url{https://doi.org/10.1145/1143997.1144096}
\leavevmode\vadjust pre{\hypertarget{ref-Kellerer2004}{}}%
Kellerer, H., Pferschy, U., \& Pisinger, D. (2004). \emph{Knapsack
problems}. Springer Berlin Heidelberg.
\url{https://doi.org/10.1007/978-3-540-24777-7}
\leavevmode\vadjust pre{\hypertarget{ref-ortools}{}}%
Perron, L., \& Furnon, V. (2022). \emph{OR-tools} (Version v9.4)
{[}Computer software{]}. Google.
\url{https://developers.google.com/optimization/}
\leavevmode\vadjust pre{\hypertarget{ref-Rust2020}{}}%
Rust, P., Picard, G., \& Ramparany, F. (2020). Resilient distributed
constraint optimization in physical multi-agent systems. \emph{24th
European Conference on Artificial Intelligence (ECAI 2020)}, 195–202.
\url{https://doi.org/10.3233/FAIA200093}
\end{CSLReferences}
\end{document}
| {'timestamp': '2022-12-01T02:20:56', 'yymm': '2211', 'arxiv_id': '2211.17222', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17222'} | arxiv |
\section{Introduction}
Over the years, our reliance on social media as an information source has increased, leading to an exponential increase in the spread of \emph{fake news}. To counter this, researchers have proposed various approaches for fake news detection (FND). Models trained on one domain often perform poorly on datasets from other domains due to the domain shift (Figure 1(1)). Some works show the efficacy of domain adaptation for cross-domain FND by extracting domain-invariant features (Figure 1(2)) for classification \citep{DA_FND}. However, adapting domains does not ensure that features in different classes align correctly across domains, which sometimes has a negative impact on performance. Some works have shown a correlation between fake news and their intrinsic emotions \citep{Dual_1, Emo_FND_AAAI} (Figure 1(3)), having successfully used it for fake news detection. However, these works are restricted to in-domain settings and don't consider cross-domain evaluation. We propose the use of emotion-guided multi-task models for improved cross-domain fake news detection, experimentally proving its efficacy, and present an emotion-guided domain adaptive approach for improved cross-domain fake news detection by leveraging better feature alignment across domains due to the use of emotion labels (Figure 1(4)).
\begin{figure}[t!]
\centering
\includegraphics[width = 0.68\columnwidth]{Emo_DA_Flowchart.pdf}
\hfill
\caption{(1) Cross-domain texts not aligned. (2) Domain adaptation for improved alignment. (3) Emotion-guided classification. (4) Emotion-guided domain adaptation.}
\label{DA_Flowchart}
\end{figure}
\section{Proposed Methodology}
\subsection{Datasets, Emotion Annotation \& Preprocessing}
We use the FakeNewsAMT \& Celeb \citep{perez-rosas}, Politifact\footnotemark[1], and Gossipcop\footnotemark[2] datasets. We annotate them with the core emotions from Ekman's \citep{ekman} (6 emotions: \textit{Joy}, \textit{Surprise}, \textit{Anger}, \textit{Sadness}, \textit{Disgust}, \textit{Fear}) and Plutchik's \citep{plut} (8 emotions: \textit{Joy}, \textit{Surprise}, \textit{Trust}, \textit{Anger}, \textit{Anticipation}, \textit{Sadness}, \textit{Disgust}, \textit{Fear}) emotion theories. We use the Unison model \citep{unison} for annotating the datasets with emotion tags. During preprocessing, we convert text to lower case, remove punctuation, and decontract verb forms (eg. \textit{“I’d”} to \textit{“I would”}).
\footnotetext[1]{https://www.politifact.com/}
\footnotetext[2]{https://www.gossipcop.com/}
\begin{figure*}[t!]
\centering
\includegraphics[width = 0.8\textwidth]{Emo-FND-Flowchart.pdf}
\hfill
\caption{Graphical representation of our emotion-guided domain-adaptive framework for cross-domain fake news detection.}
\label{Flowchart}
\end{figure*}
\subsection{Emotion-guided Domain-adaptive Framework}
We propose the cumulative use of domain adaptation and emotion-guided feature extraction for cross-domain fake news detection. Our approach aims to improve the feature alignment between different domains using adversarial domain adaptation by leveraging the correlation between the emotion and the veracity of a text (as shown in Figure \ref{DA_Flowchart}(4)). Figure \ref{Flowchart} shows our proposed framework. We use an LSTM-based multi-task learning (MTL) feature extractor which is trained by the cumulative losses from fake news classifier, emotion classifier, and discriminator (aids in learning domain-invariant features). LSTM can be replaced with better feature extractors. We use it specifically for easier comparison to non-adapted emotion-guided and non-adapted single-task models. The domain classifier acts as the discriminator. Fake news classification loss, emotion classification loss, adversarial loss, and total loss are defined as:
\begin{equation}
\small
\scriptstyle L_{FND} \ = \ \min\limits_{\theta_{l},\theta_{f}} \sum_{i=1}^{n_{s}} L_{f}^i
\end{equation}
\begin{equation}
\small
\scriptstyle L_{emo} \ = \ \min\limits_{\theta_{l},\theta_{e}} \sum_{i=1}^{n_{s}} L_{es}^i \ + \ \sum_{j=1}^{n_{t}} L_{et}^j))
\end{equation}
\begin{equation}
\small
\scriptstyle L_{adv} \ = \ \min\limits_{\theta_d} (\max\limits_{\theta_l}( \sum_{i=1}^{n_{s}} L_{ds}^i \ + \ \sum_{j=1}^{n_{t}} L_{dt}^j))
\end{equation}
\begin{equation}
\small
\scriptstyle L_{Total} \ = \ (1 - \alpha - \beta) * L_{FND} \ + \ \alpha \ * \ (L_{adv}) \ + \ \beta \ * \ (L_{emo})
\end{equation}
where $n_s$ and $n_t$ are number of samples in source and target sets; $\theta_d$, $\theta_f$, $\theta_e$, and $\theta_l$ are parameters for discriminator, fake news classifier, emotion classifier, and LSTM feature extractor; $L_{d_s}$ and $L_{d_t}$ are binary crossentropy loss for source and target classification; $L_{es}$ and $L_{et}$ are crossentropy loss for emotion classification; $L_f$ is binary crossentropy loss for Fake News Classifier; $\alpha$ and $\beta$ are weight parameters in $L_{Total}$. We optimized $\alpha$ and $\beta$ for each setting.
\section{Experimental Results \& Discussion}
Each model used for evaluation was optimized on an in-domain validation set. Table \ref{FAMT-Celeb} illustrates our results proving the efficacy of using emotion-guided models in non-adapted cross-domain settings. Table \ref{DA} compares non-adaptive models, domain adaptive models, and our emotion-guided domain adaptive models in various settings. MTL (E) and MTL (P) refer to emotion-guided multi-task frameworks using Ekman's and Plutchik's emotions respectively. STL refers to single-task framework. DA refers to domain-adaptive framework with a discriminator. Non-DA refers to a non-adapted model. Some findings observed are:
\textbf{Emotions-guided non-adaptive multi-task models outperform their single-task counterparts in cross-domain settings}, as seen in Table \ref{FAMT-Celeb}, indicating improved extraction of features that are applicable across different datasets.
\textbf{Emotion-guided domain-adaptive models improve performance in cross-domain settings.} Table \ref{DA} shows the advantage of emotion-guided adversarial domain-adaptive models over their non-adaptive counterparts. This shows the scope for improved feature extraction even after adversarial adaptation, and emotion-guided models act as a solution.
\begin{table}[t!]
\centering
\large
\resizebox{\columnwidth}{!}{
\begin{tabular}{c|c|c|c|c}
\hline
\hline
\textbf{Source} & \textbf{Target} & \textbf{\makecell{Accuracy\\Non-DA STL}} & \textbf{\makecell{Accuracy\\Non-DA MTL(E)}} & \textbf{\makecell{Accuracy\\Non-DA MTL(P)}} \\\hline
FAMT & Celeb & 0.420 & 0.520 & \textbf{0.530}\\
\hline
Celeb & FAMT & 0.432 & 0.471 & \textbf{0.476}\\
\hline
\hline
\end{tabular}}
\caption{Cross-domain evaluation of non-adaptive models on FakeNewsAMT (FAMT) \& Celeb datasets. Emotion-guided models (MTL (E) and MTL (P)) outperform their corresponding STL models in cross-domain settings.}
\label{FAMT-Celeb}
\end{table}
\begin{table}[t!]
\centering
\large
\resizebox{\columnwidth}{!}{
\begin{tabular}{c|c|c|c|c|c}
\hline
\hline
\textbf{Source} & \textbf{Target} & \textbf{\makecell{Accuracy \\ Non-DA \\ STL }} & \textbf{\makecell{Accuracy \\ DA \\ STL }}& \textbf{\makecell{Accuracy \\ DA \\ MTL(E)}} & \textbf{\makecell{Accuracy \\ DA \\ MTL(P)}}\\\hline
FAMT & Celeb & 0.420 & 0.560 & 0.540 & \textbf{0.600}\\
\hline
Celeb & FAMT & 0.432 & 0.395 & 0.501 & \textbf{0.551}\\
\hline
Politi & Gossip & 0.527 & 0.585 & \textbf{0.698} & 0.671\\
\hline
Celeb & Gossip & 0.488 & 0.525 & 0.555 & \textbf{0.587}\\
\hline
FAMT & Gossip & 0.451 & 0.790 & \textbf{0.805} & 0.795\\
\hline
FAMT & Politi & 0.363 & 0.621 & \textbf{0.704} & 0.621\\
\hline
\hline
\end{tabular}}
\caption{Cross-domain evaluation of non-adaptive, adaptive and emotion-guided adaptive models on various datasets.}
\label{DA}
\end{table}
\fontsize{9pt}{10pt}\selectfont { | {'timestamp': '2022-12-01T02:18:10', 'yymm': '2211', 'arxiv_id': '2211.17108', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17108'} | arxiv |
\section{Introduction}
The paradigm of learning universal large-scale Transformer-based models has been recently transferred to speech from natural language processing~\cite{9585401,baevski2020wav2vec,chung2021w2v}.
Due to the high complexity of speech data, the preferred way of downstream task adaptation for such models is to keep pretrained weights frozen and fine-tune small task-specific heads~\cite{Yang2021SUPERBSP}, so it is important to use the model's hidden states in the most efficient way. A common approach is to use outputs of the last layer of the model, combining them via various pooling methods; but it has been shown that for some tasks, e.g. phoneme prediction in HuBERT or the analogy task in BERT, embeddings from lower and middle layers are more useful~\cite{vulic2020probing}. \emph{Topological data analysis} (TDA) is a recently proposed way to get more efficient data representations from frozen Transformer weights~\cite{kushnareva-etal-2021-artificial,judgements}. TDA features prove to be better suited for many downstream tasks, including artificial text detection and linguistic acceptability judgement. In particular, for ungrammatical sentence detection conventional sentence embeddings yield classification quality no better than random, while TDA has led to meaningful results. Inspired by these results, in this work we apply TDA to the HuBERT model in order to build more powerful speech representations.
TDA has already been applied to signals of various nature; previous attempts for speech used topological statistics of the audio signal waveform: persistent entropy for noise classification~\cite{RUCCO2017130} and emotion recognition~\cite{Gonzalez-Diaz}, detection of a periodic signal in noisy data~\cite{9747228} etc. However, TDA for Transformer-based models has so far been limited to NLP, processing attention maps for artificial text detection~\cite{kushnareva-etal-2021-artificial,https://doi.org/10.48550/arxiv.2206.15195} and linguistic acceptability~\cite{judgements} and word embeddings for dialogue term extraction~\cite{vukovic-etal-2022-dialogue} and constructing story trees~\cite{haghighatkhah-etal-2022-story}. Evolution of inner representations in neural networks has been studied with persistent Betti numbers~\cite{topologyofdeep} and recently introduced representation topology divergence (RTD)~\cite{barannikov2021representation}. In this work, we apply RTD in particular to intermediate embeddings and attention maps of a speech Transformer.
Another interesting area of TDA applications is the interpretation of pretrained Transformer models: it is known in NLP that different heads are sensitive to different phenomena~\cite{vulic2020probing}. With TDA techniques, we demonstrate the same effect for speech Transformers, finding heads that are best for solving specific downstream tasks, e.g. separating a given pair of emotions, a given pair of speakers, detecting speech generated by a specific TTS model, or representing spectral features of sound samples (bit rate, LPCC etc.). We also investigate the pattern structure of attention maps in HuBERT with pattern classification methods~\cite{Yang_attention} and demonstrate that our TDA-based approach is able to extract meaningful representation from heads with any pattern types.
\section{Methods}\label{sec:methods}
In this section, we describe our approach. We first introduce topological data analysis for weighted graphs and then define the features we propose to extract.
\noindent
\textbf{Graph homologies}.
Given a set of points in a high-dimen\-si\-onal space, TDA proposes ways to restore the underlying lower-dimensional manifold and study its topological properties.
If the set of points has a graph structure, the $d$-di\-men\-si\-onal manifold can be obtained in the form of a {\it simplicial complex}. Informally speaking, it is the structure obtained by replacing $k+1$-cliques in the graph by filled-in $k$-dimensional simplices for all $0\le k \le d$: $0$-dimensional simplices are vertices, $1$-dimensional are edges, for $k=2$ we get triangles, for $k=3$, tetrahedrons, and so on~\cite{Sunada2013}.
\emph{Homology groups} are key topological features for the classification of topological spaces~\cite{MR1867354}. Dimensions of the sequence of {homology groups} $H_k$, $k \ge 0$, are between of the main topological invariants. In the case of graph-like structures, $\dim H_0$ equals the number of connected components, $\dim H_1$ is the number of ``loops'', and $\dim H_k$ counts $k$-dimensional ``holes''.
\noindent
\textbf{Persistent homologies for weighted graphs and point clouds}.
We would like to apply TDA to sets of vectors in ${\mathbb R}^d$ (embeddings). Such a set (point cloud) can be viewed as a complete graph $G$ with edges weighted by any distance-like measure between vectors.
However, homology groups are only defined for unweighted graphs, so we make $G$ unweighted by thresholding, leaving only edges with weights lower than a given $\epsilon$; we denote the resulting graph by
$G_\epsilon$.
TDA can track the changes of topology across varying thresholds via \emph{persistent homology}. In this case, we build a family of graphs called a \emph{filtration}: an ordered set of graphs $\Gamma_\epsilon$ for a sequence of increasing $\epsilon$.
For $\epsilon$ below the minimal distance between vertices the graph has no edges; as $\epsilon$ increases new edges are added, ending in the complete graph; during this process, gradual changes of graph topology can be expressed in terms of ``birth'' or ``death'' of basic features. We begin with $|V|$ connected components (all of them are ``born''), and as $\epsilon$ increases, pairs of them are joined together (one component ``dies'').
``Birth'' and ``death'' moments can be represented with a diagram called the \emph{barcode}~\cite{barannikov2021canonical,barannikov2021representation}, whose horizontal axis is a sequence of thresholds $\epsilon$, and each horizontal bar corresponds to a single feature.
$H_0$-bars correspond to connected components; they start at the minimal distance between vertices and correspond to edges of the minimal spanning tree (MST).
$H_1$-bars correspond to simple cycles with more than $3$ vertices; an $H_1$-bar starts when a cycle appears and ends when it is broken into triangles by a new edge. We denote by $H_k^m(G)$ the average length of $H_k$-bars for a weighted graph or point cloud $G$.
\emph{Representation topology divergence} (RTD) measures the topological dissimilarity between two data representations, formalized as two weighted graphs $G^a$ and $G^b$ with a common set of vertices. Namely, we track how the topology of the graph $G^a_\epsilon \cap G^b_\epsilon$ changes as the filtration threshold $\epsilon$ increases. These changes are then summarized via a special kind of barcode, called the \emph{cross-barcode}, which reflects how much graphs $G^a$ and $G^b$ have in common on different scales. Our RTD feature is equal to the sum of bar lengths in this barcode. For a more general and formal definition, see~\cite{barannikov2021representation}. %
\noindent
\textbf{Features}.
We use three groups of features: algebraic features of attention matrices, topological features of attention matrices, and topological features of embeddings; for comparison, we also pool embeddings from all layers.
We count the number of features for the HuBERT-base model~\cite{9585401} that consists of $12$ layers with $12$ attention heads each and has embedding dimension $768$.
\defH_0^{m,\mathrm{sym}}{H_0^{m,\mathrm{sym}}}
\defH_0^{m,\mathrm{pc}}{H_0^{m,\mathrm{pc}}}
\emph{Algebraic features} include the sum of the upper triangular part of the $n \times n$ attention matrix (normalized by $n^2$), which is used as a measure of asymmetry, and mean values of its $3$ longest diagonals. This yields $4$ features per attention map, $576$ for the entire HuBERT model.
\emph{Topological features of attention matrices} include the $H_0^m$ feature for two graphs derived from each attention matrix $A_{\mathrm{attn}}$. $H_0^{m,\mathrm{sym}}$ is defined as $H_0^{m}$ for the graph with adjacency matrix $A^\prime = 1 - \max\left(A_{\mathrm{attn}}, A_{\mathrm{attn}}^\top\right)$, that is, the symmetrization of $A_{\mathrm{attn}}$ (cf.~\cite{kushnareva-etal-2021-artificial}). $H_0^{m,\mathrm{pc}}$ is defined as $H_0^{m}$ for the rows of $A_{\mathrm{attn}}$ considered as a point cloud with the $L_1$-distance. Here we have $2$ features per attention map, $288$ in total.
\emph{Topological features of embeddings}. Considering the $i$-th layer's embeddings $X^{(i)}$ as a point cloud with the $L_2$-distance, we calculate $3$ features for each layer: $H_0^m(X^{(i)})$, RTD between $X^{(i)}$ and the last layer's embeddings $X^{(L)}$, and RTD between $X^{(i)}$ and initial embeddings $X^{(0)}$. Besides, we add the same $3$ features for mel-frequency cepstral coefficients (MFCC), i.e., baseline speech embeddings in $\mathbb{R}^{13}$. This gives us $51$ features for the entire model.
\emph{Embeddings from all layers}.
An alternative approach, inspired by~\cite{Devlin2019BERTPO}, is to use pooled embeddings from each layer (not only the last) of the Transformer. We explored two pooling strategies: averaging over the timescale (common for speech Transformers) and taking only the first embedding as suggested in~\cite{Devlin2019BERTPO}. This yields $9216$ features in each case.
\section{Evaluation}\label{sec:results}
\noindent
\textbf{Datasets}.
We have used four standard datasets for speech and emotion recognition. \textbf{IEMOCAP}, introduced in~\cite{Busso2008IEMOCAPIE}, contains $\approx 12$ hours of audiovisual data, including video, speech, motion capture of faces, and text transcriptions; we use only speech samples from the ``Anger'', ``Sadness'', ``Happiness'', and ``Neutral'' classes ($4490$ samples), with 5-fold cross-validation, similar to~\cite{8639633,9747460}.
\textbf{CREMA-D}~\cite{6849440}
has $7442$ clips from $91$ actors who spoke $12$ different sentences in one of six basic emotions (anger, disgust, fear, happy, neutral, and sad); we perform multi-class classification with $6$ classes
and evaluate by averaging five splits with 70/15/15\% train/development/evaluation subsets.
\textbf{ASVSpoof}~\cite{9358099} was presented for the 3rd Automatic Speaker Verification Spoofing and Countermeasures Challenge; we used the standard split with $25380$ training, $24844$ development, and $71237$ evaluation samples and
performed classification into generated and bonafide labels, a standard task on ASVSpoof~\cite{Yu2018SpoofingDI}.
\textbf{VoxCeleb1}~\cite{nagrani17_interspeech} contains over $100$K utterances by $1251$ celebrities extracted from \emph{YouTube} videos; we performed binary classification between pairs of utterances from the same or different speakers, with $40000$ pairs in the training set, $8000$ in development, and $37720$ in the test set; in this dataset, we clip each utterance to the first $5$ seconds for all methods except embeddings from layers.
\noindent
\textbf{Models}.
We utilize the \emph{HuBERT Base} model~\cite{9585401} pretrained for automatic speech recognition on 960 hours of audio from the \emph{Librespeech} corpus~\cite{7178964}. We use HuBERT as a pretrained frozen instance, without fine-tuning or any other adjustment of the weights.
We use a linear layer trained over the pooled output of the Transformer as the baseline, which is consistent with the SUPERB leaderboard~\cite{Yang2021SUPERBSP}; we used the results for IEMOCAP and VoxCeleb1 published there and trained the baselines ourselves for CREMA-D and ASVSpoof.
As our approach, we train a logistic regression model with $L_1$-regularization over the set of features computed from HuBERT attention maps and/or embeddings. For automatic speaker verification (i.e., checking if two utterances are made by the same person) we compute the absolute value of elementwise differences between features of both utterances.
\begin{table}[!t]\centering\small
\setlength{\tabcolsep}{1pt}
\caption{Experimental results; $\star$~--- from SUPERB~\cite{Yang2021SUPERBSP}.}
\label{tbl:results}
\begin{tabular}{P{.25\linewidth}P{.18\linewidth}P{.18\linewidth}P{.18\linewidth}P{.18\linewidth}}\hline
Model & IEMOCAP & CREMA-D & ASVSpoof & VoxCeleb1 \\
& Acc $\uparrow$ & Acc $\uparrow$ & EER $\downarrow$ & EER $\downarrow$
\\ \hline
HuBERT (baseline) & $64.92^\star$ & $71.047$ {\footnotesize $\pm0.566$} & $6.649$ & \hspace{0.1cm} $\boldsymbol{5.11}^\star$ \\\hline
All layer embs, $1$st & $65.612$ {\footnotesize $\pm1.050$} & $71.320$ {\footnotesize $\pm0.479$} & $2.706$ & $42.701$ \\\hline
All layer embs, mean & $69.355$ {\footnotesize $\pm1.801$} & $76.260$ {\footnotesize $\pm1.148$} & $\boldsymbol{1.519}$ & \hspace{0.1cm} $6.513$ \\\hline
Attention features & $69.666$ {\footnotesize $\pm1.174$} & $79.200$ {\footnotesize $\pm1.240$} & $2.138$ & $30.326$ \\\hline
Attn. \& non-attn. feat. & $\boldsymbol{69.955}$ {\footnotesize $\pm\boldsymbol{0.972}$} & $\boldsymbol{80.155}$ {\footnotesize $\pm\boldsymbol{0.680}$} & $1.946$ & $26.443$\\\hline
\end{tabular}
\end{table}
\noindent
\textbf{Experimental results}.
Our results on all four datasets are shown in Table~\ref{tbl:results}; we report accuracy (Acc, in $\%$) and equal error rate (EER, in $\%$) for models trained on four different sets of features (see Section~\ref{sec:methods}):
\begin{inparaenum}[(1)]
\item \emph{Attention features} is a combination of {algebraic} and {topological features} calculated from attention maps;
\item \emph{Attn. \& non-attn. feat.} denotes a combination of algebraic and topological features of attention maps and topological features of embeddings; this combines all our TDA features for this task;
\item \emph{All layer embs, 1st} is the concatenation of first embeddings from all HuBERT layers;
\item \emph{All layer embs, mean} is the concatenation of all HuBERT embeddings with timescale averaging.
\end{inparaenum}
First, on all datasets averaging the embeddings is a much better strategy than taking just the first. One reason might be that NLP Transformers that often use the first embedding insert a fictional first token that ``represents'' the text as a whole, while HuBERT does not do this.
Second, adding non-attention features improves performance compared to just {attention} features, as expected since they contain more information, although for IEMOCAP the improvement is quite marginal.
Third, topological features give better results than embeddings from all layers on multi-class emotion recognition datasets (IEMOCAP, CREMA-D), while on two others the results are opposite.
On all datasets except VoxCeleb1 we achieve major improvements over the baseline (conventional usage of HuBERT). Poor performance of TDA features on VoxCeleb1 might be due to the fact that we used only short clips from each utterance due to high computational costs of TDA methods over large inputs. For CREMA-D, our model achieves a new state of the art result, improving the previous SOTA of 70.95\%~\cite{lerac2022} by over 9\%.
\section{TDA for Attention maps interpretation}
\noindent
\textbf{Restricted tasks}.
Inspired by recent works on attention interpretability in natural language processing~\cite{vulic2020probing}, we analyze the roles of individual attention heads in HuBERT.
Since their ``areas of expertise'' are much more narrow than general problems considered above, we use two restricted tasks: separation of individual models (one synthetic model vs real speech) and separation (binary classification) of two speakers.
\begin{figure*}[!t]\centering
\setlength{\tabcolsep}{5pt}
\begin{tabular}{p{.62\linewidth}p{.35\linewidth}}\centering
\includegraphics[height=0.17\linewidth]{pics/fig01.png}
\includegraphics[height=0.17\linewidth]{pics/fig02.png}
\includegraphics[height=0.17\linewidth]{pics/fig03.png}
&
\\[-15pt]
\caption{$H_0^{m,\mathrm{sym}}$ for the best heads for individual model separation. Blue: human speech, red: synthetic speech; dashed line: optimal classification.}\label{fig:sep_charts}
& \\
\includegraphics[width=\linewidth]{pics/fig2.png}
&
\multirow[t]{3}{*}{\includegraphics[width=\linewidth]{pics/fig3.png}}
\\[-.3cm]
\caption{Spectral features with strong correlations with $H_0^{m,\mathrm{pc}}$.}\label{fig:pcc_TDA_spectral}
&
\caption{Types of attention heads in HuBERT.}\label{fig:head_class}
\end{tabular}\vspace{-.5cm}
\end{figure*}
For individual model separation, we collected all samples produced by a given synthetic model and an equal amount of bonafide samples (real speech) randomly selected from train and validation sets. For each HuBERT attention head, we calculated the distributions of the $H_0^{m,\mathrm{sym}}$ feature for synthetic and real samples and ranked the heads by separation quality defined as
$\mathrm{SQ}_{1, 2} = \frac{\vert m_1 - m_2 \vert}{\max(\sigma_1, \sigma_2)}$, where $m_i$ are the means and $\sigma_i$ are the variances of classes. Fig.~\ref{fig:sep_charts} shows sample separations; it turns out that for every voice model there are several heads that separate them well ($\mathrm{SQ}>1$) and for most models there are heads that separate them very well ($\mathrm{SQ}>3$). The best heads are different and are usually situated in the middle-to-top layers of HuBERT. The worst results were obtained on the A19 model that was specially fine-tuned on evaluation data (best $\mathrm{SQ} = 1.45$). Separation quality of the threshold classifier for the best head varies from EER $0.03\%$ for the A14 model ($\mathrm{SQ} = 3.5$) to EER $36.5\%$ for the A19 model.
For individual speaker separation, a similar approach on ASVSpoof also shows that every pair of speakers has heads with good separation ($\mathrm{SQ}>1$), but this time there are no heads with $\mathrm{SQ}>3$. On the other hand, more general tasks are not handled well by individual heads; e.g. the best achieved separation of male vs female speakers has $\mathrm{SQ}=0.72$.
Full results for all experiments are presented at the companion website\footnote{{\scriptsize \url{https://topohubert.github.io/speech-topology-webpages}}}.
\noindent
\textbf{Attention maps and spectral features}.
Transformer-based models such as HuBERT do not implement spectral methods intentionally, but their attention mechanisms can extract a lot of various information, so we searched for potential similarities between TDA features and common spectral features. Following~\cite{borzi2022synthetic}, we extract the main spectral features for samples from the ASVSpoof dataset (real human speech only) and compute Pearson correlations between them and attention features. Fig.~\ref{fig:pcc_TDA_spectral} shows the results for $H_0^{m,\mathrm{pc}}$; some (but not all) spectral features have a ``counterpart'' in attention maps.
\noindent
\textbf{Categorizing attention maps in HuBERT}.
To show the relation between input speech specifics, HuBERT patterns, and topological features, we categorized HuBERT patterns
following~\cite{Yang_attention}, classifying attention heads into three categories: \emph{global}, \emph{vertical}, and \emph{diagonal} based on three metrics that evaluate their entropy ${\mathbb H}$ averaged over utterances $u$. For a head $h$ and its attention map $A^u\in{\mathbb R}^{d\times d}$, we compute its globalness $G_h = {\mathbb E}_u[\frac{1}{d}\sum_{i=1}^d{\mathbb H}(A^u_{i\ast})]$, verticality $V_h = {\mathbb E}_u[-{\mathbb H}(\frac{1}{d}\sum_{i=1}^dA^u_{i\ast})]$, and diagonality $D_h = {\mathbb E}_u[-\frac{1}{T^2}\sum_{i=1}^d\sum_{j=1}^d |i-j| \cdot A^u_{ij}]$, choosing the type based on the highest rank according to these metrics.
Fig.~\ref{fig:head_class} shows that heads in lower layers tend to be global, while higher layers are mostly vertical.
To show how these types interact with TDA features, we compute the accuracy based on $H_0^m$ for a subsample of IEMOCAP (angry vs. sad). Fig.~\ref{fig:bars} shows that, similar to~\cite{Yang_attention}, diagonal heads are more important for classification performance, but sometimes $H_0$-bars can extract valuable information even from global and vertical heads.
\begin{figure}[!t]\centering
\includegraphics[width=\linewidth]{pics/fig4.png}\vspace{-.3cm}
\caption{Accuracy of each head broken into pattern types.}\label{fig:bars}\vspace{-.2cm}
\end{figure}
\begin{figure}[!t]\centering
\includegraphics[width=\linewidth]{pics/fig51.png}
\includegraphics[width=\linewidth]{pics/fig52.png}\vspace{-.3cm}
\caption{Sample MSTs: angry (top) vs. sad (bottom).}\label{fig:trees}\vspace{-.2cm}
\end{figure}
Fig.~\ref{fig:trees} illustrates the patterns arising for various input classes. We took head $4$ from layer $2$ since it performs well in this classification. The middle and right columns of Fig.~\ref{fig:trees} show typical examples of ``angry'' and ``sad'' classes: original attention maps, symmetrized matrices and minimal spanning trees. A more concentrated and narrower diagonal pattern and less branching MST arise for the ``angry'' class (top). Interestingly, lower values of $H_0^m$ and clearer diagonal patterns correspond to loud utterances with lots of words per second and background dialog, while sparse and noisy patterns with larger $H_0^m$ values correspond to slow and lifeless speech from the ``sad'' class (see the companion website for examples).
\section{Conclusion}
In this work, we have applied topological data analysis to solving downstream tasks based on a pretrained HuBERT model and analysis and interpretation of individual attention heads. We have shown that TDA yields compact feature sets that give excellent results for tasks such as emotion recognition and speaker classification, including a new state of the art result on CREMA-D. We believe that topological analysis is an important and currently underexplored venue of research for large machine learning models such as Transformers, and propose TDA as a potentially fruitful direction of study.
| {'timestamp': '2022-12-05T02:13:10', 'yymm': '2211', 'arxiv_id': '2211.17223', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17223'} | arxiv |
\section{Introduction}
\label{sec:intro}
Over the past decade, end-to-end (E2E) supervised ASR has achieved outstanding improvements. These achievements keep pushing the limit of ASR performance in terms of word error rate (WER).
However, training the state-of-the-art model still heavily relies on a reasonable amount of annotated speech \cite{contextnet, gulati2020conformer, guo2021recent}. Unfortunately, labeled data is quite limited for most of the 7000 languages worldwide \cite{grenoble2011handbook}. The fast development of self-supervised learning (SSL) could mitigate the issue to some extent by leveraging unlabeled data. This paradigm first learns the speech representations from raw audio and then fine-tunes the model on limited transcribed speech data~\cite{wav2vec2, hubert,wavlm}, resulting in reducing the need for annotated speech.
However, as there is still a need for transcribed data for downstream model training, it is difficult to directly apply the system to all languages, especially those endangered languages that are extremely difficult to obtain data \cite{michaud2014towards, shi2020leveraging}. Unsupervised ASR could be one possible direction to solve the problem where the model can be trained with more accessible unpaired speech and text data.
Wav2vec-U is the state-of-the-art UASR framework. It utilizes both SSL (i.e., wav2vec2.0) and adversarial training for the UASR task\cite{wav2vecu}. The framework is shown working not only in English, where the wav2vec2.0 \cite{wav2vec2} is trained on but also in several other mainstream languages~\cite{librispeech, timit, mls}, as well as low-resource languages~\cite{swahili}. This finding reveals the possibility of utilizing unsupervised learning for more languages.
The authors of wav2vec-U have released their code in FAIRSEQ \cite{fairseq}, which greatly improves reproducibility. The implementation mainly consists of 3 steps: data preparation, generative adversarial training (GAN)~\cite{gan}, and iterative self-training~\cite{iter} followed by Kaldi LM-decoding~\cite{kaldi}.
Along with this reproducibility direction, we develop an unsupervised ASR toolkit named ESPnet Unsupervised ASR Open-source toolkit (EURO).
EURO complements the original FAIRSEQ implementation with more efficient multi-processing data preparation, flexible choices over different SSLs, and large numbers of ASR tasks through ESPnet~\cite{espnet}. EURO also integrates a weighted finite-state transducers (WFST) decoder using the k2~\cite{k2} toolkit for word-level recognition.
K2 is the updated version of the popular ASR toolkit Kaldi~\cite{kaldi}. It seamlessly integrates WFST and neural models implemented in PyTorch~\cite{pytorch} by supporting automatic differentiation for finite state automaton (FSA) and finite state transducer (FST), which are commonly used in ASR as a natural representation of the model's architecture ~\cite{wfst}. In EURO, k2 provides a compact WFST structured and efficient algorithm for decoding. With these advantages, EURO can considerably benefit the UASR study for the speech community, together with the FAIRSEQ UASR implementation.
This paper first introduces the toolkit and its features. Then, we conduct experiments that explore mainstream self-supervised models as speech feature extractors for UASR in different languages. Finally, we provide details of the hyperparameters of our experiments.
\section{Related works}
\label{sec:related works}
This section briefly compares the framework of EURO to wav2vec-U.
As summarized in Table~\ref{tab: comparison}, EURO provides more flexible choices of SSL model as the acoustic feature extractor by integrating with the S3PRL toolkit~\cite{s3prl}. With the comprehensive pipeline in the template, EURO enjoys a fast adoption to various datasets with a limited data preparation effort (less than 20 lines of code for a minimum runnable solution).
Meanwhile, all the data preparation stages in EURO are designed to enable computing in parallel, which greatly minimized the preprocessing time compared to wav2vec-U.
Besides of WFST decoder introduced in Sec.~\ref{sec:intro}, EURO provides a self-implemented decoder to eliminate external dependencies.
\begin{table}[t]
\caption{Framework comparison of EURO with wav2vec-U}
\vspace{1mm}
\centering
\resizebox{\columnwidth}{!}{
\begin{tabular}{ll|cc}
\toprule
Features & Details & Fairseq & EURO \\
\midrule
\multirow{1}{*}{Model} & Frontend & 1 SSL & 27 SSLs in \cite{s3prl} \\
\midrule
\multirow{3}{*}{Efficiency} & Prepare & single-thread & multi-process \\
& Train & multi-GPU & multi-GPU \\
& Decode & single-thread & multi-process \\
\midrule
\multirow{2}{*}{Decoding} & Prefix & by FlashLight \cite{kahn2022flashlight} & self-implemented \\
& WFST & by PyKaldi \cite{can2018pykaldi} & by k2\\
\bottomrule
\end{tabular}}
\label{tab: comparison}
\vspace{-10pt}
\end{table}
\section{Functionalities of EURO}
\label{sec:euro}
Fig.~\ref{fig:architecture} shows the architecture of EURO. Similar to other ESPnet tasks, EURO includes two major components: a Python library of network training/inference and a collection of recipes for running complete experiments for a number of datasets. The library is built upon PyTorch, while the recipes offer all-in-one style scripts that follow the data format style in Kaldi \cite{kaldi} and ESPnet \cite{espnet}. In addition, a WFST decoder is included to perform word-level recognition.
\begin{figure}[]
\begin{minipage}[b]{0.48\linewidth}
\centering
\centerline{\includegraphics[width=5cm]{structure_euro.pdf}}
\caption{Architecture of EURO}
\label{fig:architecture}
\end{minipage}
\hfill
\begin{minipage}[b]{0.48\linewidth}
\centering
\centerline{\includegraphics[width=3.5cm]{tree.png}}
\caption{Directory of EURO}
\label{fig:tree}
\end{minipage}
\vspace{-15pt}
\end{figure}
\subsection{Models}
\label{ssec: models}
As discussed in Sec.~\ref{sec:related works}, we follow previous works in using adversarial training to achieve UASR in EURO. To be specific, we extend the Wav2vec-U framework into our implementation.
Given a spoken utterance $\mathbf{X} \in \mathcal{D}_{\text{speech}}$, we first extract the speech representation by using a speech SSL model as the feature extractor $f(\cdot)$, resulting in a sequence of hidden representations $\mathbf{H}$. Then, the sequence $\mathbf{H}$ is passed into a preprocessor $m(\cdot)$ to form a segmented feature sequence $\mathbf{S}$, which is used for the generative adversarial network (GAN). The preprocessor $m(\cdot)$ includes three steps, including adjacent clustering pooling, principle component analysis (PCA) dimension reduction, and mean pooling. The adjacent clustering pooling utilizes the K-Means cluster IDs from the input feature $\mathbf{H}$ as guidance to merge the adjacent feature frames.
The network is mainly trained with a GAN-based loss and some auxiliary supporting losses. Given the segmented feature $\mathbf{S}$ and an unpaired phonemicized text sequence $\mathbf{Y}_{u} \in \mathcal{D}_{\text{text}}$, the framework includes a generator $\mathcal{G}$ and a discriminator $\mathcal{C}$ as the classic GAN framework. The generator $\mathcal{G}$, which serves as the ASR model, transcribes $\textbf{S}$ into a phoneme sequence $\mathbf{P}$ and the discriminator $\mathcal{C}$ tries to distinguish $\mathbf{Y}_u$ from the generated phoneme sequence $\mathbf{P}$. The GAN-based loss $\mathcal{L}_{\text{GAN}}$ is as follows:
\begin{equation}
\mathcal{L}_{\text{GAN}} = \min_{\mathcal{G}} \max_{\mathcal{C}} \mathbb{E}_{\mathbf{Y}_u} [\log \mathcal{C}(\mathbf{Y}_u)] - \mathbb{E}_{\mathbf{H}} [\log(1 - \mathcal{C(\mathcal{G}(\mathbf{S}))})].
\end{equation}
\noindent
To stabilize the training, three auxiliary losses are also proposed, including (a) a gradient penalty loss $\mathcal{L}_{\text{gp}}$ to sample the mixing rate of real and fake input for different steps:
\begin{equation}
\mathcal{L}_{\text{gp}} = \underset{\mathbf{S}, \mathbf{Y}_u, \alpha \sim U(0, 1)}{\mathbb{E}} [(||\nabla \mathcal{C}(\alpha \mathcal{G}(\mathbf{S}) + (1 - \alpha) \mathbf{Y}_u)|| - 1)^2],
\end{equation}
\noindent where $\alpha$ is the mixing weight sampled from a uniform distribution~\cite{gulrajani2017improved}. (b) a smoothness penalty to penalize inconsistent phoneme prediction between adjacent segments:
\begin{equation}
\mathcal{L}_{\text{sp}} = \underset{(p_n, p_{n+1}) \in \mathcal{G}(\mathbf{S})}{\sum} ||p_n - p_{n+1}||^2,
\end{equation}
\noindent where $p_n \in \mathbf{P}$ is the generator output distribution at the $n$'s segment. (c) a phoneme diversity loss to prevent the generator $\mathcal{G}$ from generating the same phoneme all the time:
\begin{equation}
\mathcal{L}_{\text{pd}} = -\sum_{n} \mathrm{Entropy}_{\mathcal{G}}(\mathcal{G}(\mathbf{S})),
\end{equation}
\noindent that is defined by the entropy of the average generator output distribution over every frame. The final loss is defined as
\begin{equation}
\mathcal{L} = \mathcal{L}_{\text{GAN}} + \lambda \mathcal{L}_{\text{gp}} + \gamma \mathcal{L}_{\text{sp}} + \eta \mathcal{L}_{\text{pd}},
\end{equation}
\noindent where $\lambda, \gamma, \eta$ are the weights for each term.
\subsection{Frontend}
\label{ssec:frontend}
One of the major benefits of EURO compared to wav2vec-U is its tight integration with S3PRL\footnote{\url{https://github.com/s3prl/s3prl}}, a toolkit for speech/audio self-supervised models, to avoid manually managing and switching between different SSL models.
S3PRL supports various SSL models as a general toolkit.
S3PRL has kept up-to-date with the latest SSL models in the speech and audio domain. Based on the integration with S3PRL, by simply changing \textbf{one line} of the configuration, EURO can utilize up to \textbf{27} speech and audio SSLs with more than \textbf{70} of their variants.\footnote{The number is recorded in Oct. 2022.}
\subsection{Decoding}
\label{ssec: decoding}
EURO offers two methods for decoding, including a self-implemented prefix beam search method and a graph-based search method using k2.
The prefix beam search utilizes the same decoding process as the CTC prefix decoding \cite{alex2008supervised, watanabe2017hybrid}, but without the blank symbols. Similar to other ESPnet tasks, the decoding can be integrated with phoneme-level language models (LM) from both n-gram LMs and neural LMs.
As briefly introduced in Sec.~\ref{sec:intro}, the graph-based search employs WFST for decoding. Different from the prefix beam search method, the graph-based search can utilize word-level LMs in the search graph, and can also be extended to word recognition. The search graph $T$ is a composition of three functional graphs: an alignment graph $H$, a lexicon graph $L$, and a grammar graph $G$:
\begin{equation}
T = H \circ L \circ G,
\end{equation}
where $\circ$ is WFST composition. Specifically, $H$ merges duplicated adjacent phones; $L$ maps sequences of phonemes to sequences of responding words; $G$ is an n-gram word LM. Fig.~\ref{fig:h} and Fig.~\ref{fig:lexicon} show an example of $H$ and $L$ implemented in k2. The lattice is generated during decoding~\cite{lattcie}, which represents the set of most likely hypothesis transcripts structured in a directed graph and can be easily integrated with neural LMs by performing lattice scoring~\cite{rnnlm_rescoring, parallel_rescoring}. The best hypothesis is obtained by searching the best path in the lattice.
\begin{figure}[]
\begin{minipage}[b]{0.48\linewidth}
\centering
\centerline{\includegraphics[width=4.0cm]{H.png}}
\caption{$H$ topology of phone set \{k, ae, t\}. It merges duplicated adjacent phones in the input sequence, e.g., (k, k, ae, t, t) $\rightarrow$ (k, ae, t). The arc with $-1$ is a special arc defined in k2 pointing to the final state.}
\label{fig:h}
\end{minipage}
\hfill
\begin{minipage}[b]{0.48\linewidth}
\centering
\centerline{\includegraphics[width=3.5cm]{L.png}}
\caption{$L$ topology of lexicon \{cat: k, ae, t; act: ae, k, t\} in k2. It maps the phone sequence to the corresponding word allowing optional silence token (sil) between words. e.g., (sil, k, ae, t, sil) $\rightarrow$ cat.}
\label{fig:lexicon}
\end{minipage}
\vspace{-15pt}
\end{figure}
\subsection{Recipes for reproducible experiments}
\label{ssec: recipes}
\subsubsection{Directory structure}
EURO follows the unified directory organization of ESPnet as shown in Fig.~\ref{fig:tree}. Similar to other tasks (e.g., ASR, speech translation (ST)), the recipe \texttt{usar.sh} and its related bash scripts are stored under \texttt{egs2/TEMPLATE/uasr/}.
The model \texttt{espnet\_model.py} and task \texttt{uasr.py} are stored at \texttt{espnet2/uasr/} and \\ \texttt{espnet2/tasks/}, respectively. Decoding scripts \\ \texttt{uasr\_inference.py} and
\texttt{uasr\_inference\_k2.py} are placed under \texttt{espnet2/bin/}.
\subsubsection{Recipe flow}
The recipe in EURO follows the ESPnet2 style of task, which provides the template \texttt{uasr.sh}. The stages are defined as follows:
\noindent \textit{\textbf{Stage 1-5}: Data preparation.} The initial data format starts from the Kaldi style \cite{kaldi}, but the \texttt{text} for transcription is supposed to be unpaired with the speech data. Then, we offer two optional data preprocessing stages: speed perturbation and voice activity detection (VAD). The VAD results can be applied in silence removal as it is shown to be important for some speech corpus for wav2vec-U. After the preprocessing, all speech data is converted into a standard format, by resampling, segmentation, silence removal, and dumping from pipe-style formats. \\
\noindent \textit{\textbf{Stage 6-7}: Text tokenization and token list generation.} Texts are converted to phoneme tokens using the graphemes to phonemes toolkit g2p-en. Tokens are collected from the training text and formed into a corresponding token list for modeling. For UASR, the unpaired text~$\mathbf{Y}_u$ is fed into training in a random fashion. For efficiency purposes, we initialize a randomized text loader with the tokenized text, which is especially useful for large text data. \\
\noindent \textit{\textbf{Stage 8-11}: LM preparation.} These stages train and evaluate LMs based on the unpaired text $\mathcal{D}_{\text{text}}$. The LMs include both neural-based LMs and N-gram LM. \\
\noindent \textit{\textbf{Stage 12}: WFST graph construction.} This stage creates the WFST decoding graph for the k2 decoder.\\
\noindent \textit{\textbf{Stage 13}: UASR statistics collection.} In this stage, EURO collects necessary input statistics for batching and mean-variance normalization (MVN). Optionally, the feature from frontends (i.e., S3PRL module in EURO) can be extracted at the stage to support efficient training in further stages. \\
\noindent \textit{\textbf{Stage 14}: UASR feature preprocessing.} This stage applies the preprocessing steps discussed in Sec.~\ref{ssec: models}, including adjacent clustering pooling, PCA, and mean pooling. The resulting segments are used for UASR training. \\
\noindent \textit{\textbf{Stage 15}: UASR training.} This stage conducts the adversarial training as discussed in Sec.~\ref{ssec: models}. \\
\noindent \textit{\textbf{Stage 16}: UASR decoding.} EURO has two decoding schemes as introduced in Sec.~\ref{ssec: decoding}. This stage supports both decoding methods. \\
\noindent \textit{\textbf{Stage 17}: UASR evaluation.} The evaluation in this stage utilizes the NIST \textit{sclite} toolkit to compute the phone error rate (PER) or the word error rate (if applicable). \\
\noindent \textit{\textbf{Stage 18-20}: Model packing and uploading.} This stage automatically packs the trained model checkpoint for easier sharing of the pre-trained model. EURO also supports uploading models to Huggingface for model sharing.
\begin{table*}[t]
\centering
\caption{PER ($\%$) on TIMIT of different SSL models. SE-ODM~\cite{sedom} only reports results on the test set. The best result is highlighted in \textbf{bold}. Experimental details can be found in Sec.~\ref{ssec: exp details}.}
\vspace{1mm}
\label{tab: timit}
\begin{tabular}{@{\extracolsep{4pt}}llllllll@{}}
\hline
\multirow{2}{*}{Framework} & \multirow{2}{*}{SSL model} & \multirow{2}{*}{Layer} & \multirow{2}{*}{LM} & \multicolumn{2}{c}{TIMIT} \\ \cline{5-6}
& & & & dev & test \\ \hline
SE-ODM \cite{sedom} & - & - & 5-gram & - & 36.5 \\ \hline
wav2vec-U \cite{wav2vecu} & wav2vec 2.0 & 15 & 4-gram & 17.0 & 17.8 \\ \hline
\multirow{3}{*}{EURO} & wav2vec 2.0 & 15 & 4-gram & 18.5 & 19.8 \\
& HuBERT & 15 & 4-gram & 14.9 & 16.4 \\
& WavLM & 14 & 4-gram & \textbf{14.3} & \textbf{14.6} \\
\hline
\end{tabular}
\end{table*}
\begin{table*}[t]
\centering
\caption{PER/WER ($\%$) on Librispeech of different SSL models. PER is from the prefix beam search decoder and WER is from the k2 WFST decoder. The best result is highlighted in \textbf{bold}. Experimental details can be found in Sec.~\ref{ssec: exp details}.}
\vspace{1mm}
\label{tab: librispeech}
\begin{tabular}{@{\extracolsep{4pt}}llllllllll@{}}
\hline
\multirow{2}{*}{Framework} & \multirow{2}{*}{SSL model} & \multirow{2}{*}{Layer} & \multirow{2}{*}{LM} & \multicolumn{4}{c}{Librispeech} \\ \cline{5-8}
& & & & dev clean & dev other & test clean &test other \\ \hline
wav2vec-U & wav2vec 2.0 & 15 & 4-gram & 18.9/31.7 & 22.4/35.4 & 18.4/30.7 & 23.0/36.1 \\ \hline
\multirow{3}{*}{EURO} & wav2vec 2.0 & 15 & 4-gram & 16.2/26.5 & \textbf{19.3}/29.8 & 15.7/25.6 & \textbf{19.8}/30.7 \\
& HuBERT & 15 & 4-gram & \textbf{15.2}/23.1 & 20.7/\textbf{29.3} & \textbf{15.1}/\textbf{22.8} & 21.1/\textbf{29.8} \\
& WavLM & 15 & 4-gram & 18.0/\textbf{23.0} & 21.2/31.0 & 16.6/22.9 & 21.4/31.0 \\
\hline
\end{tabular}
\end{table*}
\section{Experiments}
\label{sec:experiments}
\vspace{-3mm}
\subsection{Datasets}
\noindent \textbf{TIMIT}: The TIMIT dataset is a popular benchmark for the UASR task \cite{timit}. It contains 6300 sentences (5.4 hours) of reading speech. All sentences are manually transcribed to phonemes with time alignment. We use the standard split of the train (3696 sentences), dev (400 sentences), and test (192 sentences) sets for our experiments.\\
\noindent \textbf{Librispeech}: The LibriSpeech dataset is a common benchmark for the ASR task~\cite{librispeech}. It contains 960 hours of reading speech automatically derived from the audiobooks of LibriVox. This corpus is split into 3 training sets (100 and 360 hours of clean speech, and 500 hours of other speech), 2 dev sets (each has 5 hours), and test sets (each has 5 hours).
\vspace{-2mm}
\subsection{SSL models}
\vspace{-2mm}
We explore three SSL models for UASR in EURO, wav2vec 2.0 (wav2vec2-large-ll60k), HuBERT (hubert-large-ll60k), and WavLM (wavlm-large).\footnote{Corresponding models can be found in \url{https://s3prl.github.io/s3prl/tutorial/upstream_collection.html}} The three models have the same architecture that consists of 24 layers of Transformer encoders~\cite{transformer} with a similar number of parameters. Among them, wav2vec 2.0 and HuBERT are pre-trained on 60,000 hours of Libri-Light. In addition to Libri-Light~\cite{kahn2020libri}, Wavlm uses 10,000 hours of Gigaspeech~\cite{gigaspeech} and 24,000 hours of VoxPopuli~\cite{vox} for pre-training.
\vspace{-2mm}
\subsection{Comparison of SSL models}
\noindent \textbf{TIMIT}: We test EURO on TIMIT to confirm that the toolkit works properly. We use the text from the same training set for unsupervised training. To make it comparable with wav2vec-U, we adopt the same setup for EURO wav2vec 2.0. More specifically, we use the model wav2vec2-large-ll60k and the features are extracted from the \nth{15} layer of the model. For Hubert and WavLM, we explore the performance of features from different layers and report the best PER results.
Table~\ref{tab: timit} shows the results on TIMIT. Wav2vec-U serves as the baseline and achieves 17.0\% and 17.8\% PER on dev and test sets, respectively.
EURO with the same setup gets 18.5\% and 19.8\% PER on the dev and test set which is slightly worse than wav2vec-U. While our model is not heavily tuned under this setup, the results are comparable with wav2vec-U.
For Hubert (hubert-large-ll60k), EURO performs best on features extracted from the \nth{15} layer. The PERs on the dev set and test set are 14.9\% and 16.4\%. Compared with the wav2vec-U baseline and EURO wav2vec 2.0, it provides a relative improvement of 10\% and 20\%, respectively.
WavLM (wavlm-large) provides further improvement. The model trained using features extracted from \nth{14} layer of WavLM achieves 17\% relative improvement compared with baseline and 25\% relative improvement compared with EURO wav2vec 2.0 in terms of PER. It reduces the PER to 14.3\% on the dev set and 14.6\% on the test set.\\
\\
\noindent \textbf{Librispeech}: For Librispeech, because of the limitation of computing resources, we use 100 hours of clean speech for UASR training. Unlike TIMIT, we use the text from the whole training set (960 hours) excluding the overlap part with the training speech. The text is phonemicized using G2P phonemizer~\cite{g2p}. In total, around 25m sentences are used for UASR training.
We measure both the PER and WER of UASR systems using different SSL models for this dataset. Wav2vec-U uses a sophisticated decoder to convert phoneme sequences to word sequences and it may not be easily applied to other datasets. To make a fair comparison, we train the wav2vec-U model using the same data and load the model into EURO. We use the same prefix beam search decoder for PER and k2 WFST decoder for WER.
Table~\ref{tab: librispeech} show the results of LibriSpeech's standard dev and test sets. All EURO models outperform the baseline wav2vec-U. For phone recognition, the HuBERT model performs best on clean sets. It achieves PER 15.2 on the dev clean set and PER 15.1 on the test clean set. Wav2vec 2.0 performs best on more difficult sets. It achieves PER 19.3 and 19.8 on dev other and test other sets, respectively. For word recognition, Hubert gets the best WER of 29.3, 22.8, and 29.8 on dev other, test clean and test other sets. WavLM performs best on dev clean and achieves 23.0 WER which is slightly better than HuBERT.
\subsection{Experimental details}
\label{ssec: exp details}
For training, we set $\lambda=1.5$, $\gamma=0.5$, and $\eta=2.0$ for TIMIT and $\lambda=2.0, \gamma=1.0, \eta=4.0$ for LibriSpeech datasets.
For (phone-level) prefix beam search decoding, we set $\text{beam size}=2$ and tunes the weight n-gram language model in $\left[ 0,0.9 \right]$. For (word-level) graph-based WFST decoding, we set $\text{search beam size}=30$, $\text{output beam size}=15$, $\text{min active states}=14,000$, and $\text{max active stats}=56,000$. More details can be found in the configuration file under \texttt{egs2/TEMPLATE/uasr/conf/}.
\section{Conclusions}
\label{sec:conclusions}
This work introduces a new toolkit for unsupervised ASR, namely EURO. The toolkit is developed as an open platform for the research field of unsupervised ASR. The current architecture of EURO is based on the Wav2vec-U framework but greatly improves the reproducibility with flexible frontends of almost 30 SSL models and a faster preparation/inference compared to its original implementation in FAIRSEQ. By integrating with k2, EURO provides a WFST decoder for word recognition. Our experiments on TIMIT and LibriSpeech show that we could get comparable performances with wav2vec-U in FAIRSEQ but even better results with Hubert and WavLM as new frontends.
\section{Acknowledgement}
\label{sec:acknowledgement}
Part of the work presented here was carried out during the 2022 Jelinek Memorial Summer Workshop on Speech and Language Technologies at Johns Hopkins University, which was supported with unrestricted gifts from Amazon, Microsoft, and Google. This work used the Bridges system ~\cite{nystrom2015bridges}, which is supported by NSF award number ACI-1445606, at the Pittsburgh Supercomputing Center (PSC).
\clearpage
\bibliographystyle{IEEEbib}
| {'timestamp': '2022-12-02T02:15:19', 'yymm': '2211', 'arxiv_id': '2211.17196', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17196'} | arxiv |
\section{Introduction}
\noindent In the video game realm, the main goal of Reinforcement Learning (RL) has usually been to achieve superhuman performances \cite{AlphaZero} \cite{AlphaStar}.
Another interesting application for RL is the pursuit of human behavior \cite{Strong_human_like_kl_regu_search}, in order to perform automated game testing.
These automated tests can have varying objectives: find the most resource consuming assets of the game or flag possible unintended exploits in the gameplay. In our case we wish to perform automated tests in order to help assess more accurately the difficulty of the game.
The results of these automated tests are most useful to the designers during the production phase of the game, during which there is very little human data available (only the occasional human play-tests). Moreover, this data is rarely in the form of full trajectories but rather in the form of \textit{summary data}, i.e. in the form of a few key metrics, or \textit{play-modes},
that are of most interest to the designers (e.g. number of shots fired during a game).
Indeed, tracking and storing full players' paths (state-action tuples) is a big constraint to put on developers, especially in the early stages of the production, as it involves issues of bandwidth and computational resources.
Whereas summary data is cheaper to acquire and to store.
Furthermore, the pipeline for tracking and storing summary data is usually the same during the production of the game, as it is post launch.
In short, logging summary data is cheaper, easier to implement and is most likely already being done by the developers.
In this work, the available human data is assumed to be very limited and in a summarized format: no full trajectories, only a few key metrics, so as to fit with the constraints of game production.
To assess the difficulty of a game, distinguishing between performance (i.e. success) and play-style is important: a game can be perceived hard for a subset of the players because of their style of play, not because of the game itself. So the performances relative to the play-style should be reported to the designers, as well as the overall difficulty, so as to help them make informed decisions.
A play-style is measured using key metrics which capture different aspects of the gameplay.
We present here a Configurable Agent with Relative Metrics as Input (\textit{CARMI}) agent, which aims at generating a continuum of play-styles, fitting with the players distribution, making the sampling of human-like play-styles straightforward, even on levels previously unseen by the agent and the players.
This agent is configurable with respect to the metrics used to define the play-styles and is obtained through a single RL training loop.
The definition and measure of a play-style is done on summary data (e.g. the number of shots fired and the number of stabs made with a knife during a game). However, here it is normalized level by level, using the players distribution. Therefore the play-styles are defined not as absolute but as relative to the players population, making them independent from the levels and their designs.
Take for example a play-style characterized by "a high use of a riffle over a knife". Instead of measuring "high use" as "X times during a game" it would be measured "X times more than the other players", making the definition of this play-style applicable no matter the level.
The agent learns a policy conditioned to matching a desired play-style. This is done by giving the desired relative summary data $z$ as input to the agent, and building a reward function that orients the agent towards matching this $z$.
It is the main contribution of this work: training an agent conditioned by a play-style which is defined in relationship to human play-styles distribution. This means that the agent learns the distribution of the players in the play-style space solely through the reward function.
Proceeding this way produces two results.
First, it ensures that the agent is able to cover at least the same space as the human players in the space of the play-styles.
Second, the independence between the play-styles and the level design allows the agent to easily generalize the play-styles to newly unseen levels.
This is due to the fact that the agent has learnt to associate any value of $z$ to a behavior, no matter the level, which allows better generalization.
The new direction presented by this paper results from the capacity to generalize human summary data to new levels using few human data, to better fit with the constraint of the industry.
We can therefore use this agent to play-test new levels, using play-styles defined from human data collected on previous levels. And because the agent is conditioned using a very interpretable input $z$, it could also be used for automated play-tests using designers' hand-made play-styles, since each dimension of $z$ corresponds to a specific metric.
In this paper we first give a more formal definition of play-styles as well as the existing methods that aim at learning various personas and those aimed at modeling human behavior.
We then introduce the environment: a turn based strategic shooter. And finally compare our results with the existing method CARI \cite{CARI_paper}.
\section{Background}
\subsection{Play-Styles As A Combination Of Play-Modes}
\citeauthor{Canossa2009PatternsOP} adapt the "persona" framework introduced by
\cite{CooperPersonas} in the field of Human Computer Interaction.
\citeauthor{PersonasInGame2008} make the distinction between play-mode, play-style and play-persona. It is a distinction based on the level of data aggregation.
A play-mode is one or a few discrete metrics, within the same overall group or type of metrics.
From there, play-style is defined as "a set of composite play-modes".
And finally play-personas represent the "larger-order patterns that can be defined when a player uses one or more play-styles consistently". The focus of this paper is on the simulation of human-like play-styles through the generation of behaviors yielding play-modes similar to players'.
\subsection{Automated Play-Testing}
Recent work as been done to develop automated play-tests using machine learning (ML) approaches, more specifically using agents trained through (Deep) RL.
There are two main categories of test: technical tests (e.g. frame rate, bugs) and gameplay tests (e.g. difficulty assessment, game consumption analysis). Our approach focuses on difficulty assessment for the experiments while taking into account the diversity of approaches and resulting play-styles.
RL can be use to improve game testing \cite{Automated_game_testing_using_DRL} in order to find unintended exploits in the video game.
It can also be used to measure what is achievable in the game. For example, \cite{CCPT} train an agent to uncover what is possible in the environment, but should not be, in order to flag bugs and glitches for the designers to fix.
\citeauthor{smartnav} trained an agent to navigate complex 3D environments, which can be used for Non Playable Character (NPC) development with complex navigational skills, or in order to measure the feasibility of procedurally generated goals.
However, in this work we are interested in training an agent that can inform us about the difficulty of the game. Therefore, this agent must produce diverse human-like play-style in order to provide meaningful feedback.
\subsection{Diverse Human-Like Behavior} \label{sec:Human_Like_Behavior}
To approximate human behavior, Inverse Reinforcement Learning (IRL) \cite{ng2000algorithms} can potentially be used.
The 2 main drawbacks of IRL methods are the homogeneity assumption in the trajectories and the quantity of the data necessary for such approaches to yield convincing results.
In our case, neither full trajectories nor large dataset are available.
\citeauthor{IRL_SD} developed an approach to perform IRL using solely summary data to alleviate this problem. However they assume homogeneity in the data, in the sense that all the data comes from the same expert.
This homogeneity assumption goes against the idea of generating varying, and therefore heterogeneous, play-styles.
There are a few possibilities to insert heterogeneous play-styles into an agent.
To that effect, \citeauthor{holmgard2018automated} have demonstrated that shaping the reward (\citeyear{holmgard2014Generative}), fitness (\citeyear{holmgard2014Evolving}) or utility function (\citeyear{holmgard2018automated}) produces variety in the style of play of the agents.
Moreover they showcased that archetypes (i.e. stereotypical play-styles) can be a good low-cost, low-fidelity approach to automated play-test.
Because each archetype requires its own training and its own reward function, they limit themselves to only 4 archetypes.
\citeauthor{CARI_paper} (\citeyear{CARI_paper}) solved this issue by training a \textit{CARI} agent where the coefficients of the reward function are given to the RL agent as input. Concretely, they train a policy $\pi(a|s,w)$ where $w$ are the coefficients of the reward function: $r = w \cdot \theta$, where $\theta$ represents all the events which induce a reward signal.
Additionally one must define $W$, the intervals within which the $w$ will be sampled during the training.
Thus creating a continuum of available play-styles to sample from at inference time (simply using varied $w$). This approach allows to train one single model rather than multiple ones. It moves the problem of selecting the proper $w$ to generate the desired play-style after the training rather than before, it does not however remove it.
The CARI approach suffers from two main issues. The first is the absence of guarantee that the space of generated playstyles covers well enough the set of human play-styles. The second is that even if the CARI generated play-styles do include the players' play-styles, there is no straightforward way to know which reward coefficients $w$ to select in order to simulate the human-like play-styles. This is due to the fact that the process still relies on finding a good combination of reward coefficients that will hopefully generate the desired play-modes.
Both these issues are solved here by directly giving the target values of the desired play-modes as the goal to the agent as part of its input state: replacing $w$ by a $z$ which encodes a desired play-style. These objectives are encoded and sampled using the distribution of the play-mode over the players population.
This agent still allows access to a wide variety of play-styles but also ensure that the generated play-styles do in fact encompass the humans' ones.
However, there is no guarantee that the players' and the agent's full trajectories look the same, for that we would need full human trajectories to train on, which we assume to not have access to during the the production of the game. We are not claiming to generate human-like behaviors, but human-like play-styles, as they are measured : using summary data. The goal is to produce summary data that are player-like enough to take well informed decisions, on new levels.
\subsection{Goal-Conditioned Reinforcement Learning}
Goal-conditioned RL has been used in video game testing in different ways. For example \cite{constraint_RL}, frame their problem as constrained RL, to create an agent with the desired behavior. Their approach relies on a main goal to achieve and several constraints to fulfill, and are automatically weighed throughout training. This approach does not allow the emergence of heterogeneous play-styles, necessary in our case, since the play-style is the goal to achieve, not a constraint to be met.
Goal-conditioned RL has been extensively studied \cite{goal_cond_rl_old} \cite{UVFA_goal_cond_value_function} \cite{Goal_RL_subgoals}. The framework is usually in the form of a policy which given a state $s$ and a goal $g$, predicts actions which lead to the goal. The goal is usually a certain state of interest in the environment (e.g. a destination). In our case the goal is the encoded play-style $z$, relative to the players distribution. It is not a state in the environment, but a behavior to adopt.
Moreover, this behavior is not absolute, but relative to the players, and should be matched on different levels. The only information about the distribution of the players given to then agent is thought the reward feedback.
\section{Proposition}
Our goal is to learn a play-style conditioned policy which generates trajectories yielding summary data as close as possible to a given objective. This policy is then used to emulate human-like play-styles, on previously unseen levels.
\subsection{Notations}
In our environment, let $\tau = (s_0, a_1, s_1, ..., a_T, s_T)$ denote the trajectory of a full episode.
We introduce the summarizing function $ \psi $ which takes as input a trajectory and returns a set of $M$ summary data (e.g. number of shots and stabs made): $\psi(\tau) \in \mathbf{R}^M$.
In this work, we assume to have access to the summary data of $N_P$ players over $N_L$ levels of the game: $\{ \psi(\tau_{l,p}) \}_{l \in [1:N_L], p \in [1:N_P]}$. Additionally, $\mu_l$ and $\sigma_l$ represent the mean and standard deviation of the players summary data on level $l$, such that $\psi(\tau_{l,.}) \sim \mathcal{N}(\mu_{l}, \sigma_{l})$.
We also note $\psi_l(\tau) := \frac{\psi(\tau) -\mu_l}{\sigma_l}$, the summary data on level $l$, normalized by the players distribution on that level (assuming a Gaussian distribution).
We introduce the policy $\pi_z (a|s) := \pi(a|s,z) $, with $a$ the action, $s$ the state and $z$ some additional information (e.g. a play-style to emulate in our case or the reward coefficients in CARI) given to the agent, with $z \sim \mathcal{P}_z $, here we assume that $\mathcal{P}_z = \mathcal{N}(0,1) $. In our case we wish for $z$ to represent $\psi_l(\tau)$.
Our goal is for $\pi_z$ to generate $\tau_{\pi_z}$ yielding $\psi_l(\tau_{\pi_z})$ as close as possible to $z$.
The reward function reflects this objective by being proportional to $-d_t := -\Delta(\psi_l(\tau_{\pi_z, t}); z)$, the current distance between the goal $z$ and the agent. Where $\tau_{\pi_z, t}$ is the trajectory generated by $\pi_z$ until time-step $t$.
By formulating the problem this way, we can then use any RL algorithm to solve this MDP and generate an agent with a policy $\pi \in argmin_\pi
\{\mathbf{E}_l [\mathbf{E}_z [ \mathbf{E}_{\tau \sim \pi_z} [ \psi_l(\tau)-z ]]] \}$.
\subsection{Relative Metrics As Input}
The way the metrics are encoded, when given to the agent as goals, is key here.
Instead of aligning $z$ (the agent's goal) to the absolute metrics values $\psi(\tau)$, it is aligned to the relative ones, w.r.t. the players distribution on that particular level: $\psi_l(\tau)$.
It moves the issue of playing with a given play-style from a hard to define absolute point of view, into an easier relative one.
It is difficult to define what can be considered a \textit{high} frequency of shots, it is however easier to say if a given frequency of shots is among the \textit{highest} over the players population.
Additionally, it improves greatly the usefulness of the agent at inference time, especially on new previously unseen levels.
Giving the absolute metrics as the objective (i.e. $z \approx \psi(\tau)$) would have the agent learn how to achieve that specific goal, no matter the level design. During inference the agent would then still generate these exact metrics values, if the level allows it. This would render the agent quite useless for any automated testing procedure: on a new level the agent is tasked with shooting twice and it does it. We did not learn much, except that shooting twice on this new level is possible.
Instead giving the normalized metrics, relative to the players, as the objective (i.e. $z \approx \psi_l(\tau)$) means that the agent needs to learn to adapt its behavior to fit with the portion of the players represented by $z$.
Since we assumed the data to be normally distributed and given than $P(X \sim \mathcal{N}(0,1) < -1.96) = 0.025$, at inference time giving the target value $z = -1.96$ to the agent means shooting as much as the $2.5\%$ of players that shoot the least.
After playing one level with this $z$, the absolute number of shots done by the agent is then reported to the designers, which would correspond to the number of shots done by this portion of the players, had they played that new level.
\subsection{Configurable Agent}
The more complex the game the more numerous the play-styles, thus the more numerous the number of models to train. In order to solve this issue a single model is trained, much like in \cite{CARI_paper}.
The objective $z$, which correspond to the normalized metrics $\psi_l(\tau)$ are given inputs to the model.
Proceeding this way makes the agent configurable: the play-style we wish the agent to adopt can be chosen after training, at inference time. We only need to train a single model for all play-styles.
At the beginning of each episode a new $z$ is drawn and given as input to the agent. The agent has then the objective of matching this value by the end of the episode.
The reward function used to this end is defined as
$r_t = d_{t-1}-d_t + [-d_t ]_{t=T}$.
If the agent does an action bringing it closer to its objective it will receive a positive reward corresponding to how much closer it got, much like in a navigation problem.
The same applies if the chosen action moves it away from the objective. The objective of the agent is to end the episode as close as possible to $z$.
This is why at the end of the episode the agent perceives a negative signal equal to how much distance to the target is left. Moreover, $\sum_{t=1}^T r_t = (d_0 - d_T) - d_T$: the cumulative reward on the whole episode is equal to the distance "\textit{travelled}" towards the objective minus the distance left at the end.
\section{Experimental Setup}
\subsection{Game Environment}
The game environment used in this work is the same as in \cite{CARI_paper}. This environment presents a few advantages. It is complex enough to be able to have different play-styles and some of the challenges that come with training in a complex video game, but simple enough to have moderate computation requirements. Moreover it is developed using Unity's ML-Agents \cite{Unity_Ml_agent}, which allows to control the agent either with the Python programming language (for the RL aspect) or with a controller (for the human player aspect).
\begin{figure}[]
\centerline{\includegraphics[width=\linewidth]{proto_screenshot.PNG}}
\caption{Screenshot of the Video Game}
\label{fig:Capture_proto}
\end{figure}
This video game environment is a discrete, turn-based, shooter-strategic, see Fig. \ref{fig:Capture_proto}.
In this video game, two teams fight to the death on a 3D cell based board.
This game is inspired in its gameplay elements from the "Mario + Rabbids" video game, developed by Ubisoft.
The movements can be done in any directions toward an empty cell.
Some portals (the circles in Fig. \ref{fig:Capture_proto}) are spawned across the board to allow characters to take short-cuts.
In addition the board also consist of a series of covers behind which the characters can hide to avoid getting shot at.
A team of 3 heroes (in blue), controlled by an agent (or a human, during a play-test), face a team of a varying number of enemies (up to 7, in red) controlled by hand-crafted behavior trees, designed by us like any NPC would be in most video games, for a maximum of 10 turns.
Every hero character has the capacity to move, shoot and stab (i.e. melee attack). They are all defined by a set of basic statistics: their health, their range of movement and of fire and their damages. Additionally, each hero a \textit{super capacity}. One has the power to heal nearby allies, another has the ability to apply an empowerment to nearby allies thereby increasing the damage caused by their attacks for one turn and the third hero can apply a shield that will block one attack. Each of these \textit{super capacity} has a two turns cool-down.
It is a turn-based game, meaning that when one of the team is playing, the other one is frozen in place. A full turn is not a single time-step, rather a full turn is many time-steps.
So for example during one turn, the agent (controlling the whole hero team) can move around with hero number one, stab and shoot an enemy with the same hero, then shoot another enemy with hero number 3, and use the shield of hero number 2 before skipping the rest of its turn, effectively starting the enemy's turn. Each character has a maximum of one shot and one stab per turn. Once a character has shot it cannot move for the rest of the turn.
The game ends once one of the two teams has been fully destroyed or if the game reaches the 10 turns limit, in which case the game is considered to be a draw.
The state returned by the environment is twofold: an image-like segmentation map of size 20x20x3 indicating what object is inside each cell (hero, enemy, cover, portal or nothing at all) and an array comprising the rest of the information needed: the number of turns left, the current stats for each hero and each enemy
. The state size is 7414, as it is the concatenation of the flattened image-like segmentation map and vectorial inputs.
Regarding the action space, there are three main group of actions per hero : movement, long and short range attacks, super use. To move, the agent selects a cell on which to send a hero, assuming this cell is within reach of the hero. We use a path-finding algorithm to then move the hero. For the attacks, the agent choose which of the enemies to attack, there is at most 8 enemies. So the total number of possible actions is 3 (number of heroes) x [20x20 (size of the map) + 8 (one shot per enemy) + 8 (one stab per enemy) + 3 (the number of supers)] + 1 (skip) = 1258. Note that not all actions are available for all heroes at all times. For example, the healer cannot use the shield ability or some cells might be out of reach for a hero. When an action is unavailable to the agent, it is simply masked, putting its probability to be selected to 0.
To gather players' data, a play session with 30 participants was organized. We designed a playlist of 10 levels that each player had to play. At the end of each level the player would go on to the next level, no matter the outcome. Playing all 10 levels took each participant roughly one hour of play-time. The game was introduced to them with a tutorial in the form of a PowerPoint document as well as a small video demonstration.
No further interaction with the players took place to ensure that each player had the same level of information going in. The players only knew that this play session was done in order to help automated test, there was no mention of ML. Most participants are not familiar with RL or with ML in general.
Out of the 30 players, the data of 25 of them was used: the rest either did not play all the way to level 10 or skipped some levels. The first level was removed from the available data, as it mainly served as an introduction level where players where mostly testing the controllers and not engaging fully with the game. Levels 2 through 8 were kept as a training set ($L_{Train}$) and levels 9 and 10 as test levels ($L_{Test}$), which means the training set only contains 7 (levels, $L_{Train}$) * 25 (players, $N_P$) = 175 data points.
\subsection{Training Procedure}
To train the agent, we chose to use the ACER \cite{ACER} algorithm. There are a few reasons why ACER was chosen. First, it is a discrete action algorithm which suits the problem well. It is an on-policy and an off-policy algorithm, allowing for both fast convergence and better use of the data generated.
The off-policy part is coupled with a replay buffer, which is prioritized following \cite{schaul2016prioritized}.
Another major reason for choosing ACER is the possibility to run multiple environments in parallel in an asynchronous fashion, all feeding the same buffer and training the same model. This is quite useful for training agents with an environment that is not perfectly stable and could crash.
The inputs of the agent are both vectorial and convolution-based. The actions of the agent are also both vectorial (shots and stabs) and convolution-based (the movements of each hero). Therefore the neural architecture used was very similar to the one developed in \cite{Quentin_Catane}.
The neural network architecture treats the image-like inputs using 2D convolution layers and the vectorial inputs using dense layer. The features generated are then combined to produce both convolutional (for the movements) and vectorial (for the attacks, supers and skip) outputs for the actions.
Some objectives $z$ are easier than others to reach. For example, shooting as little as the players who shot the least is easier than shooting as much as the players who shot the most. This is the reason why a curriculum-based approach was used to sample the play-modes objectives $z$ at each episode. Moreover, automatic curriculum approaches can improve performances of multi-goal agents \cite{ACL_survey} .
The approach used here is the modeling of absolute learning progress with Gaussian mixture models (ALP-GMM) developed by \citeauthor{ALP_curriculum}.
Realistically, training a RL agent on only 7 levels is usually not enough for the agent to be able to generalize well.
Moreover, in most video games it is usually possible to create more levels, simply by changing the topology, the enemies team composition, or the characters' stats (e.g. health or damage).
In this work, the low amount of levels used to train is not due to the low number of levels available to the RL framework, but rather due to the low number of levels the players played on.
Finding a way to incorporate additional levels, even without human data, into the training procedure should be a focus in future work.
Three environments in parallel (each participating in the training of the same model) were used, each running around 12,500 episodes, training the same model. It is equivalent to 24 hours given our computational setup, which is a reasonable constraint to aim for, in real-life use-case of game production.
Our setup is a single computer with a 12 core CPU and a NVIDIA GeForce GTX 1070 GPU.
\section{Evaluation And Results}
\begin{table*}[]
\centerline{
\addtolength{\tabcolsep}{-1.75pt}
\begin{tabular}{|c|c|ll|ll|ll||lll|}
\hline
\multirow{2}{*}{} & \multirow{2}{*}{\textbf{Metrics}} & \multicolumn{2}{c|}{\textbf{Cluster 1}} & \multicolumn{2}{c|}{\textbf{Cluster 2}} & \multicolumn{2}{c||}{\textbf{Cluster 3}} & \multicolumn{3}{c|}{\textbf{All}} \\ \cline{3-11}
& & \multicolumn{1}{c}{\textbf{Player}} & \multicolumn{1}{c|}{\textbf{CARMI}} & \multicolumn{1}{c}{\textbf{Player}} & \multicolumn{1}{c|}{\textbf{CARMI}} & \multicolumn{1}{c}{\textbf{Player}} & \multicolumn{1}{c||}{\textbf{CARMI}} & \multicolumn{1}{c}{\textbf{Player}} & \multicolumn{1}{c|}{\textbf{CARMI}} & \multicolumn{1}{c|}{\textbf{WinOnly}} \\ \hline
\multirow{8}{*}{\rotatebox[origin=c]{90}{\textbf{Train}}} & \textbf{Stabs} & 0.6 (±0.1) & 0.6 (±0.1) & 1.3 (±0.1) & 1.1 (±0.1) & 0.9 (±0.2) & 0.9 (±0.1) & 1.0 (±0.1) & \multicolumn{1}{l|}{0.9 (±0.0)} & 1.1 ( ±0.0) \\
& \textbf{Shots} & 1.7 (±0.1) & 1.5 (±0.1) & 2.1 (±0.1) & 1.9 (±0.0) & 1.7 (±0.2) & 1.6 (±0.1) & 1.9 (±0.1) & \multicolumn{1}{l|}{1.7 (±0.0)} & 0.9 ( ±0.0) \\ \cline{2-11}
& \textbf{Empower} & 0.2 (±0.1) & 0.1 (±0.0) & 0.8 (±0.1) & 0.7 (±0.0) & 0.5 (±0.1) & 0.4 (±0.1) & 0.5 (±0.1) & \multicolumn{1}{l|}{0.5 (±0.0)} & 0.0 ( ±0.0) \\
& \textbf{Heal} & 0.3 (±0.0) & 0.2 (±0.0) & 0.3 (±0.0) & 0.2 (±0.0) & 0.1 (±0.0) & 0.0 (±0.0) & 0.2 (±0.0) & \multicolumn{1}{l|}{0.2 (±0.0)} & 0.2 ( ±0.0) \\
& \textbf{Shield} & 0.1 (±0.0) & 0.1 (±0.0) & 0.2 (±0.0) & 0.1 (±0.0) & 0.1 (±0.0) & 0.1 (±0.0) & 0.1 (±0.0) & \multicolumn{1}{l|}{0.1 (±0.0)} & 0.2 ( ±0.0) \\ \cline{2-11}
& \% Win & 75 (±11) & 52 (±5) & 95 (±4) & 77 (±3) & 87 (±10) & 67 (±7) & 88 (±4) & \multicolumn{1}{l|}{68 (±2)} & 33 ( ±1) \\
& \% Lost & 0 (±0) & 22 (±4) & 0 (±0) & 18 (±3) & 0 (±0) & 20 (±6) & 0 (±0) & \multicolumn{1}{l|}{19 (±2)} & 8 ( ±1) \\
& \% Draw & 24 (±11) & 25 (±4) & 4 (±4) & 4 (±1) & 12 (±10) & 12 (±5) & 11 (±4) & \multicolumn{1}{l|}{12 (±2)} & 58 ( ±2) \\ \hline \hline
\multirow{8}{*}{\rotatebox[origin=c]{90}{\textbf{Test}}} & \textbf{Stabs} & 1.3 (±0.4) & 0.9 (±0.2) & 2.1 (±0.9) & 1.3 (±0.2) & 1.4 (±2.2) & 1.4 (±0.2) & 1.7 (±0.4) & \multicolumn{1}{l|}{1.2 (±0.1)} & 1.6 ( ±0.1) \\
& \textbf{Shots} & 2.1 (±0.2) & 2.0 (±0.2) & 2.2 (±0.3) & 2.2 (±0.1) & 1.9 (±0.6) & 1.8 (±0.2) & 2.1 (±0.2) & \multicolumn{1}{l|}{2.1 (±0.1)} & 1.2 ( ±0.1) \\ \cline{2-11}
& \textbf{Empower } & 0.2 (±0.1) & 0.2 (±0.1) & 0.8 (±0.3) & 0.6 (±0.1) & 0.7 (±0.4) & 0.3 (±0.1) & 0.5 (±0.2) & \multicolumn{1}{l|}{0.5 (±0.1)} & 0.0 ( ±0) \\
& \textbf{Heal} & 0.3 (±0.1) & 0.2 (±0.0) & 0.3 (±0.1) & 0.2 (±0.0) & 0.1 (±0.1) & 0.1 (±0.0) & 0.2 (±0.1) & \multicolumn{1}{l|}{0.2 (±0.0)} & 0.1 ( ±0.0) \\
& \textbf{Shield} & 0.1 (±0.1) & 0.1 (±0.0) & 0.2 (±0.1) & 0.1 (±0.0) & 0.1 (±0.1) & 0.1 (±0.0) & 0.2 (±0.1) & \multicolumn{1}{l|}{0.1 (±0.0)} & 0.5 ( ±0.0) \\ \cline{2-11}
& \% Win & 100 (±0) & 75 (±13) & 100 (±0) & 80 (±8) & 75 (±25) & 52 (±20) & 95 (±8) & \multicolumn{1}{l|}{74 (±7)} & 33 ( ±5) \\
& \% Lost & 0 (±0) & 21 (±13) & 0 (±0) & 13 (±7) & 0 (±0) & 43 (±20) & 0 (±0) & \multicolumn{1}{l|}{20 (±6)} & 0 ( ±0) \\
& \% Draw & 0 (±0) & 2 (±2) & 0 (±0) & 6 (±5) & 25 (±25) & 4 (±4) & 4 (±8) & \multicolumn{1}{l|}{4 (±3)} & 66 ( ±5) \\ \hline
\end{tabular}
}
\caption{Mean and 95\% confidence interval of key-metrics for each cluster for the players and the CARMI agent, on the Train and Test Levels. In bold the metrics used to train the CARMI agent and are reported as the average per turn.}{}
\label{tab:results_all_clusters}
\end{table*}
The CARMI agent is trained on 5 metrics: the number of shots, the number of stabs, the number of shots under an empower, the number of heal made and the number of shield used. All these metrics are expressed as a number per turn, so not the number of shots, but the number of shots per turn for example. The first two metrics represent the overall attack strategy of the play-style, while the other three represent the use of the \textit{super capacity} available.
We will measure the quality of our agent on two aspects :
\begin{enumerate}
\item
Does the space of play-modes generated by the agent cover well the distribution of human players ?
\item Is the agent capable of generating human-like metrics on new and unseen levels
\end{enumerate}
Three models are trained : CARMI, CARI and WinOnly. All three models train on the same levels, have the same state and action space and use the same neural network architecture.
The coefficients of the reward function used by CARI are sampled uniformly in intervals including both positive and negative values, to have the possibility to both encourage and discourage the agent to perform certain actions. This baseline measures what diversity driven agent produces, without taking into account the closeness between its diversity and the diversity in the players play-styles.
The WinOnly model has a sparse binary win/loss reward function. This serve as a baseline to how useful this most commonly used approach would be to give feedback to designers on difficulty assessment, using only a win driven agent, without taking into account the diversity of play-styles.
\subsection{Play-Style Coverage}\label{sec:PS_coverage}
In this section we report the coverage of play-styles for both the CARI and the CARMI agent, and compare them with the players.
We report the results solely on two metrics, due to space constraints: the number of shots per turn and the number of stabs per turn. The CARI agent used here was trained on the same metrics as the CARMI agent.
To measure the coverage possible by the CARI and the CARMI agent we ran 2500 episodes with random $w \sim \mathcal{U}(W)$ for CARI and $z \sim \mathcal{N}(0,1)$ for CARMI.
These results are reported in Fig \ref{fig:coverage_comparison}.
Additionally, we report the Kullback-Leibler (KL) divergence and the Jensen-Shannon (JS) divergence between each of the models (CARMI, CARI and WinOnly) and the Players, both on the train and on the test levels, on the joint distribution of all metrics in Table \ref{tab:kl_JS}.
\begin{table}[]
\centerline{
\begin{tabular}{|ll|l|l|l|}
\hline
& & \textbf{WinOnly} & \textbf{CARI} & \textbf{CARMI} \\ \hline
\multicolumn{1}{|l|}{\multirow{2}{*}{\textbf{Train}}} & KL & 10.17 & 9,34 & \textbf{6,69} \\
\multicolumn{1}{|l|}{} & JS & 0.76 & 0,73 & \textbf{0,60} \\ \hline \hline
\multicolumn{1}{|l|}{\multirow{2}{*}{\textbf{Test}}} & KL & 9,53 & \textbf{9,38} & 9,74 \\
\multicolumn{1}{|l|}{} & JS & 0,80 & 0,80 & \textbf{0,78} \\ \hline
\end{tabular}
}
\caption{All metrics joint normalized distribution divergence between players and agents}{}
\label{tab:kl_JS}
\end{table}
\begin{figure}[h]
\centerline{\includegraphics[scale=0.3]{coverage.png}}
\caption{Coverage of CARI, CARMI and the players. The metrics here are normalized by the players distribution, each point corresponding to an episode.}
\label{fig:coverage_comparison}
\end{figure}
The CARMI agent is indeed very much capable to cover the same space as the players. It even generates play-styles not seen in the players population. This too can be an interesting feedback to give to designers as to what is achievable in these levels.
\subsection{Human-Like Play-Style Emulation}\label{sec:human_ps_sim}
To measure the capacity of the agent to emulate human-like play-style one must first define the play-styles used. To this end, a Gaussian mixture model (GMM) \cite{Gaussian_mixture_model} clustering is trained on the players training normalized summary data: $\psi_{L_{Train}} := \{\psi_l(\tau_{l,.})\}_{l \in L_{Train}}$, which yields $C$ clusters, each representing a portion of the players. In other words, $\{ \mu_c, \Sigma_c\}_{c \in [1:C]} \gets GMM(C;\psi_{L_{Train}})$. These clusters are what is being used to sample the adequate $z$ in order to emulate players' play-styles..
For CARMI, a number of targets per level is sampled from the distribution of each cluster.
For each level $l \in [1: N_L]$ (including $L_{Test}$) and each cluster $c \in [1:C]$, $z$ is sampled following $\mathcal{N}(\mu_c, \Sigma_c)$ and the episode is run using the trained policy $\pi_z$ on level $l$.
Using this sampling method, the absolute metrics generated by CARMI are compared to what is observed in the players' data, on the train and test levels.
Note that the 7 train levels are used to fit the clustering GMM algorithm. The 2 test levels are used for testing. The human data available on these 2 test levels is not used to re train the clustering or the CARMI agent. So, in effect, neither the agents, nor the clustering, use the test levels for anything else than evaluation.
We do not compare results with CARI here for 2 reasons. First, there is no straightforward way to transform the samples $z$ from the clusters into $w$ to feed the CARI agent. Second, even if there were, it is obvious from the big gap in Fig. \ref{fig:coverage_comparison} between the CARI and the players, that the CARI agent would never be able to emulate the players accurately. We do however, compare those results with a pure RL model trained with the sole objective of winning, called "WinOnly". This model is here to compare with what is possible using "\textit{classical}" RL. Indeed, training a model solely to win and using it to inform designers on balancing issues is not unheard of in the industry.
Note that neither the training of CARMI nor the training of the clustering have seen the test levels nor the players' data on those levels, these are truly previously unseen levels. These results are available in Table \ref{tab:results_all_clusters}.
The first thing to notice is the capacity of the agent to match the desired metrics on the train levels, it is a good indicator that the model did converge. Also it is worth noting that the agent is overall capable to generalize those play-styles to unknown levels, in the test set.
Looking at what the CARMI agent has produced, the feedback that we would have given the designers would have been that the new levels will have the players shoot and dash more, but that the use of the \textit{super capacities} would remain somewhat stable. These feedback would have been correct since they match what is observed in the player's data for the test levels.
Had we used the WinOnly model to give feedback to the designers we would have been right about the shots and dash, we would however have missed completely the feedback on the \textit{super capacities}. This goes to show that encouraging models to fit the players play-modes allows to create mode meaningful feedback from automated tests.
The other very interesting result are the win rates. Overall the players perform better on the new level: from 88\% to 95\% of game won. The same is observed with the agent: from 68\% to 74\%. But even more interesting are the win rates of the clusters between the train and the test levels. The players in clusters 1 and 2 both perform better in the test levels, and this increase in performance is mirrored by the agent emulating these two clusters. However the players in cluster 3 perform worse: from 87\% to 75\%. The agent, when emulating this third cluster, also performs worse.
Indeed, regarding difficulty assessment, given what the CARMI agent has produced, we would have concluded to the designers that the new levels are overall easier, expect for the third cluster.
Additionally, as for the play-modes, the win rates of the WinOnly model is not reliable and doesn't allow to draw correct conclusions.
\section{Conclusion And Discussion}
We have developed a new agent capable, with one single training phase, to generate a continuum of play-styles which includes the players' ones, using limited human summarized data. We have also developed and demonstrated the effectiveness of a straightforward sampling strategy able to generate human-like play-styles on new levels reliably. This approach can provide very meaningful feedback to level designers.
This approach makes no assumption as to the type of environment, or RL algorithm used, making it easily usable in many different contexts.
Improvements should be made to incorporate more play-modes in order to capture more of the players play-styles. We argue that the more numerous the play-modes, the smaller the differences in win rates.
Another limitation of this approach is the number of level used for training being limited by the available human data. Including randomly generated levels (or at least some variations of the training levels), lacking human data, into the training procedure would also allow the agent to generalize better between the train and the test levels.
Furthermore, we notice that the differences between the agent and the players are bigger at the level of the clusters rather than at the level of the whole population. Including the players' clusters distribution in the learning phase would probably increase the accuracy of the agent when emulating each of these clusters. Simply put, using the clustering during both learning and inference would allow a better approximation of the clusters by the agent.
Moreover, this method relies on metrics computed over a whole episode (i.e. a whole game). So, for games with very long episodes (e.g. RTS games) there are many ways to reach the desired metrics. This might produce unexpected results. For example, in a RTS game with a metric measuring the amount of resources gathered, the CARMI agent could gather the desired amount of resources in an unexpected way. This could indeed produce misleading feedback for the designers. One way to counter balance this is to increase the number of target metrics used and their variety to capture more gameplay aspects. The more numerous the number of metrics, the more constrained the agent should be. Studying the effect of a varying number of metrics should be done in the future.
\normalsize
| {'timestamp': '2022-12-01T02:19:58', 'yymm': '2211', 'arxiv_id': '2211.17188', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17188'} | arxiv |
\section{Introduction}
Dynamic systems in AI are often constituted by autonomous agents and heterogeneous components whose internal specification is either unknown
or not accessible, so that well-known techniques to ascertain their correctness at design-time, such as model checking and testing, are not applicable.
This calls for approaches to check
desired
properties at runtime, by \emph{monitoring} the executions of the black-box system under scrutiny.
A widely known, solid approach to monitoring is that of \emph{runtime verification} (RV), where given a logical property,
the monitor emits a provably correct verdict~\cite{LeuS09}.
Formalisms based on LTL and its extensions have indeed been extensively applied when monitoring multi-agent systems \cite{DaTY18}, software components~\cite{LeuS09} and business processes~\cite{LMMR15,MaggiFDG14}.
\citeauthor{LeuS09} (\citeyear{LeuS09}) highlight two essential semantic desiderata
of linear-time monitors. First, a monitored trace has a finite length, which calls for a finite-trace semantics. Second, a trace is the prefix of an unknown, full trace. Thus, the verdict of the monitor should be \emph{anticipatory}~\cite{BartocciFFR18}, i.e., depend not only on the data seen so far, but also on its (infinitely many) possible continuations.
In this spectrum, we build on
the widely studied logic \textsc{LTL}$_f$\xspace, or LTL over finite traces~\cite{DeGV13}, where both the monitored prefixes and their infinitely many suffixes have a finite (yet unbounded) length.
Specifically, we focus on the more sophisticated setting of \textsc{RV-LTL}\xspace by \citeauthor{BaLS10} (\citeyear{BaLS10}), where the verdict of the monitor of a property $\psi$ at each point in time
is one of four possible values: \emph{currently satisfied} ($\psi$ is satisfied now but may be violated in a future continuation), \emph{permanently satisfied} ($\psi$ is satisfied now and will necessarily stay so), and the two complementary values of \emph{permanent} and \emph{current violation}.
Thus,
\textsc{RV-LTL}\xspace monitoring is at least as hard as satisfiability and validity.
For propositional \textsc{LTL}$_f$\xspace, an \textsc{RV-LTL}\xspace monitor can be constructed from the deterministic finite-state automaton (DFA) corresponding to the property, by labeling each DFA state by an \textsc{RV-LTL}\xspace value, depending on whether it is final and can reach final and non-final states \cite{MMWV11, DDMM22}.
Prior work on \textsc{LTL}$_f$\xspace monitoring like the above has often focused on propositional traces, where states are described by propositional interpretations.
This coarse-grained representation creates a large abstraction gap w.r.t. dynamic systems, which often generate \emph{data-aware} traces where states contain richer objects from an infinite domain, e.g., strings or numbers. On the other hand, for richer logics partial methods have been devised,
but without guarantees that the monitoring task can be solved, e.g.~\cite{RegerCR15}.
Aiming to bridge this gap, we
\begin{inparaenum}[\it (i)]
\item introduce an extension of \textsc{LTL}$_f$\xspace, called A\textsc{LTL}$_f$\xspace, which combines linear-time operators with linear arithmetic constraints over data variables \emph{within and across states},
\item study how to construct automata-based \textsc{RV-LTL}\xspace monitors for such formulae
and
\item identify decidable classes of properties, given that A\textsc{LTL}$_f$\xspace monitoring is in general undecidable.
\end{inparaenum}
\NEW{The next example illustrates the challenge that we aim to address.}
\newcommand{\mathit{r}}{\mathit{r}}
\newcommand{\mathit{p}}{\mathit{p}}
\newcommand{\mathit{b}}{\mathit{b}}
\newcommand{\mathit{t}}{\mathit{t}}
\newcommand{\mathit{T}}{\mathit{T}}
\newcommand{\mathit{act}}{\mathit{act}}
\begin{example}
\label{ex:intro}
\NEW{
Consider the monitoring of suspicious bidding patterns in an on-line auction.
The auction process can be depicted as a labeled transition system as follows:\\
\resizebox{\columnwidth}{!}{
\begin{tikzpicture}[node distance=42mm,>=stealth']
\tikzstyle{action}=[scale=.55]
\tikzstyle{pstate}=[draw, rectangle, rounded corners, inner sep=3pt, line width=.7pt, scale=.6]
\node[pstate] (1) {init};
\node[pstate, right of=1] (2) {$\mathit{act}$};
\node[pstate, right of=2] (3) {term};
\draw[edge] (1) to node[above,action]
{$\m{set}$}
node[below,action]
{$\mathit{b}'\,{=}\,0,\ \mathit{t}' \,{=}\,\mathit{T},\ \mathit{p}' \,{>}\,0$}(2);
\draw[edge] (2) to node[above,action] {$\m{exp}$} node[below,action] {$\mathit{t} \,{\leq}\,0$} (3);
\draw[edge, loop above] (2) to node[right,action, yshift=-2mm] {$\ \m{dec}\colon\mathit{t}' \,{<}\,\mathit{t}$} (2);
\draw[edge, loop below] (2) to node[right,action, yshift=2mm] {$\ \m{bid}\colon\mathit{p}'\,{>}\,\mathit{p},\ \mathit{b}'\,{\neq}\,\mathit{b},\ \mathit{t}' \,{=}\,\mathit{T}$} (2);
\end{tikzpicture}
}
The process maintains three variables: the current price $\mathit{p}$ (i.e., the last bid); the id of the last bidder $\mathit{b}$, and a timer $t$. In the edge labels, $'$ indicates the next value of the respective variable that is written by the transition. The transition $\mathsf{set}$ fixes $\mathit{p}$ to some base price and initializes the timer to the duration $\mathit{T}$ of a round. Then, either the timer is decreased by transition $\mathsf{dec}$, or a bidder increases the price, upon which the timer is reset to $\mathit{T}$.
Finally, $\mathsf{exp}$ terminates the auction when the timer expires.
(We assume that all variables not explicitly written in transition guards keep their value.)
With an additional variable $s$ for the state, the process can be encoded in ALTL$_f$ as follows:
\begin{equation}
\label{eq:transition:system}
(s\,{=}\,\mathit{init}) \wedge \mathsf{G}\xspace(\psi_{\m{set}} \vee \psi_{\m{dec}} \vee \psi_{\m{bid}} \vee \psi_{\m{exp}})
\tag{$\star$}
\end{equation}
where, e.g., $\psi_{\m{set}} = (s\,{=}\,\mathit{init} \wedge s'\,{=}\,\mathit{act} \wedge \mathit{t}' \,{=}\,\mathit{T}\wedge\mathit{p}' \,{>}\,0)$, and other transitions are encoded similarly.}
\NEW{
During an auction, it is desirable to identify users that exhibit \emph{shilling behavior}, i.e., they drive up the auction price for the seller.
Given a user $u$, consider the following behavior patterns~\cite{XuC07}:
\begin{inparaenum}
\item[(OB)] \emph{Overbidding}: $u$ places an overbid (i.e.,increasing the price by at least 20\%) when the last bid happened a while ago. This can be expressed as $\mathit{OB}_u:= \mathsf{F}\xspace(\mathit{b}'\,{=}\,u \wedge \mathit{t}\,{\leq}\,\epsilon \wedge \mathit{p}'\,{\geq}\mathit{p}\cdot 1.2)$, for some small $\epsilon$.
\item[(AU)] \emph{Aggressive underbidding}: \emph{underbidding} means that the price increase is less than 3\$, and \emph{aggressive} that the time gap between two bids is small (for simplicity, we assume here in the next state). This can be
expressed as $\mathit{AU}_u:= \mathsf{G}\xspace(\mathit{b}\,{\neq}\,u \wedge \mathit{b}\,{>}\,0 \to \mathit{p}'\,{\geq}\,\mathit{p}{+}3 \wedge\mathit{b}\,{=}\,u)$.
\end{inparaenum}
Both (OB) and (AU) likely imply shilling.
The following is an example process execution (also called a \emph{trace}) with $\mathit{T}=2$
\\[1ex]
$\begin{array}{l|r@{\hspace{3mm}}r@{\hspace{3mm}}r@{\hspace{3mm}}r@{\hspace{3mm}}r@{\hspace{3mm}}r@{\hspace{3mm}}r@{\hspace{3mm}}r@{\hspace{3mm}}r@{\hspace{3mm}}r}
s &\mathit{init}&\mathit{act}&\mathit{act}&\mathit{act}&\mathit{act} & \mathit{act}& \mathit{act}& \mathit{act}\\
\mathit{t} & 0 & 2 & 2 & 2 & 1 & 2 & 2 & 2 \\
\mathit{p} & 0 & 10 & 30 & 32 & 32 & 36 & 40 & 50 \\
\mathit{b}& 0 & 0 & 1 & 2 & 2 & 3 & 1 & 2 \\
\multicolumn{9}{c}{}\\[-1.3ex]
\mathit{OB}_2 & \textsc{cv} & \textsc{cv} & \textsc{cv} & \textsc{cv} & \textsc{cv} & \textsc{cv} & \textsc{cv} & \text{\textsc{ps}} \\
\mathit{AU}_2 & \textsc{cs} & \textsc{cs} & \textsc{cs} & \textsc{cs} & \textsc{cs} & \textsc{cs} & \textsc{pv} & \textsc{pv} \\
\mathit{shill_2} & \textsc{cs} & \textsc{cs} & \textsc{cs} & \textsc{cs} & \textsc{cs} & \textsc{cs} & \textsc{cv} & \text{\textsc{ps}}\\
\end{array}$\\[1ex]
The lower part of this table shows monitoring results for the trace, namely
the RV values obtained for observing
(OB) and (AU) for user 2, as well as for
$\mathit{shill_2} := \mathit{OB}_2 \vee \mathit{AU}_2$.
The techniques presented in this paper show how to construct monitors for such properties fully automatically.}
\end{example}
Technically, we follow \citeauthor{DD07} (\citeyear{DD07})
and consider traces consisting of assignments of a fixed set of variables to
numeric values (which may encode complex data objects, e.g. strings).
A starting point is the approach in \cite{FMW22a}, where automata-based techniques are used to model check dynamic systems against an extension of \textsc{LTL}$_f$\xspace with linear arithmetic constraints, e.g.,
``the value of sensor $x$ differs from that of sensor $y$ by 5 units until it exceeds 25''.
However, that approach has two prohibitive technical limitations.
The first one is operational: their automata are too weak for monitoring as they are faithful only for reachability of final, but not non-final states.
The second shortcoming is semantical: arithmetic conditions can only relate variables within the same state, so one cannot specify the (un)desired progression of assignments over instants in the trace.
For this reason \citeauthor{DD07} (\citeyear{DD07}) and, more recently, \citeauthor{GGG22} (\citeyear{GGG22}), allow properties to compare variables across states.
Our logic A\textsc{LTL}$_f$\xspace follows this route, enabling variable \emph{lookahead}
to reference variable values in different instants within arbitrary linear arithmetic constraints, (cf. e.g. $p'\,{>}\,p$ in Ex.~\ref{ex:intro}).
Our approach is thus substantially different from \cite{DD07}, which restricts to
variable-to-variable and variable-to-constant comparisons to guarantee decidability of satisfiability.
Instead, we allow arbitrary linear arithmetic constraints with lookahead, making satisfiability (and monitoring) of A\textsc{LTL}$_f$\xspace undecidable even for simple formulae.
Despite the rich research body on monitoring,
there are few approaches that are anticipatory, feature full LTL$_f$, and incorporate arithmetic with lookahead~\cite{FalconeKRT21}.
The seminal LOLA approach~\cite{DAngeloSSRFSMM05} supports arithmetic with lookahead and finite traces, but is not anticipatory.
Also
\citeauthor{FaymonvilleFSSS19} (\citeyear{FaymonvilleFSSS19}) and \cite{BasinKMZ15} have only bounded anticipation.
More related is
\textsf{MarQ} \cite{RegerCR15}, a strong, anticipatory RV tool for finite traces with relations and arithmetic, but its approach has no decidability guarantees.
We
overcome these limitations as follows:
\begin{inparaenum}[(1)]
\item we show that A\textsc{LTL}$_f$\xspace monitoring is decidable for linear arithmetic constraints without lookahead, and provide techniques to construct automata-based \textsc{RV-LTL}\xspace monitors.
\item we show, for formulae with lookahead, undecidability of A\textsc{LTL}$_f$\xspace satisfiability/monitoring.
\item To mitigate this, we study how the abstract property of \emph{finite summary}, introduced in \cite{FMW22a}, can be employed for A\textsc{LTL}$_f$\xspace formulae with lookahead that satisfy this property, proving decidability of monitoring and providing a technique to construct automata-based \textsc{RV-LTL}\xspace monitors.
\item We use this general result to show decidability for different concrete classes of formulae enjoying finite summary, obtained by restricting either the language of constraints, or the way these interact with each other via lookahead.
\item A prototype tool witnesses feasibility of our approach.
\end{inparaenum}
\NEW{
The structure of the paper reflects Contributions (1)--(5) in this order, after
the introduction of A\textsc{LTL}$_f$\xspace and the monitoring problem
and a section about the construction of automata for A\textsc{LTL}$_f$\xspace properties afterwards.}
\section{Preliminaries}
We consider the sorts $\mathit{int}$ and $\mathit{rat}$ with domains $d(\mathit{int})=\allowbreak\mathbb Z$ and $d(\mathit{rat}) = \mathbb Q$.
For a set of variables $V
, let $V_s\,{\subseteq}\,V$ be those in $V$ of sort $s$.
We define arithmetic constraints as:
\begin{definition
\label{def:constraint}
Given a set of variables $V$, expressions $e_s$ of sort $s$ and \emph{constraints} $c$ are defined as follows: \\
\begin{tabular}{r@{~}l@{\qquad}r@{~}l}
$e_s$ :=&\ $v_s\:\mid\:k_s\:\mid\:e_s + e_s\:\mid\:k_s \cdot e_s $ \\
$c$ :=&\ $e_s = e_s\:\mid\:e_s \neq e_s\:\mid\:e_s < e_s\:\mid\:e_s \leq e_s \mid {}$\\
&\ $e_{\mathit{int}} \approx_n e_{\mathit{int}}\mid\:e_{\mathit{int}} \not\approx_n e_{\mathit{int}}$
\end{tabular}\\
where $k_s\in d(s)$ is a constant, $v_s \in V_s$ a variable of appropriate sort, and $\approx_n$ denotes
congruence modulo $n\in \mathbb N$.
\end{definition}
\noindent
The set of all constraints over $V$ is denoted by $\mc C(V)$.
E.g., $x\,{<}\,y\,{+}\,z$, and $x\,{-}\,y\,{\neq}\,2 $ are constraints
independent of the sort of $x, y, z$,
but $u \equiv_3 v + 1$ requires that $u$ and $v$ have sort $\mathit{int}$.
We also consider boolean formulas with constraints as atoms; these are in the realm of SMT with linear arithmetic, which is decidable and admits \emph{quantifier elimination}~\cite{Presburger29}:
if $\varphi$ is a formula with free variables $X \cup \{y\}$
and constraint atoms,
there is some $\varphi'$ with free
variables $X$ that is logically equivalent to $\exists y. \varphi$,
i.e., $\varphi'\,{\equiv}\,\exists y. \varphi$.
From now on, let $V$ be a fixed, finite, non-empty set of variables
called \emph{state variables}.
An \emph{assignment} $\alpha$ maps every $v\inn V$ to a value $\alpha(v)$ in the domain of its sort.
\NEW{
The set of \emph{variables with lookahead} ${\mathcal V}$ consists of all $v^{\prime\cdots\prime}$ such that $v\in V$ is decorated with $i$ prime symbols $'$, for $i\geq 0$, and we say that $v$ \emph{has lookahead $i$}.
Intuitively, $v^{\prime\cdots\prime}$ with $i$ primes refers to the value of $v$ looking $i$ instants into the future.
For instance, $v'$ refers to the value of $v$ in the next step, while $v''$ is the value of $v$ two steps ahead.
}
\begin{definition}
Let $\mathcal L$ be the set of properties $\psi$ defined by the following grammar,
where $c \in \mc C(\mathcal V)$ is a constraint:
\[\psi :: =
c \mid
\psi {\wedge} \psi \mid \neg \psi \mid
\mathsf{X}_s\xspace \psi \mid \psi \U \psi
\]
\end{definition}
When needed, we write $\mathcal L(V)$ instead of $\mathcal L$ to make explicit the set of variables in constraints.
The usual transformations apply, namely $\psi_1 {\vee} \psi_2 \equiv \neg (\psi_1 {\wedge} \psi_2)$, $\mathsf{X}_w\xspace \psi \equiv \neg (\mathsf{X}_s\xspace \neg \psi)$,
$\mathsf{F}\xspace \psi \equiv \top \U \psi$, $\mathsf{G}\xspace \psi \equiv \neg \mathsf{F}\xspace \neg \psi$;
moreover $\top \equiv (v = v)$ for some $v\,{\in}\,V$, and $\bot \equiv \neg \top$.
A property $\psi$ \emph{has lookahead $m$} if
\NEW{the maximal lookahead of a variable in $\psi$ is $m$.
For instance, all properties in Ex.~\ref{ex:intro} are in this language; the lookahead of $\mathit{AU}_2$ is 1 but of $\mathit{t} \,{\leq}\,0$ it is 0.}
Properties are evaluated over \emph{traces}: a trace $\tau$ of length $n\,{\geq}\,1$ is a finite sequence
$\alpha_0, \alpha_1, \dots, \alpha_{n-1}$ of assignments with domain $V$.
We write $\tau(i)$ to denote $\alpha_i$, for $0\,{\leq}\,i\,{<}\,n$.
A constraint $c$ is \emph{well-defined} at instant $i$ of $\tau$ if $0 \leq i < n$ and all \NEW{variables with lookahead $j$ in $c$ satisfy $i\,{+}\,j < n$.
The upper part of the table in Ex.~\ref{ex:intro} is an example of a trace,
and e.g., $\mathit{p}' \geq \mathit{p}$ is well-defined at all but the last instant.}
\begin{definition}
\label{def:witness}
If an expression $e$ is well-defined at instant $i$ of a trace $\tau$ of length $n$,
its \emph{evaluation} $[\tau,i](e)$ at instant $i$ is:\\[1ex]
\begin{tabular}{@{}r@{\,}l@{\:\:}r@{\,}l@{}}
$[\tau,i](k)$ &$= k$ &
$[\tau,i](e{+}e_2)$ &$= [\tau,i](e_1){+}[\tau,i](e_2)$\\
$[\tau,i](v^{\prime\cdots\prime})$ &$= \tau(i{+}j)(v)$ &
$[\tau,i](k\cdot e)$&$=k\cdot[\tau,i](e)$
\end{tabular}\\[1ex]
where $v^{\prime\cdots\prime}$ has lookahead $j$.
Then, $\tau$ \emph{satisfies} $\psi \in \mathcal L$, denoted
$\tau \models \psi$, iff $\tau,0 \models \psi$ holds,
where, for $0\leq i$:
\noindent
\begin{tabular}{@{}l@{\:}l@{}}
$\tau,i \models$&$ e_1 \odot e_2$ iff $0 \leq i < n$ and either\\
& -- $e_1 \odot e_2$ is not well-defined for $\tau$ and $i$, or \\
& -- $[\tau,i](e_1) \odot [\tau,i](e_2)$ holds
\\
$\tau,i \models$&$ \psi_1 \wedge \psi_2$ iff
$\tau,i \models \psi_1$ and $\tau,i \models \psi_2$\\
$\tau,i \models$&$ \neg \psi$ iff
$\tau,i \not\models \psi$\\
$\tau,i \models$&$ \mathsf{X}_s\xspace\psi$ iff $i<n-1$ and $\tau,i{+}1 \models \psi$\\
$\tau,i \models$&$ \psi_1 \U \psi_2$ iff $i < n$ and either
$\tau,i \models \psi_2$, or \\
& $i\,{<}\,n{-}1$,
$\tau,i \models \psi_1$ and
$\tau,i{+}1\models \psi_1 \U \psi_2$
\end{tabular}
\end{definition}
\noindent
\NEW{The trace in Ex.~\ref{ex:intro} e.g. satisfies $\mathit{OB}_2$, its proper prefixes do not.}
Note that lookahead variables have a \emph{weak} semantics, in that a constraint $c$ holds if it contains a variable $v^{\prime\cdots\prime}$ that refers to an instant beyond the trace.
If instead a strict semantics is desired, one can replace
$c$ by $c\wedge \mathsf{X}\xspace_s\dots\mathsf{X}\xspace_s\top$, where the number of $\mathsf{X}\xspace_s$ operators equals
the lookahead of $c$.
We now define our main task, that is to monitor how the satisfaction of a given property changes along a trace, that is, by considering the trace (fragment) $\tau$ seen \emph{so far}.
As customary~\cite{BaLS10}, we consider the set $RV = \{\text{\textsc{ps}}, \textsc{cs}, \textsc{cv}, \textsc{pv}\}$ of four distinct \emph{monitoring states}:
current satisfaction ($\textsc{cs}$), permanent satisfaction ($\text{\textsc{ps}}$), current violation ($\textsc{cv}$) and permanent violation ($\textsc{pv}$).
\begin{definition
\label{def:monitoring}
A property $\psi\in \mathcal L$ is in
monitoring state $s \in RV$ after a trace $\tau$, written $\tau \models \llbracket \psi = s\rrbracket$, if
\begin{compactitem}
\item
$s = \textsc{cs}$, $\tau \models \psi$, and $\tau\tau' \not\models \psi$ for some trace $\tau'$;
\item
$s = \text{\textsc{ps}}$, $\tau \models \psi$, and $\tau\tau' \models \psi$ for every trace $\tau'$;
\item
$s = \textsc{cv}$, $\tau \not\models \psi$, and $\tau\tau' \models \psi$ for some trace $\tau'$;
\item
$s = \textsc{pv}$, $\tau \not\models \psi$, and $\tau\tau' \not\models \psi$ for every trace $\tau'$.
\end{compactitem}
\end{definition}
E.g., $\tau \models \llbracket \psi = \textsc{cs}\rrbracket$ means that $\psi$ is currently true after $\tau$ but there exists a possible continuation of $\tau$ (i.e., a trace $\tau\tau'$) after which $\psi$ is false.
After a trace, a property $\psi$ is in exactly one possible monitoring state.
\NEW{For instance, the given monitoring states in Ex.~\ref{ex:intro} are as defined in Def.~\ref{def:monitoring}.}
Given input $\tau$ and $\psi$,
the \emph{monitoring problem}
is to compute the state $s\in RV$ s.t.
$\tau \models \llbracket \psi = s\rrbracket$. It is \emph{solvable} if
one can construct a procedure for $\psi$ that computes the monitoring
state for any given trace. Unfortunately, we have that in general:
\begin{theorem}
The monitoring problem is not solvable.
\end{theorem}
To see this, call a property $\psi \in \mathcal L$ \emph{satisfiable} if
$\tau \models \psi$ for some (non-empty) trace $\tau$.
It can be shown
\longversion{(cf.~Lem. \ref{lem:undecidable} in the appendix)}{}
that
satisfiability of $\mathcal L$ properties with lookahead 1 is undecidable, by a reduction from reachability in 2-counter machines.
Now, for a formula of the form $\psi=\mathsf{X}_s\xspace\psi'$ and a trace $\tau_0$ of length 1,
$\psi'$ is satisfiable iff
$\tau_0\models\llbracket\psi=\textsc{cv}\rrbracket$,
so satisfiability of $\psi'$ reduces to monitoring $\tau_0$ against $\psi$.
\smallskip
In this paper we study when monitoring is solvable.
First, we show that without loss of generality one can restrict to properties with lookahead 1: Indeed, a
property with lookahead $m{>}1$ can be transformed into one with $m{=}1$ by adding fresh variables and extending to these the assignments in the trace
in an appropriate way.
In general, $m{-}1$ fresh book-keeping variables are needed for each variable with lookahead $m{>}1$.
Intuitively,
constraints are then rewritten to mention only consecutive instants,
using chains of next operators.
E.g.,
$\psi{=} \mathsf{G}\xspace (x''\,{>}\,x)$ is equivalent to
$\widehat\psi{=} \mathsf{G}\xspace (u'\,{>}\,x \wedge \mathsf{X}_w\xspace(u\,{=}\,x'))$.
The trace
$\tau\colon
\{x\,{=}\,2\},\allowbreak
\{x\,{=}\,0\},\allowbreak
\{x\,{=}\,3\}$
satisfies $\psi$ and
$\widehat\tau\colon
\{x\,{=}\,2,\allowbreak u\,{=}\,0\},\allowbreak
\{x\,{=}\,0,\allowbreak u\,{=}\,3\},\allowbreak
\{x\,{=}\,3,\allowbreak u\,{=}\,0\}$
satisfies $\widehat\psi$, with $\widehat\tau$ obtained from $\tau$ by assigning to $u$ the subsequent value of $x$.
A detailed proof of the next result can be found in the appendix.
\begin{restatable}{lemma}{lemmamorelookahead}
\label{rem:look:ahead:only:1}
Let $\psi\in \mathcal L(V)$ have lookahead $m$.
There is some $\psi_1\in \mathcal L(V \cup X)$ with lookahead $1$ for a set of fresh variables $X$ such that for every trace $\tau$ over $V$ there is a trace $\widehat\tau$ over $V \cup X$ satisfying $\tau \models \psi$ iff $\widehat\tau \models \psi_1$, where $|\widehat\tau|=|\tau|$ and $\widehat\tau(i)$ agrees with $\tau(i)$ on $V$, for all $i$.
\end{restatable}
\section{Automata for properties}
\label{sec:automata}
In the sequel, we will develop first monitoring techniques for $\mathcal L$ properties
without lookahead, and then with lookahead 1.
Although the former case is simpler and could be addressed by an ad-hoc approach resembling techniques for propositional LTL$_f$~\cite{MMWV11}, we adopt a uniform approach for both cases.
To this end, we first present the
construction of an automaton that represents a given property $\psi$; this will be crucial in the later sections.
As a preprocessing step, two transformations are applied to the property:
\noindent
(1) We assume $\psi$ in negation normal form; so it may also contain $\vee$, $\mathsf{G}\xspace$, and $\mathsf{X}_w\xspace$, so far considered syntactic sugar.
Note that for constraints with lookahead, negation cannot be pushed to the constraint level, e.g., $\neg (x'\,{=}\,x)$ is not equivalent to $x'{\neq}x$ as the latter is satisfied by any trace of length 1 but the former need not be.
In the construction, we thus treat constraints with and without negation separately.
For clarity, we write $neg(c)$ to flip the comparison operator in $c$:
$neg (t_1\,{=}\,t_2) := t_1\,{\neq}\,t_2$,
$neg (t_1\,{<}\,t_2) := t_2\,{\leq}\,t_1$,
$neg (t_1\,{\approx_n}\,t_2) := t_2\,{\not\approx_n}\,t_1$,
and vice versa, for all $t_1,t_2$.
\noindent
(2)
We want a monitor to return the monitoring state for the trace (prefix) $\tau$ seen so far, without depending on future variable assignments.
However, the evaluation of a constraint with lookahead depends on the next, not yet seen, assignment (see Def.~\ref{def:witness}).
To avoid this counterintuitive peculiarity and make the monitoring task clearer, we transform constraints with look\emph{ahead} 1 into constraints with look\emph{back} 1.\\
To this end, we consider variables $\pre{v}$ and $\cur{v}$, for all $v\inn V$.
For a constraint $c$, let $back(c)$ be defined as
(a) if $c$ has no lookahead, $back(c)$ is obtained from $c$ by replacing $v$ with $\cur{v}$, and
(b) if $c$ has lookahead, $back(c) :=\mathsf{X}_w\xspace \bar{c}$, with $\bar{c}$ obtained from $c$ by replacing $v$ with
$\pre{v}$ and $v'$ with $\cur{v}$; for all $v\inn V$.
We denote the property where each constraint $c$ is replaced by $back(c)$ by $\psi_\back$.
Then $\psi$ and $\psi_\back$ are equivalent
\longversion{(cf.~Lem. \ref{lem:lookback:lookahead} in the appendix)}{(see long version)}.
We write $V_{{\mathit{pre}}} {=} \{\pre{v} \mid v\in V\}$ and the same for $V_{{\mathit{cur}}}$.
\begin{example}
Property $\psi = \mathsf{G}\xspace(x'\,{>}\,x) \wedge \mathsf{F}\xspace (x\,{=}\,2)$ is equivalent to $\psi_\back = \mathsf{G}\xspace(\mathsf{X}_w\xspace (\cur{x}\,{>}\,\pre{x})) \wedge \mathsf{F}\xspace (\cur{x}\,{=}\,2)$.
\end{example}
Given $\psi_\back$, we build an NFA $\NFA[\psi_\back]$ using an auxiliary function $\delta$, as in~\cite{DeGV13}.
Let $C$ be the set of constraints in $\psi_\back$, and $C^\pm = C \cup\{ neg(c) \mid c\inn C\}$;
and $\lambda$ be an auxiliary proposition used to mark the last element of a trace.
The alphabet of the NFA will be $\smash{\Sigma=2^{C^\pm}}$, i.e., a symbol is a set of constraints. For the construction
we also use its extension $\smash{\Sigma_\lambda=2^{C^\pm \cup \{\lambda,\neg\lambda\}}}$.
Let $\varsigma\inn \Sigma_\lambda$ be \emph{satisfiable} if $\{\lambda, \neg \lambda \}\not \subseteq \varsigma$, and the conjunction of constraints in $\varsigma$ is satisfiable.
The input of $\delta$ is a (quoted) property $\phi \in \mathcal L\cup \{\top,\bot\}$ over $V_{\mathit{pre}} \cup V_{\mathit{cur}}$.
The output of $\delta$ is a set of pairs
$(\inquotes{\phi'},\varsigma)$ where $\phi' \in \mathcal L\cup \{\top,\bot\}$ is again
a (quoted) property over $V_{\mathit{pre}} \cup V_{\mathit{cur}}$
and $\varsigma \in \Sigma_\lambda$.
For two sets of such pairs $R_1$, $R_2$, let
$R_1 \owedge R_2 = \{ (\inquotes{\psi_1 \wedge \psi_2}, \varsigma_1 \cup \varsigma_2) \mid (\inquotes{\psi_1}, \varsigma_1) \inn R_1, (\inquotes{\psi_2}, \varsigma_2) \inn R_2\text{ and }\varsigma_1\cup \varsigma_2\text{ is satisfiable} \}$, where we simplify $\psi_1 \wedge \psi_2$ if possible; and let $R_1 \ovee R_2$ be defined in the same way, replacing con- with disjunction.
Intuitively, $(\inquotes{\phi'},\varsigma)\in\delta(\phi)$ expresses that when $\phi$ is the property to evaluate, if $\varsigma$ is the current symbol of the word $w\inn \Sigma^+$ that is read, then $\phi'$ is the (sub)property yet to satisfy to determine whether $w$ satisfies $\phi$.
\begin{definition}
For $\psi \in \mathcal L \cup \{\top, \bot\}$, $\delta$ is as follows:
\begin{tabular}{@{~}r@{~}l}
$\delta(\inquotes{\top})$ =& $\{(\inquotes{\top},\emptyset)\} \text{ and }\delta(\inquotes{\bot}) = \{(\inquotes{\bot},\emptyset)\}$\\
$\delta(\inquotes{c})$ =& $\{(\inquotes{\top},\{c\}),(\inquotes{\bot},\{neg(c)\})\}$ \\
$\delta(\inquotes{\neg c})$ =& $\{(\inquotes{\bot},\{c\}),(\inquotes{\top},\{neg(c)\})\}$\\
$\delta(\inquotes{\psi_1 \wedge \psi_2})$ =& $\delta(\inquotes{\psi_1}) \owedge \delta(\inquotes{\psi_2})$\\
$\delta(\inquotes{\psi_1 \vee \psi_2})$ =&
$\delta(\inquotes{\psi_1}) \ovee \delta(\inquotes{\psi_2})$ \\
$\delta(\inquotes{\mathsf{X}_s\xspace \psi})$ =&
$\{(\inquotes{\psi},\{\neg \lambda\}), (\inquotes{\bot}, \{\lambda\})\}$ \\
$\delta(\inquotes{\mathsf{X}_w\xspace \psi})$ =&
$\{(\inquotes{\psi},\{\neg \lambda\}), (\inquotes{\top}, \{\lambda\})\}$\\
$\delta(\inquotes{\mathsf{G}\xspace \psi})$ =&
$\delta(\inquotes{\psi}) \owedge \delta(\inquotes{\mathsf{X}_w\xspace\mathsf{G}\xspace \psi})$ \\
$\delta(\inquotes{\psi_1 \U \psi_2})$ =&
$\delta(\inquotes{\psi_2}) \ovee (\delta(\inquotes{\psi_1})
\owedge \delta(\inquotes{\mathsf{X}_s\xspace(\psi_1 \U \psi_2)}))$.
\end{tabular}
\end{definition}
While the symbol $\lambda$ is needed for defining $\delta$, we can omit it
from the NFA, and define $\NFA$ as follows:
\begin{definition}
\label{def:NFA}
Given a property $\psi \in \mathcal L$, we define the NFA as
$\NFA\,{=}\,(Q, \Sigma, \varrho, q_0, Q_F)$ where $q_0\,{=}\,\inquotes{\psi_\back}$ is the initial state,
$Q_F = \{\inquotes{\top}, q_{+}\}$ is the subset of final states,
$q_{-}$ is an additional non-final state,
and
$Q$, $\varrho$ are the smallest sets such that $q_0, q_F, q_{+}, q_{-} \in Q$ and whenever
$q\in Q\setminus\{q_{+}, q_{-}\}$ and $(q', \varsigma)\in \delta(q)$
then $q'\in Q$ and
\begin{compactenum}[(i)]
\item if $\lambda \not\in \varsigma$ then
$(q, \varsigma \setminus\{\neg \lambda \}, q') \in \varrho$, and
\item
whenever $\lambda \in \varsigma$, if $q' = \inquotes{\top}$ then
$(q, \varsigma \setminus\{\lambda \}, q_{+}) \in \varrho$, and if
$q' = \inquotes{\bot}$ then
$(q, \varsigma \setminus\{\lambda\}, q_{-}) \in \varrho$.
\end{compactenum}
\end{definition}
A word $w = \varsigma_0, \varsigma_1, \dots, \varsigma_{n-1}\in \Sigma^+$ is \emph{well-formed} if there are no (negated) constraints in $\varsigma_0$ that mention $V_{{\mathit{pre}}}$.
We next define the notion of consistency to relate words $w\inn\Sigma^+$ as above (where each $\varsigma_i$ is a set of constraints) with those traces $\tau = \alpha_0, \alpha_1, \dots, \alpha_{n-1}$ s.t., at each step, the assignment $\alpha_i$ satisfies $\varsigma_{i}$, i.e., the traces fitting $w$.
To that end, for assignments $\alpha$ and $\alpha'$ with domain $V$, define for all $v\in V$ the assignment $\combine{\alpha}{\alpha'}$ with domain $V_{{\mathit{cur}}} \cup V_{{\mathit{pre}}}$ as
$\combine{\alpha}{\alpha'}(\pre{v}) = \alpha(v)$ and
$\combine{\alpha}{\alpha'}(\cur{v}) = \alpha'(v)$.
\begin{definition}
A well-formed word $\varsigma_0, \varsigma_1,\dots, \varsigma_{n-1} \in \Sigma^+$ is \emph{consistent} with a trace $\alpha_0, \alpha_1, \dots, \alpha_{n-1}$ if $\alpha_0 \models \varsigma_0$ and
$\combine{\alpha_{i-1}}{\alpha_{i}} \models \varsigma_i$
for all $0 < i < n$.
\end{definition}
The key property of $\NFA$ is stated in the following theorem: a word $w$ is accepted iff all the traces captured by $w$ satisfy $\psi$.
The proof can be found in the appendix.
\begin{restatable}{theorem}{lemmaNFA}
\label{lem:automaton:acceptance}
Given $\psi\inn\mathcal L$, a trace $\tau$ and a well-formed word $w\inn \Sigma^+$ consistent with $\tau$, $\mathcal{N}_{\psi_\back}$ accepts $w$ iff $\tau \models \psi$.
\end{restatable}
However, $\NFA[\psi_\back]$ is not deterministic, which is inconvenient for monitoring.
Thus, we next build an equivalent DFA $\DFA[\psi_\back]$ (exponentially larger in the worst case), using a subset construction,
and a restricted alphabet:
Let $C_{\mathit{cur}} \subseteq C$ be the subset of constraints in $\psi_\back$ that mention only $V_{\mathit{cur}}$ (but not $V_{\mathit{pre}}$).
Let the alphabet $\Theta \subseteq \Sigma$ consist of all
maximal satisfiable subsets of $C^\pm$, and
$\Theta_{\mathit{cur}} \subseteq \Sigma$ consist of all maximal satisfiable subsets of $C_{\mathit{cur}}^\pm$.
\begin{definition}
For $\NFA[\psi_\back]\,{=}\,(Q, \Sigma, \varrho, q_0, Q_F)$,
let $\DFA[\psi_\back] = (\mathcal Q, \Theta \cup \Theta_{\mathit{cur}}, \Delta, \{q_0\}, \mathcal Q_F)$ where
$\mathcal Q = 2^Q$,
$\mathcal Q_F$ consists of all $P\,{\subseteq}\,Q$ such that $P\,{\cap}\,Q_F\,{\neq}\,\emptyset$, and the transition function is given by
$\Delta(\{q_0\}, \varsigma_0) = \{q' \mid (q_0,\varsigma', q') \inn \varrho\text{ and }\varsigma'\,{\subseteq}\,\varsigma_0\}$ for all $\varsigma_0 \in \Theta_{\mathit{cur}}$, and
$\Delta(P, \varsigma) = \{q' \mid q\in P\text{, }(q,\varsigma', q') \in \varrho\text{ and }\varsigma' \subseteq \varsigma\}$ for all $\varsigma \in \Theta$ and $P \neq \{q_0\}$.
\end{definition}
Note that $\Delta$ is defined either $(i)$ for the initial state $\{q_0\}$ and $\varsigma \in \Theta_{\mathit{cur}}$, i.e., a constraint set not mentioning $V_{\mathit{pre}}$, or $(ii)$ for
a non-initial state and $\varsigma \in\Theta$.
This distinction ensures that $\DFA[\psi_\back]$ accepts only well-formed words, and
$\DFA$ is \emph{deterministic} in that
for every $w \in \Theta_{\mathit{cur}} \Theta^*$ there is a unique state
$P$ of $\DFA[\psi_\back]$ such that $\{q_0\} \gotos{w} P$.
In the appendix, we show that $\DFA$ is equivalent to $\NFA$ in the following sense:
\begin{restatable}{lemma}{lemmaDFANFA}
\label{lem:DFA:NFA}
Given a trace $\tau$,
$\DFA$ accepts a word consistent with $\tau$ iff $\NFA$ accepts a word consistent with $\tau$.
\end{restatable}
\begin{example}
\label{exa:lookahead}
The property $\psi = \mathsf{G}\xspace(x' \geq x) \wedge \mathsf{F}\xspace (x = 2)$ is
equivalent to $\psi_\back = \mathsf{G}\xspace\mathsf{X}_w\xspace (\cur{x}\,{\geq}\,\pre{x}) \wedge \mathsf{F}\xspace (\cur{x}\,{=}\,2)$; it demands that $x$ is increasing, and at some point has value 2.
We get the following NFA $\NFA[\psi_\back]$:
\noindent
\resizebox{\columnwidth}{!}{
\begin{tikzpicture}[node distance=44mm]
\node[state, minimum width=6mm] (0) {$q_0$};
\node[state, minimum width=6mm, right of =0] (1) {$q_1$};
\node[state, right of=1, minimum width=6mm, final] (top) {$q_{+}$};
\node[state, below of=1, yshift=25mm, minimum width=6mm] (bot) {$\bot$};
\node[state, right of=bot, minimum width=6mm] (2) {$q_2$};
\draw[edge] ($(0) + (-.3,.4)$) -- (0);
\draw[edge] (0) -- node[action, above] {$\{\cur{x} \neq 2\}$} (1);
\draw[edge, rounded corners] (0) -- ($(0)+(0,.5)$) -- ($(top) + (0,.42)$) -- node[action, right] {$\{ \cur{x}\,=\,2\}$} (top);
\draw[edge, rounded corners] (0) |- ($(2) + (0,-.45)$) -- node[action, right] {$\{ \cur{x}\,{=}\,2\}$} (2);
\draw[edge, rounded corners] (0) |- node[action, below, near end] {$\{ \cur{x}\,\neq\,2\}$} (bot);
\draw[edge] (1) -- node[action, right, near start, anchor=west, yshift=-2mm] {\begin{tabular}{r}$\{\cur{x}\,{\geq}\,\pre{x},\quad$\\$\cur{x}\,{=}\,2\}$\end{tabular}} (2);
\draw[edge] (1) to node[action, above] {$\{\cur{x}\,{=}\,2,\cur{x}\,{\geq}\,\pre{x}\}$} (top);
\draw[edge] (1) -- node[action, left, pos=.72, xshift=3mm] {\begin{tabular}{r}$\{\cur{x}\,{<}\,\pre{x}\}$\\$\{\cur{x}\,{\geq}\,\pre{x},\,\cur{x}\,{\neq}\,2\}$\end{tabular}} (bot);
\draw[->] (1) to[loop, in=250, out=200, looseness=8] node[action, left, xshift=1mm, anchor=east, yshift=1mm] {$\{\cur{x}\,{\geq}\,\pre{x},\:\cur{x}\,{\neq}\,2\}$} (1);
\draw[->] (2) to[loop right, looseness=10] node[action, right, anchor=west, xshift=-7mm, yshift=4mm] {$\{\cur{x}\,{\geq}\,\pre{x}\}$} (2);
\draw[->] (2) -- node[action, right] {$\{ \cur{x}\,{\geq}\,\pre{x}\}$} (top);
\draw[->] (bot) to[loop, in=250, out=200, looseness=8] (bot);
\draw[->] (2) -- node[action, below] {$\{\cur{x}\,{<}\,\pre{x}\}$} (bot);
\end{tikzpicture}
}
\noindent
In the respective DFA $\DFA[\psi_\back]$ below,
$\Theta_{\mathit{cur}}$ consists of $\{\cur{x}\,{=}\,2\}$ and
$\{\cur{x}\,{\neq}\,2\}$, and
$\Theta$ of all four combinations of
$\cur{x}\,{=}\,2$ or
$\cur{x}\,{\neq}\,2$ with $\cur{x}\,{\geq}\,\pre{x}$ or $\cur{x}\,{<}\,\pre{x}$:
\noindent
\resizebox{\columnwidth}{!}{
\begin{tikzpicture}[node distance=49mm]
\node[state] (A) {$A$};
\node[state, right of =A, final] (B) {$B$};
\node[state, below of=A, yshift=25mm] (C) {$C$};
\node[state, right of=C] (E) {$D$};
\draw[edge] ($(A) + (-.4,0)$) -- (A);
\draw[edge] (A) -- node[action, below] {$\{\cur{x}\,{=}\,2\}$} (B);
\draw[edge] (A) -- node[action, left] {$\{\cur{x}\,{\neq}\,2\}$} (C);
\draw[->] (B) to[loop right, looseness=8]
node[action, right, anchor=west] {$\{\cur{x}\,{\geq}\,\pre{x}, \cur{x}{=}2\}$}
node[action, right, anchor=west, yshift=-5mm] {$\{\cur{x}\,{\geq}\,\pre{x}, \cur{x}{\neq}2\}$} (B);
\draw[edge] (B) --
node[action, right, anchor=west] {$\{\cur{x}\,{<}\,\pre{x}, \cur{x}{=}2\}$}
node[action, right, anchor=west, near end] {$\{\cur{x}\,{<}\,\pre{x}, \cur{x}{\neq}2\}$} (E);
\draw[->] (C) to[loop left, looseness=8] node[action, left, anchor=east] {$\begin{array}{r@{}l}\{\cur{x}\,{\geq}\,\pre{x},\\ \,\cur{x}\,{\neq}\,2\}\end{array}$} (C);
\draw[->] (C) to node[action, left, anchor=east, pos=.6] {$\begin{array}{r@{}l}\{\cur{x}\,&{\geq}\,\pre{x},\\\,\cur{x}\,&{=}\,2\}\end{array}$} (B);
\draw[->] (C) to
node[action, above, xshift=2mm] {$\{\cur{x}\,{<}\,\pre{x}, \cur{x}{=}2\}$}
node[action, below, xshift=2mm] {$\{\cur{x}\,{<}\,\pre{x}, \cur{x}{\neq}2\}$} (E);
\draw[->] (E) to[loop right, looseness=8] node[action, right] {$\Theta$} (E);
\end{tikzpicture}
}
\noindent
Here $A$ corresponds to $\{q_0\}$,
$B$ to $\{q_2, q_+\}$ (equivalent to $\{q_2, q_+, \bot\}$),
$C$ to $\{q_1, \bot\}$, and
$D$ to $\{\bot\}$.
\end{example}
\section{Monitoring properties without lookahead}
\label{sec:nolookahead}
In this section we show that monitoring properties without lookahead is solvable, and
a monitoring structure is given by
the DFA $\DFA[\psi_\back] = (\mathcal Q, \Theta, \delta, \{q_0\}, \mathcal Q_F)$ (note that without lookahead, $\Theta_{\mathit{cur}}$ and
$\Theta$ as defined in the last section coincide). We illustrate the construction on an example.
\begin{example}
\label{exa:DFA}
Let $\psi = (y\,{\geq}\,0) \U (x\,{>}\,y \wedge \mathsf{G}\xspace (x\,{>}\,y))$.
Then $\psi_{\mathit{back}}$
is as $\psi$ but where $x$ is replaced by $\cur{x}$ and $y$ by $\cur{y}$.
As there is no lookahead, no confusion can arise, so we write
$x$ for $\cur{x}$ and $y$ for $\cur{y}$.
We get the following NFA $\NFA[\psi_\back]$ with alphabet $\smash{\Sigma=2^{C^\pm}}$ for $C = \{x\,{>}\,y,\:y\,{\geq}\,0\}$:\\
{\centering
\resizebox{.65\columnwidth}{!}{
\begin{tikzpicture}[node distance=35mm]
\node[state, minimum width=6mm] (1) {1};
\node[state, right of=1, minimum width=6mm, final] (2) {2};
\draw[edge] ($(1) + (-.3,.2)$) -- (1);
\draw[edge] (1) -- node[action, above] {$\{x\,{>}\,y\}$} (2);
\draw[->] (1) to[loop left, looseness=8] node[action, left, anchor=east] {$\{y\,{\geq}\,0\}$} (1);
\draw[->] (2) to[loop right, looseness=8] node[action, right, anchor=west] {$\{x\,{>}\,y\}$} (2);
\end{tikzpicture}
}
}\\
The next DFA $\DFA[\psi_\back]$ is equivalent; its alphabet consists of all maximal satisfiable subsets of $C^\pm$,
i.e.,
$\{y{\geq}0,\,x{>}y\}$,
$\{y{\geq}0,\,x{\leq}y\}$,
$\{y{<}0,\,x{>}y\}$, and
$\{y{<}0,\,x{\leq}y\}$. \\
{\centering
\resizebox{\columnwidth}{!}{
\begin{tikzpicture}[node distance=35mm]
\node[state, minimum width=7mm, cvcolor, scale=.8] (1) {1};
\node[state, right of=1, minimum width=7mm, cscolor, final, scale=.8] (2) {2};
\node[state, below of=1, minimum width=7mm, cscolor, final, scale=.8, yshift=18mm] (12) {12};
\node[state, right of=12, minimum width=7mm, pvcolor, scale=.8] (bot) {$\emptyset$};
\draw[edge] ($(1) + (0,.4)$) -- (1);
\draw[edge] (1) -- node[action, above, yshift=-.9mm] {$\{y\,{<}\,0,\,x\,{>}\,y\}$} (2);
\draw[edge, bend right=10] (1) to node[action, left, anchor=east] {$\{y\,{\geq}\,0,\,x\,{>}\,y\}$} (12);
\draw[edge] (1) -- node[action, right, pos=.2, xshift=1mm] {$\{y\,{<}\,0,\,x\,{\leq}\,y\}$} (bot);
\draw[->] (1) to[loop left, looseness=8] node[action, left, anchor=east] {$\{y\,{\geq}\,0,\:x\,{\leq}\,y\}$} (1);
\draw[->] (12) to[loop left, looseness=8] node[action, left, anchor=east] {$\{y\,{\geq}\,0,\:x\,{>}\,y\}$} (12);
\draw[->, bend right=10] (12) to node[action, right, very near start] {$\{y\,{\geq}\,0,\:x\,{\leq}\,y\}$} (1);
\draw[->] (2) to[loop above, looseness=8, pos=.8]
node[action, right] {$\{y\,{\geq}\,0,\:x\,{>}\,y\},\,\{y\,{<}\,0,\,x\,{>}\,y\}$} (2);
\draw[->] (bot) to[loop right, looseness=8] node[action, right, anchor=west, near start, xshift=1mm] {$\Theta$} (bot);
\draw[->] (2) --
node[action, right, anchor=west, pos=.7] {$\{y\,{\geq}\,0,\,x\,{\leq}\,y\}$}
node[action, right, anchor=west, pos=.4] {$\{y\,{<}\,0,\,x\,{\leq}\,y\}$} (bot);
\draw[->] (12) -- node[action, below, yshift=.9mm] {$\{y\,{<}\,0,\,x\,{\leq}\,y\}$} (bot);
\draw[->, rounded corners] (12) -- ($(12) + (0,-.35)$) -| ($(2) + (1.7,0)$) -- node[action, right, xshift=12mm, yshift=-15mm] {$\{y\,{<}\,0,\,x\,{>}\,y\}$} (2);
\end{tikzpicture}
}
}
\end{example}
Next, we formalize how to use $\DFA[\psi_\back]$ as a monitor.
We call a state $ P'$ \emph{reachable} from $P$ if $P \to^*_w P'$ for some $w$.
\begin{theorem}
\label{thm:lookahead0:monitoring}
If a word $w \inn \Theta^+$ is consistent with a trace $\tau$ and $P$ is the state
in $\DFA[\psi_\back]$ such that
$\{q_0\} \gotos{w} P$,
{
\setlength{\parindent}{0em}
\setdefaultleftmargin{0em}{2em}{}{}{}{}
\begin{compactitem}[]
\item $\tau \models \llbracket \psi\,{=}\,\text{\textsc{ps}}\rrbracket$
if only final states are reachable from $P$,
\item $\tau \models \llbracket \psi\,{=}\,\textsc{cs}\rrbracket$
if $P\inn \mathcal Q_F$ but $P \to^* P'$ for some $P'\not\in \mathcal Q_F$,
\item $\tau \models \llbracket \psi\,{=}\,\textsc{cv}\rrbracket$
if $P\,{\not\in}\, \mathcal Q_F$ but $P \to^* P'$ for some $P'\in \mathcal Q_F$,
\item $\tau \models \llbracket \psi\,{=}\,\textsc{pv}\rrbracket$
if no final state is reachable from $P$.
\end{compactitem}
}
\end{theorem}
\begin{proof}
By Lems.~\ref{lem:DFA:NFA} and
\ref{lem:automaton:acceptance}, $\tau \models \psi$ iff $P$ is final.
(Case $\text{\textsc{ps}}$:) $P$ has no path to a non-final state.
Towards contradiction, assume $\tau'$ exists s.t. $\tau\tau' \not\models \psi$.
By Lems.~\ref{lem:automaton:acceptance} and \ref{lem:DFA:NFA}, $\DFA[\psi_\back]$ does not accept a word consistent with $\tau\tau'$.
By Lem.~\ref{lem:word:for:trace},
there is a unique word $\bar w \in \Theta^+$ consistent with $\tau\tau'$
s.t. $\{q_0\} \to^*_{\bar w} P'$ in $\DFA[\psi_\back]$ for some $P'$, which cannot be accepting.
By determinism,
we can write $\bar w = ww'$ s.t. $\{q_0\} \to^*_w P \to^*_{w'} P'$, contradicting that only final states are reachable from $P$.
Thus $\tau'$ cannot exist.
(Case $\textsc{cs}$:) let $P \to^*_{w'} P'$ for a non-final state $P'$.
Sets in $\Theta$ are satisfiable, so there is a trace $\tau'$ s.t. $w'$ is consistent with $\tau'$, and $ww'$ with $\tau\tau'$.
By Lem.~\ref{lem:word:for:trace}, $ww'$ is the unique word in $\Theta^*$ consistent with $\tau\tau'$, and is not accepted. By Lems.~\ref{lem:DFA:NFA} and~\ref{lem:automaton:acceptance}, $\tau\tau' \not \models \psi$ thus $\tau \models \llbracket \psi = \textsc{cs}\rrbracket$.
The other two cases are similar.
\end{proof}
\noindent
Thm.~\ref{thm:lookahead0:monitoring} implies that monitoring is solvable,
and the monitoring state only depends on the DFA state matching a trace.
\begin{example}
Consider the property of Ex.~\ref{exa:DFA}.
The following example trace is interleaved with the state reached by the corresponding word in $\DFA[\psi_\back]$, and the monitoring state:\\[1ex]
$\begin{array}{@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}}
\begin{array}{@{}c@{}} 1\\ \phantom{\textsc{cv}} \end{array}
& \domino{x}{0}{y}{0} &
\begin{array}{@{}c@{}} 1\\ \textsc{cv} \end{array}
& \domino{x}{0}{y}{3} &
\begin{array}{@{}c@{}} 1\\ \textsc{cv} \end{array} & \domino{x}{4}{y}{3} &
\begin{array}{@{}c@{}} 12\\ \textsc{cs} \end{array} & \domino{x}{0}{y}{3} &
\begin{array}{@{}c@{}} 1\\ \textsc{cv} \end{array} & \domino{x}{0}{y}{-1} &
\begin{array}{@{}c@{}} 2\\ \textsc{cs} \end{array}
\end{array}$
\\
Each DFA state corresponds to a monitoring state,
as indicated by the colors in Ex.~\ref{exa:DFA}: non-final states are $\textsc{cv}$ if a final state is reachable (yellow), $\textsc{pv}$ otherwise (red); final states are $\textsc{cs}$ if a non-final state is reachable (blue), $\text{\textsc{ps}}$ otherwise.
\end{example}
\section{Solvable cases for properties with lookahead}
In this section we study the more involved case of properties with lookahead 1.
The next example shows that the approach from the last section does not work for this case:
\begin{example}
\label{exa:lookahead:complicates:things}
Consider the property and DFA from Exa.~\ref{exa:lookahead} and the following trace,
interleaved with the reached state in $\DFA[\psi_\back]$ as well as the monitoring state for every prefix:\\[1ex]
$\begin{array}{@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}c@{\:}}
\begin{array}{@{}c@{}} A\\ \phantom{\textsc{cv}} \end{array}
& \{x=0\} &
\begin{array}{@{}c@{}} C\\ \textsc{cv} \end{array}
& \{x=1\}&
\begin{array}{@{}c@{}} C\\ \textsc{cv} \end{array}
& \{x=3\} &
\begin{array}{@{}c@{}} C\\ \textsc{pv} \end{array}
& \{x=4\} &
\begin{array}{@{}c@{}} C\\ \textsc{pv} \end{array}
\end{array}$\\
The reached DFA state is the same for every prefix, even though the monitoring state changes.
\end{example}
Note that while the state $P$ reached by a trace $\tau$ in $\DFA[\psi_\back]$ can still tell whether $\tau$ satisfies $\psi$, reachability of (non)final states from $P$
is no longer sufficient to predict whether the trace can be \emph{extended} to satisfy $\psi$.
We therefore develop an enhanced monitoring structure.
To simplify notation, we assume that $\psi$ is the result of the $\back(\cdot)$ transformation, i.e., a property over variables $V_{\mathit{pre}} \cup V_{\mathit{cur}}$.
Moreover, we assume throughout this section that $\DFA$ is a DFA for $\psi$
of the form $\DFA= (\mathcal Q, \Theta\,{\cup}\,\Theta_{\mathit{cur}}, \Delta, \{q_0\}, \mathcal Q_F)$.
The idea is to abstract the variable configurations that are relevant for verification by a set of formulas.
This abstraction requires some additional notation:
First, let $V_0 = \{v_0 \mid v\inn V\}$ be a copy of $V$, it will act
as placeholders for the initial values of the variables $V$.
We write $\varphi_{\mathit{init}}$
for the formula $\varphi_{\mathit{init}} = \bigwedge_{v\in V}v = v_0$.
For a formula $\varphi$ with free variables $V_0 \cup V$, let $\varphi(\vec U)$ denote the formula
where $\vec V$ is replaced by $\vec U$, but $V_0$ is not replaced (with denote by $\vec V$ a fixed ordering of $V$).
For a set of constraints $C$ with free variables $V_{\mathit{pre}} \cup V_{\mathit{cur}}$,
let $C(\vec U, \vec V)$
denote the constraints where $\vec V_{\mathit{pre}}$ is replaced by $\vec U$ and $\vec V_{\mathit{cur}}$ is replaced by $\vec V$.
\begin{definition}
\label{def:update}
For a formula $\varphi$ with free variables $V_0 \cup V$
and a set of constraints $C$ with free variables $V_{\mathit{pre}} \cup V_{\mathit{cur}}$,
let
$\smash{\update(\varphi, C) = \exists \vec U. \varphi(\vec U) \wedge \bigwedge C(\vec U, \vec V)}$.
\end{definition}
Both $\varphi$ and $\update(\varphi, C)$ have free variables $V_0 \cup V$.
Although $\update$ introduces existential quantifiers, there is an equivalent quantifier-free formula for $\update(\varphi, C)$: linear arithmetic has quantifier elimination.
E.g., for $\varphi = (x\,{=}\,x_0 \wedge x_0\,{\neq}\,2)$ and
$C = \{\cur{x}\,{\geq}\,\pre{x}, \cur{x}\,{=}\,2\}$, we have
$\update(\varphi, C) = \exists u.\: u\,{=}\,x_0 \wedge x_0\,{\neq}\,2 \wedge
x\,{\geq}\,u \wedge x\,{=}\,2$, which is equivalent to $x_0 < 2 \wedge x=2$.
In order to design a monitoring structure,
we build a \emph{constraint graph} which, intuitively,
connects in a graph all variable dependencies
(described by formulas) emerging from a state $P_0$ in the DFA, and where ${V_0}$ acts as placeholder for the initial variable values.
The constraint graph is parameterized by an equivalence relation $\sim$ on formulas
used to reduce its size.
Our correctness proof will require further properties of $\sim$
but a default choice is the logical equivalence relation $\equiv$.
\begin{definition}\label{def:cg}
A \emph{constraint graph} $\CG_\psi(P_0, \sim)$ for $\DFA$ and a DFA state $P_0 \inn \mathcal Q$
is a triple
$\langle S, s_0, \gamma, S_F\rangle$ where the node set $S$
consists of tuples $(P, \varphi)$ of a state $P\inn \mathcal Q$ and a formula $\varphi$ with free variables $V_0 \cup V$,
and $\gamma \subseteq S \times \Sigma \times S$. Then, $S$ and $\gamma$ are inductively defined as follows:
\begin{compactitem}
\item[$(i)$] $s_0 = (P_0, \varphi_{\mathit{init}})$ is the initial node and $s_0\in S$;
\item[$(ii)$] if $s = (P,\varphi) \in S$ and $P \goto{\varsigma} P'$ in $\DFA$ such that
$\update(\varphi, \varsigma)$ is satisfiable,
there is some $s' = (P', \varphi')\in S$
with $\varphi' \sim \update(\varphi, \varsigma)$, and
$s \goto{\varsigma} s'$ is in $\gamma$;
\item[$(iii)$] $(P, \varphi)\in S$ is in the set of final nodes $S_F$ iff $P\inn \mathcal Q_F$.
\end{compactitem}
\end{definition}
We simply write $\CG_\psi(P_0)$ for $\CG_\psi(P_0, \equiv)$.
The constraint graph $\CG_\psi(C)$ for the DFA $\DFA[\psi_\back]$ from
Ex.~\ref{exa:lookahead} is shown in Fig.~\ref{fig:cg}.
For readability, edge labels are combined; e.g. the two
edges from $B$ to $D$ labeled
$\{\cur{x}\,{<}\,\pre{x}, \cur{x}\,{=}\,2\}$ and $\{\cur{x}\,{<}\,\pre{x}, \cur{x}\,{\neq}\,2\}$ are combined to one edge labeled $\{\cur{x}\,{<}\,\pre{x}\}$.
\longversion{The graphs $\CG_\psi(A)$ and $\CG_\psi(B)$ are shown in Ex.~\ref{exa:cgs} in the appendix.}{}
\begin{figure}
\begin{tikzpicture}[node distance = 17mm, ->,>=stealth',shorten >=1pt]
\node[node, below of=0, xshift=-55mm] (2)
{\cgnode{$C$}{$x\,{=}\,x_0$}};
\node[node, below of=2, xshift=-35mm] (21)
{\cgnode{$C$}{$x \geq x_0 \wedge x\,{\neq}\,2$}};
\node[node, below of=2, final] (22)
{\cgnode{$B$}{$x_0\,{\leq}\,2 \wedge x\,{=}\,2$}};
\node[node, right of=22, xshift=16mm] (23)
{\cgnode{$D$}{$x\,{<}\,x_0$}};
\node[node, below of=23] (231)
{\cgnode{$D$}{$\top$}};
\node[node, below of=22] (222)
{\cgnode{$D$}{$x_0\,{\leq}\,2$}};
\node[node, below of=21, final, xshift=-7mm] (221)
{\cgnode{$B$}{$x_0\,{\leq}\,2 \wedge x \geq 2$}};
%
\draw[goto, bend right=15] (2) to node[action, above, anchor=south east, near start]{$\{\cur{x}{\geq}\pre{x}\wedge \cur{x}{\neq}2\}$} (21);
\draw[goto] (2) to node[action, right, anchor= west]{\begin{tabular}{@{}c@{}}$\{\cur{x}{\geq}\pre{x}$\\${}\wedge \cur{x}{=}2\}$\end{tabular}} (22);
\draw[goto, bend left=15] (2) to node[action, above, near start, anchor=south west]{$\{\cur{x}{<}\pre{x}\}$} (23);
\draw[goto, loop above, out=95, in=66, looseness=10] (23) to node[action, above, xshift=4mm]{$\{\cur{x}{<}\pre{x}\}$} (23);
\draw[goto] (23) to node[action, right]{$\{\cur{x}{\geq}\pre{x}\}$} (231);
\draw[goto] (22) to node[action, above, anchor=south west, near end]{$\{\cur{x}{<}\pre{x}\}$} (222);
\draw[goto] (22) to node[action, right, near end, xshift=2mm]{$\{\cur{x}{\geq}\pre{x}\}$} (221.100);
\draw[goto, loop right, out=175, in=185, looseness=7] (221) to node[action, above, xshift=-4mm, yshift=1mm]{$\{\cur{x}{\geq}\pre{x}\}$} (221);
\draw[goto] (221) to node[action, below]{$\{\cur{x}{<}\pre{x}\}$} (222);
\draw[goto, loop left, out=150, in=170, looseness=3] (21) to node[action, above]{$\{\cur{x}{\geq}\pre{x}\wedge \cur{x}{\neq}2\}$} (21);
\draw[goto, bend right=20, in=191] (21) to node[action, below, anchor=north east, near start, xshift=-1mm, yshift=1mm]{$\{\cur{x}{\geq}\pre{x}\wedge \cur{x}{=}2\}$} (22);
\draw[goto, loop right, out=13, in=-5, looseness=7] (222) to node[action, right]{$\widehat \Sigma$} (222);
\end{tikzpicture}
\caption{\label{fig:cg}Constraint graph $\CG_\psi(C)$.}
\end{figure}
The construction in Def.~\ref{def:cg} need not terminate as infinitely many formulas may occur, but we will show in the next section that termination is guaranteed for several relevant cases.
\begin{definition}
\label{def:future}
For $\psi$ with DFA $\DFA$, a state $P_0$ in $\DFA$, and
$G:= \CG_\psi(P_0,\sim)$ with node set $S$, let\\[.5ex]
$\begin{array}{r@{\,}l}
\textsc{FSat}(G) =&
\exists \vec V. \bigvee \{\varphi \mid (P, \varphi)\in S \text{ is a final node} \}
\\
\textsc{FUns}(G) =&
\exists \vec V. \bigvee \{\varphi \mid (P, \varphi) \in S \text{ is a non-final node} \}
\end{array}$
\end{definition}
Intuitively, $\textsc{FSat}(G)$ expresses a condition on the variable values when a final state in $\DFA$ is reachable from $P_0$; dually, $\textsc{FUns}$ gives a condition for reachability of non-final states.
This leads to the following monitoring procedure:
\begin{algorithmic}[1]
\Procedure{monitor}{$\psi$, $\tau$}
\State compute $\psi_\back$ and $\DFA[\psi_\back]$ \Comment{or take from cache}
\State $w \gets$ word in $\Theta_{\mathit{cur}}\Theta^*$ consistent with $\tau$
\State $P \gets$ state in $\DFA[\psi_\back]$ such that $\{q_0\}\gotos{w} P$
\State $G\gets\CG_\psi(P, \sim)$ \Comment{or take from cache}
\State $\alpha_n \gets $ last assignment in $\tau$
\If{$P$ accepting in $\DFA[\psi_\back]$}
\State \textbf{return} ($\textsc{cs}$ \textbf{if} $\alpha_n \models\textsc{FUns}(G)$ \textbf{else} $\text{\textsc{ps}}$)
\EndIf
\State \textbf{else return} ($\textsc{cv}$ \textbf{if} $\alpha_n \models\textsc{FSat}(G)$ \textbf{else} $\textsc{pv}$)
\EndProcedure
\end{algorithmic}
When monitoring multiple traces against a property $\psi$,
the mo\-ni\-toring structures (DFA, constraint graphs for every state, $\textsc{FSat}$, $\textsc{FUns}$) can be computed once and for all upfront. Instead, the procedure shown above is intended as a \emph{lazy} implementation, where the structures are computed when needed and cached.
\begin{example}
For
$\psi_{\mathit{back}} = \mathsf{G}\xspace\mathsf{X}_w\xspace (\cur{x}\,{\geq}\,\pre{x}) \wedge \mathsf{F}\xspace (\cur{x}\,{=}\,2)$
from Exa.~\ref{exa:lookahead}, by the graph in Fig.~\ref{fig:cg} we have
$\textsc{FSat}(C) = \exists x. (x_0\,{\leq}\,2 \wedge x\,{\geq}\,2) \vee (x_0\,{\leq}\,2 \wedge x\,{=}\,2)$, equivalent to $x_0 \leq 2$. We show how the procedure distinguishes two prefixes of the trace from Exa.~\ref{exa:lookahead:complicates:things} with different monitoring state:
\begin{compactitem}
\item
Trace $\tau_1 = \langle\{x\,{=}\,0\}\rangle$ corresponds to $w = \langle\{\cur{x}\,{\neq}\,2\}\rangle$, leading to the non-accepting state $C$.
As $\{x\,{=}\,0\} \models \textsc{FSat}(G_C)(V) = x\leq 2$, we have
$\tau_1 \models \llbracket \psi{=}\textsc{cv} \rrbracket$.
\item
Trace $\tau_3 =\langle\{x\,{=}\,0\}, \{x\,{=}\,1\}, \{x\,{=}\,3\}\rangle$ matches
$\langle\{\cur{x}\,{\neq}\,2\},$ $\{\cur{x}\,{\neq}\,2, \cur{x}{\geq}\pre{x}\}^2\rangle$, leading again to state $C$.
However,
$\{x\,{=}\,3\} \not\models x\leq 2$, so
$\tau_3 \models \llbracket \psi{=}\textsc{pv} \rrbracket$.
\end{compactitem}
\end{example}
\paragraph{Correctness.}
To prove correctness,
we need some additional notions. First, we define \emph{history constraints}
to capture the formulas obtained from stacked $\update$
operations:
\begin{definition}\label{def:history constraint}
For $w\,{=}\,\varsigma_0,\dots, \varsigma_{n-1}$ in $\Theta^*$,
the \emph{history constraint} $h(w)$ is given by
$h(w) = \varphi_{\mathit{init}}$ if $n= 0$, and if $n\,{>}\,0$ then
$h(w) = \update(h(\langle\varsigma_0,\dots, \varsigma_{n-2}\rangle), \varsigma_{n-1})$.
\end{definition}
There is the correspondence between satisfying assignments of
$h(w)$ and traces that satisfy
the constraints in $w$:
\begin{restatable}{lemma}{lemmaabstraction}
\label{lem:abstraction}
For $w\in \Theta^*$ of length $n$,
$h(w)$ is satisfied by assignment $\nu$ iff
$\langle\emptyset\rangle\,{\cdot}\,w$ is consistent with a trace $\alpha_0, \dots, \alpha_{n}$
such that $\nu(v_0)\,{=}\, \alpha_0(v)$ and $\nu(v)\,{=}\, \alpha_n(v)$ for all $v\in V$.
\end{restatable}
Next, we define a \emph{history set} to capture all variable configurations that are relevant for monitoring. More precisely, it collects pairs of history constraints for words and the state that they lead to, but where equivalent pairs are eliminated:
\begin{definition}
A \emph{history set} for $\DFA$ is a minimal set $\Phi$ of pairs $(P, \varphi)$
of a state $P \inn \mathcal Q$ and a formula $\varphi$ such that for all $P'$ and $w\in \Theta_{\mathit{cur}}\Theta^*$ with $P \gotos{w} P'$ in $\DFA$, there is a $(P',\varphi) \in \Phi$ s.t.
$h(w) \equiv \varphi$.
\end{definition}
If $\Phi$ is finite, it represents an abstract representation of the relevant variable configurations and can be used to build the states of the constraint graph.
For succinctness, we pair a history set with an equivalence relation.
\begin{definition}
\label{def:summary}
A \emph{summary} for $\DFA$
is a pair $(\Phi, \sim)$ of a history set $\Phi$ for $\DFA$
and equivalence relation $\sim$ on $\Phi$ such that
\begin{compactenum}[(1)]
\item $\sim$ contains $\equiv$ on formulas in $\Phi$ and is decidable,
\item for all $(q,\varphi),(q,\psi) \in \Phi$ such that $\varphi \sim \psi$,
\begin{inparaenum}
\item if $\alpha \models \varphi$, there is some $\alpha'$ such that $\alpha' \models \psi$ and $\alpha(u) = \alpha'(u)$ for all $u \in V_0$, and
\item for all
transitions $q \goto{\varsigma} q'$,
$\update(\varphi,\varsigma) \sim \update(\psi,\varsigma)$.
\end{inparaenum}
\end{compactenum}
\end{definition}
The summary $(\Phi, {\sim})$ is \emph{finite} if
$\sim$ has finitely many equivalence classes, and
$\psi$ \emph{has finite summary} if a finite summary exists for $\DFA$.
For a word $w\,{=}\, \varsigma_1, \dots, \varsigma_n$, we write $(P_0, \varphi_{\mathit{init}}) \gotos{w} (P, \varphi)$
if there is a path
$(P_0, \varphi_{\mathit{init}}) \goto{\varsigma_1} \dots \dots \goto{\varsigma_n} (P, \varphi)$
in $\CG_\psi(P_0, \sim)$.
The next lemma states that a path in the CG emulates a path in $\DFA$ and leads to a state that is equivalent to a history constraint.
\begin{restatable}{lemma}{lemmacg}
\label{lem:cg}
Let $(\Phi, \sim)$ be a summary for $\DFA$.
\begin{inparaenum}[(a)]
\item If $\CG_\psi(P_0, \sim)$ has a path $(P_0, \varphi_{\mathit{init}}) \gotos{w} (P, \varphi)$ then
$P_0 \gotos{w} P$ in $\DFA$ and $\varphi \sim h(w)$ is satisfiable, and
\item if $P_0 \gotos{w} P$ and $h(w)$ is satisfiable then there is a path
$(P_0, \varphi_{\mathit{init}}) \gotos{w} (P, \varphi)$ for some $\varphi$ such that $\varphi \sim h(w)$.
\end{inparaenum}
\end{restatable}
\noindent
At this point we are ready to prove our main theorem:
\begin{theorem}
\label{thm:lookahead1:monitoring}
Let $(\Phi, \sim)$ be a summary for $\DFA$.
Given a DFA $\DFA$ for $\psi$ and a trace $\tau$, let $w\in \Theta_{\mathit{cur}}\Theta^*$ be
the word consistent with $\tau$ and
$P$ the $\DFA$ state
s.t. $\{q_0\} \gotos{w} P$. For $G:= \CG_\psi(P, \sim)$ the constraint graph from $P$,
\begin{compactitem}
\item
if $P\,{\in}\,P_F$ then $\tau \models \llbracket \psi{=}\textsc{cs} \rrbracket$ if
$\alpha_n \models \textsc{FUns}(G)(\vec V)$, and $\tau \models \llbracket \psi{=}\text{\textsc{ps}} \rrbracket$ otherwise,
\item
if $P\,{\not\in}\,P_F$ then $\tau \models \llbracket \psi{=}\textsc{cv} \rrbracket$ if
$\alpha_n \models \textsc{FSat}(G)(\vec V)$, and $\tau \models \llbracket \psi{=}\textsc{pv} \rrbracket$ otherwise.
\end{compactitem}
\end{theorem}
\begin{proof}[Proof]
Note that the word $w$ that is
consistent with $\tau$ is unique (cf. Lem.~\ref{lem:word:for:trace}).
Consider the case where $P\,{\in}\,P_F$, so that $\tau \models \psi$ by Lem. \ref{lem:automaton:acceptance} and \ref{lem:DFA:NFA}.
First, suppose $\alpha_n \models \textsc{FUns}(G)(\vec V)$, so
$\alpha_n \models (\exists \vec V.\,\varphi)(\vec V)$
for some non-final node $(P', \varphi)$ of $G$.
Let $u$ be a word s.t. there is a path $(P, \varphi_{\mathit{init}}) \gotos{u} (P', \varphi)$ in
$\CG_\psi(P)$.
By Lem. \ref{lem:cg}, $P \gotos{u} P'$ in $\DFA$ and $\varphi \sim h(u)$.
By Def.~\ref{def:summary}, $\alpha_n \models (\exists \vec V.\,h(u))(\vec V)$, so
there is an assignment $\nu$ with domain
$V_0 \cup V$ s.t. $\nu(v_0) = \alpha_n(v)$ for all $v\inn V$ and
$\nu \models h(u)$.
By Lem. \ref{lem:abstraction}, $\langle \emptyset\rangle\,{\cdot}\,u$ is consistent with some trace $\tau' = \langle \alpha_0', \dots, \alpha_k'\rangle$ s.t. $\nu(v_0) = \alpha_0'(v)$ for all $v\in V$.
Thus, $\alpha_n$ and $\alpha_0'$ coincide, and $wu$ is consistent with
the trace $\tau'' = \langle \alpha_0, \dots, \alpha_n, \alpha_1', \dots, \alpha_k'\rangle$
as $w$ is consistent with $\tau$ and $u$ with $\tau'$.
As $\{q_0\} \gotos{wu} P'$ is not accepting, by Lem. \ref{lem:automaton:acceptance}, $\tau'' \not\models \psi$, hence $\tau \models \llbracket \psi{=}\textsc{cs} \rrbracket$.
Second, let $\alpha_n \not\models \textsc{FUns}(G)(\vec V)$.
Towards a contradiction, suppose there is a trace $\tau' = \langle \alpha_1', \dots, \alpha_k'\rangle$ s.t.
$\tau\tau' \not\models \psi$.
Using Lem.~\ref{lem:word:for:trace}, there is a word $u\in\Theta^*$ s.t. $wu$ is consistent with $\tau\tau'$; let $P'$ the state s.t. $\{q_0\} \gotos{wu} P'$.
By Lem.~ \ref{lem:automaton:acceptance} and \ref{lem:DFA:NFA}, the state $P'$ is not final.
As $wu$ is consistent with $\tau\tau'$, $\langle \emptyset\rangle \cdot u$ is consistent with $\langle\alpha_n\rangle\tau'$, so
by Lem. \ref{lem:abstraction}, the assignment $\nu$ s.t.
$\nu(v_0) = \alpha_n(v)$ and $\nu(v) = \alpha_k'(v)$ for all $v\in V$ satisfies
$h(u)$.
Thus Lem. \ref{lem:cg} implies that $\CG_\psi(P)$ has a path $(P, \varphi_{\mathit{init}}) \gotos{u} (P', \varphi)$ s.t. $\varphi \sim h(u)$.
As $\nu \modelsh(u)$, by Def.~\ref{def:summary}, $\alpha_n \models (\exists.\,\varphi)(\vec V)$ because $\nu(v_0) = \alpha_n(v)$ for all $v\in V$.
As $P'$ is non-final, it follows that $\alpha_n \models \textsc{FUns}(G)$, a contradiction; so $\tau'$ cannot exist.
Thus $\tau \models \llbracket \psi{=}\text{\textsc{ps}} \rrbracket$.
The case where $\tau \not\models \psi$ is dual, using $\textsc{FSat}(G)$.
\end{proof}
Finally, if $\psi$ has a finite summary $(\Phi,\sim)$, by~Lem. \ref{lem:cg} a constraint graph $\CG(P,\sim)$ computed from $\DFA$ can take all nodes from the finitely many equivalence classes of
$\Phi$, so that the constraint graph can be finite. Therefore:
\begin{corollary}
\label{cor:main}
Monitoring is solvable for $\psi\in\mathcal L$ if $\psi$ has finite summary.
\end{corollary}
\section{Concrete criteria for solvability}
We next apply Cor.~\ref{cor:main} to show
solvability of concrete property classes, by restricting the constraint set or control flow.
\paragraph{Monotonicity constraints} (MCs) over variables $\mathcal V$ and domain $D$ have the form $p \odot q$ where $p,q\in {D\,{\cup}\,\mathcal V}$
and $\odot$ is one of $=, \neq, \leq$, or $<$.
We call an LTL$_f$ property whose constraint atoms are MCs over $D$ an \emph{MC$_D$ property}.
Ex.~\ref{exa:lookahead} gives a simple example of an MC property. However,
MC properties are rich enough to capture practically important settings:
For instance, \citeauthor{GeistRS14} (\citeyear{GeistRS14}) model the specification of a fluxgate magnetometer of a Swift UAS system operated by NASA, as linear-time properties with arithmetic comparisons of sensor values, which are all MCs over $\mathbb Q$ (cf. their Table 2).
We have that:
\begin{restatable}{theorem}{theoremMC}
\label{thm:mc}
Monitoring is solvable for MC$_\mathbb Q$ properties.
\end{restatable}
\begin{proof}[Proof (sketch)]
This is shown as in~\cite[Thm.~5.2]{FMW22a}, exploiting that quantifier elimination of MC formulas over $\mathbb Q$ produces MC formulas with the same constants, so that a finite history set exists.
\end{proof}
\paragraph{Integer periodicity constraints} (IPCs) confine the constraint language in a similar way as MCs, but allow equality modulo, and variable-to-variable comparisons are restricted. IPCs are e.g. used in calendar formalisms~\cite{Demri06}.
More precisely, IPC atoms have the form $x = y$, $x \odot d$ for $\odot \in \{=,\neq, <, >\}$, $x \equiv_k y + d$, or $x \equiv_k d$, for variables $x,y$ with domain $\mathbb Z$ and $k,d\in \mathbb N$.
An $\mathcal L$ property over IPC atoms is called an \emph{IPC property}.
The next result is proven similarly as Thm.~\ref{thm:mc}, cf.~\cite[Thm.~4]{FMW22c}.
\begin{theorem}
\label{thm:ipc}
Monitoring is solvable for IPC properties.
\end{theorem}
A simple example of an IPC property is $(x \equiv_7 y+1)\U (x\,{=}\,z)$.
Also e.g. a parallel program as in~\cite[Fig.~3]{HavelundRR19} can be modeled
as an IPC property, where monitoring detect at runtime whether a trace may trigger the race on variable $x$ that the program exhibits.
\paragraph{Control flow restrictions} can be used instead of confining the constraint language to obtain solvability.
\emph{Computation graphs}~\cite{DDV12} were introduced to track dependencies between variable instances at different trace events.
A property $\psi$ is said to have $k$-\emph{bounded lookback}~\cite{FMW22a} if all paths in computation graphs of $\psi$ have length at most $k$, without counting equality edges. Intuitively, this corresponds to forbid variable updates that depend on an unbounded history of values (of the same or of other variables), but only on a $k$-bounded ``moving window".
A property has bounded lookback (BL) if its has $k$-bounded lookback for some $k\geq 0$.
E.g., $\mathsf{G}\xspace (x'\,{>}\,x)$ does not have BL, because there is an unbounded dependency chain between the values of $x$, whereas $\mathsf{F}\xspace (x'\,{>}\,2y) \wedge \mathsf{G}\xspace (x{+}y\,{>}\,0)$ has 1-bounded lookback as variable comparisons span at most one time unit.
Also all properties with lookahead 0 have BL.
Monitoring of BL properties is solvable
because, roughly, the quantifier depth of history constraints is upper-bounded a priori.
A formal definition, proof and examples are in \longversion{the appendix}{\cite{longversion}}.
\begin{restatable}{theorem}{theoremboundedlookback}
\label{thm:bounded:lookback}
Monitoring of BL properties is solvable.
\end{restatable}
\paragraph{Gap-order constraints} (GCs) have the form
$x - y \geq k$ for $x$ and $y$ either variables with domain $\mathbb Z$ or integers, and $k\inn \mathbb N$.
Satisfiability of GC properties is decidable~\cite{BP14}.
However, validity is undecidable, because a GC property $\psi$ is valid iff $\neg\psi$ is unsatisfiable, where $\neg \psi$
can be written as a property whose atoms are negated GCs, i.e. of the form $\neg c$ for $c$ a GC. Negated GCs can model counters~\cite[Thm. 12]{BP14}, so that state reachability of a 2-counter machine can be reduced to satisfiability of a property over negated GCs.
Consequently,
\begin{restatable}{remark}{remarkGC}
Monitoring of GC properties is not solvable.
\end{restatable}
MCs over $\mathbb Z$ can be written as GCs~\cite{BP14}, with the key difference that
for an MC $c$ also $\neg c$ is an MC, and hence a GC. Thus, we can assume that in a DFA for an $\text{MC}_{\mathbb Z}$ property $\psi$, all constraints are GCs.
In \cite[Thm.~5.5]{FMW22a} it was shown that a transition system over GCs admits a finite summary $(\text{GC}_K, \sim_K)$. Here, $\text{GC}_K$ is the finite set of quantifier-free formulas with GC atoms over variables $V$ and constants $\leq K$, and $\sim_K$ is the cutoff equivalence relation, where equivalence of two formulas is
checked after replacing constants greater than $K$ by $K$, for $K$ the maximal difference between constants in the input.
Finite summary relies on the initial assignment of $V$ being fixed,
whereas by Def.~\ref{def:history constraint} history constraints start from $\varphi_{\mathit{init}}$, i.e., a parametric assignment $\vec V \mapsto \vec V_0$. This can hamper finiteness of the summary. E.g., for $\psi=\mathsf{X}\xspace_w (\cur{x}{>}\pre{x} \U \cur{x}{>}5)$ there are finitely many equivalence classes only if the initial value $z$ of $x$ is known (after at most $5-z$ steps $\psi$ holds).
Nonetheless, Cor.~\ref{cor:main} can be used to show that monitoring is solvable, although the procedure needs to be suitably refined.
\begin{restatable}{theorem}{theoremMCZ}
\label{thm:mc}
Monitoring is solvable for MC$_\mathbb Z$ properties.
\end{restatable}
\begin{proof}[Proof (sketch)]
We modify our procedure as follows:
(1) in line 5, we compute the CG starting from
$\bigwedge v{=}\alpha_n(v)$ instead of $\varphi_{\mathit{init}}$.
By \cite[Thm.~5.5]{FMW22a} a finite summary exists, so the CG computation terminates.
(2) The checks in lines 8,9 are simplified: as the initial assignment is now integrated in the CG, at line 8 it suffices to check whether the CG has a non-empty path to a non-final state (resp. to a final state in line 9).
It is not hard to adapt the proof of Thm.~\ref{thm:lookahead1:monitoring} accordingly.
However, the changed procedure comes with the price of computing CGs
not only for every DFA state but also every assignment in the trace.
\end{proof}
\section{Conclusions}
\label{sec:conclusions}
\paragraph{Implementation.}
We implemented our approach in a prototype, whose source code and
web interface are available via \emph{https://bit.ly/3QFoJHA}.
The tool takes an A\textsc{LTL}$_f$\xspace property $\psi$ and a trace as input,
determines whether $\psi$ is in one of the
decidable classes identified in the last section, constructs and visualizes a monitor, and computes the monitoring state.
The tool is implemented in Python, using Z3~\cite{Z3} and CVC5~\cite{DR0BT14} for SMT checks and quantifier elimination.
\paragraph{Future work.}
We want to lift our automata-based approach to the case of traces of richer states, equipped with full-fledged relations. Hence we plan to study how to integrate our approach with \cite{DeLT16} and \cite{CDMP22}. The former
considers states consisting of first-order structures modulo theories, but does not foresee any form of lookahead in the properties. In \cite{CDMP22}, instead, states are labeled by first-order interpretations and properties are expressed in a fragment of first-order LTL with a controlled first-order quantification across time; however arithmetic theories are not supported. None of these approaches feature an automata-based characterization of monitors, which makes the integration with the current work particularly interesting.
\section{Appendix}
\subsection{Preliminaries}
\begin{lemma}
\label{lem:undecidable}
Satisfiability of $\mathcal L$ properties with lookahead 1 is undecidable.
\end{lemma}
\begin{proof}
We model state reachability in a 2-counter machine $M$ as a property in $\mathcal L$ with lookahead 1:
Let $V = \{x,y,s\}$ where $x,y$ model the counters, and $s$ is an additional variable keeping track of the control state. We fix for every state $q$ of $M$ a value $n_q \in \mathbb Z$; let $n_0$ be the value of $M$'s initial state.
For a transition $t \colon q \to p$ in $M$, let $\psi_t$ be the property
\begin{inparaitem}
\item[$(i)$]
$s\,{=}\,n_q \wedge s^1\,{=}\,n_{p} \wedge x^1\,{=}\,x{+}1 \wedge y^1\,{=}\,y$ if
$t$ increments $x$
\item[$(ii)$]
$s\,{=}\,n_q \wedge s^1\,{=}\,n_{p} \wedge x > 0 \wedge x^1\,{=}\,x{-}1 \wedge y^1\,{=}\,y$ if it decrements $x$
\item[$(iii)$]
$s\,{=}\,n_q \wedge s^1\,{=}\,n_{p} \wedge x\,{=}\,0 \wedge y^1\,{=}\,y\wedge x^1 = x$ if it checks $x$ for 0
\end{inparaitem}
and similar for $y$.
Then, state $f$ is reachable in $M$ iff $(s\,{=}\,n_0) \wedge \mathsf{F}\xspace (s\,{=}\,n_f) \wedge \mathsf{G}\xspace (\bigvee_t \psi_t)$ is satisfiable.
\end{proof}
\lemmamorelookahead*
\begin{proof}
We define a sequence of formulas $\psi_j$ of lookahead $j$, $0\,{\leq}\,j\,{\leq}\,m$, as follows:
$\psi_m = \psi$; and for $0\,{\leq}\,j\,{<}\,m$ we set $\psi_j = d(\psi_{j+1})$, where $d(\psi_{j+1}) = \psi_{j+1}$ if $j = 0$, and otherwise $d(\psi_{j+1})$ is obtained from $\psi_{j+1}$ by performing the following replacement exhaustively:
if a constraint $e_1\odot e_2$ in $\psi_{j+1}$ contains $v^{j+1}$ for some variable $v$,
use a fresh variable $x$ of the same sort and replace $e_1\odot e_2$
by
\[(e_1[v^{j+1} \mapsto x'] \odot e_2[v^{j+1} \mapsto x'] \wedge \mathsf{X}_w\xspace (x^{j} = v)) \vee \mathsf{X}_w\xspace^j\bot\]
Here $e[y \mapsto z]$ for an expression $e$ is the expression obtained from $e$ by
substituting all occurrences of $y$ by $z$.
After applying this transformation exhaustively, $\psi_j := d(\psi_{j+1})$ has lookahead $j$.
Let $x_{v,j}$ denote the fresh variable introduced to substitute $v^j$, for all $v\in V$ and $1<j\leq m$, and $X$ the set of all such variables.
For a trace $\tau$ of length $n$ over variables $V$, let $\tau'$ be obtained from $\tau$ by setting $\tau'(i)(v) = \tau(i)(v)$ for all $v\in V$ and $0\leq i < n$;
and $\tau'(i)(x_{v,j}) = \tau(i+j)(v)$ if $i+j < n$, and otherwise $\tau'(i)(x_{v,j}) := 0$.
(1) We show that $[\tau',i](e) = [\tau', i](e[v^o \mapsto x_{v,o}])$, for an arbitrary $i$ and expression $e$ with lookahead $j$ such that $i+j<n$, and lookahead $o>1$.
This is straightforward to show by structural induction on $e$.
If $e$ is a constant or a variable different from $v^o$, both evaluations clearly coincide.
If $e = e_1 + e_2$ or $e = e_1 - e_2$, the statement follows from the induction hypothesis.
Otherwise, $e = v^o$ and $[\tau', i](e[v^o \mapsto x_{v,o}]) = [\tau', i](x_{v,o})$ and by definition of $\tau'$, $\tau'(i) = \tau(i+o)(v)$ holds.
(2) Next, we show that $\tau',i\models \psi_j$ iff $\tau',i\models d(\psi_j)$ for arbitrary $i$ and $\psi'$, by induction on $(n-i,\psi')$.
The interesting case if the one where $\psi_j$ is a constraint $c = e_1 \odot e_2$.
If $c$ has lookahead smaller than $j$, then $d(c) = c$, so there is nothing to show. Otherwise, suppose $c$ is replaced by $(d(c)\wedge \mathsf{X}_w\xspace (x^{j} = v)) \vee \mathsf{X}_w\xspace^j\bot$ (the case for multiple replaced variables is similar).
If $\tau',i\models c$ holds, either $i+j < n$ and $[\tau',i](e_1) \odot [\tau',i](e_2)$
holds, or $i+j \geq n$. In the latter case, $\tau',i\models \mathsf{X}_w\xspace^j\bot$, so $\tau',i\models d(\psi')$. Otherwise,
$d(c) = e_1[v^{j+1}\mapsto x_{v,j+1}'] \odot e_2[v^{j+1} \mapsto x_{v,j+1}']$, and the claim follows from (1).
Similarly, if $\tau',i\not \models c$, we must have $i+j < n$ and $[\tau',i](e_1) \odot [\tau',i](e_2)$ does not hold; then the claim follows again from (1).
If $\psi_j = \psi \wedge \psi'$ or $\psi_j = \neg \psi$, the claim follows from the induction hypothesis as the formula gets smaller.
If $\psi_j = \mathsf{X}_s\xspace \psi$ then $\tau',i\models \psi'$ can only hold if $i<n-1$ and
$\tau,i+1 \models \psi$ from which the claim follows again by the induction hypothesis; and the other direction is similar.
A similar reasoning applies to $\psi_j = \psi \U \psi'$.
From (2) we conclude that $\tau',i\models \psi_m$ iff $\tau',i\models \psi_1$.
Since $\psi_m = \psi$ contains only the variables $V$ and $\tau$ and $\tau'$ coincide on $V$, we it follows that $\tau\models \psi$ iff $\tau'\models \psi_1$.
Note that the variable $x_{v,j}$ must be distinct for every $v$ and $j$, but obviously, if $v^j$ has multiple occurrences, the respective fresh variable and additional constraint can be shared.
\end{proof}
\subsection{Automata}
\begin{lemma}
\label{lem:lookback:lookahead}
For $\psi$ with lookahead 1,
$\tau \models \psi$ iff $\tau \models \psi_\back$.
\end{lemma}
\begin{proof}
We extend the semantics to account for variables in $V_{prev}$ and $V_{curr}$: first, we impose $[\tau,i](v_{curr})=\tau(i)(v)$ $0{\leq} i{\leq} n$ and $[\tau,i](v_{prev}) = \tau(i{-}1)(v)$ for $0{<}i{\leq} n$.
We denote by $\models_b$ the satisfaction relation defined as $\models$ apart from the modification above.
%
Given this, we show that for all constraints $c$, $\tau,i\models c$ iff $\tau,i\models_b back(c)$.
%
If $c$ does not contain primed variables, the claim trivially holds since $back(c)=c$.
%
Otherwise, consider the case $c=v' \odot u$, so that $back(c) = \mathsf{X}_w\xspace (v_{curr} \odot u_{prev})$.
%
($\Rightarrow$)
%
For $i{<}n$ we have that $\tau,i\models c$ implies
%
$[\tau,i](v')\odot [\tau,i](u)$ thus $\tau(i+1)(v) \odot \tau(i)(u)$ which implies $[\tau,i{+}1](v)\odot [\tau,i](u)$ and hence $\tau,i{+}1\models_b v_{curr} \odot u_{prev}$, so that $\tau,i\models_b \mathsf{X}_w\xspace ( v_{curr} \odot u_{prev})$.
%
For $i{=}n$, we simply note that $\tau,i\models c$ as this is not well-defined for $\tau$ and $i$, and $\tau,i\models_b back(c)$.
%
The same reasoning can be applied for arbitrary constraints.
The opposite direction ($\Leftarrow$) is proven by the same steps in reversed order.
%
It thus follows that $\tau,i\models \psi$ iff $\tau,i\models_b \psi_{\mathit{back}}$, since $\psi_{\mathit{back}}$ differs from $\psi$ only at the level of atoms.
\end{proof}
Let $\mathcal L_\back$ denote the set of properties obtained from $\mathcal L$ after the transformation to negation normal form, and after replacing lookahead by lookback.
Formally, $\mathcal L_\back$ is defined by the following grammar, where $c\in \mc C(V_{\mathit{pre}}\cup V_{\mathit{cur}})$:\\
$\psi :: =
c \mid \neg c \mid
\psi {\wedge} \psi \mid \psi {\vee} \psi \mid \mathsf{X}_w\xspace \psi \mid
\mathsf{X}_s\xspace \psi \mid \mathsf{G}\xspace \psi \mid \psi \U \psi
$
To refine the notion of consistency to the level of constraint sets with $\lambda$s, and ensure that $\lambda$s
occur in the right place, we define $\lambda$-consistency:
\begin{definition}
Let $\constr(\varsigma) = \varsigma \setminus \{\lambda, \neg \lambda\}$.
A symbol $\varsigma \in \Sigma_\lambda$ is \emph{$\lambda$-consistent with instant $i$} of trace $\langle\alpha_0, \dots, \alpha_{n-1}\rangle$ (or simply with $(\tau, i)$)
if
(1) $0\,{\leq}\,i\,{<}\,n{-}1$ and $\lambda \not\in \varsigma$, or $i=n{-}1$ and $\neg \lambda \not\in \varsigma$,
(2) if $i\,{=}\,0$ then $\varsigma$ does not contain $V_{\mathit{pre}}$ and
$\alpha_0 \models constr(\varsigma)$; and if $i\,{>}\,0$ then $\combine{\alpha_{i-1}}{\alpha_{i}} \models \constr(\varsigma)$.
\end{definition}
Let a property $\psi \in \mathcal L_\back$ have \emph{safe lookback} if
\begin{inparaitem}
\item
$\psi$ is a (negated) constraint that does not mention $V_{\mathit{pre}}$,
\item $\psi = \mathsf{X}_w\xspace\psi'$, $\psi = \mathsf{X}_s\xspace\psi'$, or $\psi \in \{\top, \bot\}$,
\item $\psi = \neg \psi'$ or $\psi = \mathsf{G}\xspace\psi'$, and $\psi'$ has safe lookback, or
\item $\psi = \psi_1 \wedge \psi_2$, $\psi = \psi_1 \vee \psi_2$, or $\psi = \psi_1 \U \psi_2$, and
$\psi_1$ and $\psi_2$ have safe lookback.
\end{inparaitem}
We next show that $\delta$ is total in the sense that it provides a matching transition for every instant of a trace.
\begin{lemma
\label{lem:delta:total}
Consider $\psi \in \mathcal L_\back\cup \{\top,\bot\}$, a trace $\tau$ of length $n$, and $0\leq i < n$ such that if $i=0$ then $\psi$ has safe lookback.
Then there is some $(\inquotes{\psi'}, \varsigma) \inn \delta(\inquotes{\psi})$
such that
$\varsigma$ is $\lambda$-consistent with $(\tau, i)$.
\end{lemma}
\begin{proof}
By structural induction on $\psi$. The claim is easy to check for every base
case of the definition of $\delta$, and in all other cases it follows from the induction hypothesis and the definition of $\owedge$ and $\ovee$.
\end{proof}
The next result show that $\delta$ preserves and reflects satisfaction of properties at trace instants.
\begin{lemma}
\label{lem:delta}
Let $\psi \in \mathcal L_\back$,
$\tau = \langle\alpha_0, \dots, \alpha_{n-1}\rangle$ a trace, and $0\,{\leq}\,i\,{<}\,n$.
Then the following are equivalent:
\begin{compactitem}
\item
$\tau,i \models \psi$ and if $i=0$ then $\psi$ has safe lookback, and
\item
there is some $(\inquotes{\psi'}, \varsigma)\in \delta(\inquotes{\psi})$ such that\\
\noindent
\begin{tabular}{@{\ }r@{\ }p{8cm}}
$(a)$ & $\varsigma$ is $\lambda$-consistent with instant $i$ of $\tau$, and\\
$(b)$ & if $i\,{=}\,n{-}1$ then $\psi'\,{=}\,\top$, and otherwise $\tau,i{+}1 \models \psi'$.
\end{tabular}
\end{compactitem}
\end{lemma}
\begin{proof}
We prove both directions simultaneously by induction on $\psi$, using the definition of $\delta$.
\begin{compactitem}
\item
If $\psi = \top$ then it must be $\psi'=\top$ and $\varsigma=\emptyset$, so
both directions hold trivially.
If $\psi = \bot$ it must be $\psi'=\bot$, so neither $\tau,i\models \psi$
nor $\tau,i+1\models \psi'$ hold.
\item Let $\psi$ be a constraint $c\in \mc C(V_{\mathit{pre}}\cup V_{\mathit{cur}})$.
$(\Longrightarrow)$
Suppose $\tau,i\models c$. For $(\inquotes{\top}, \{c\}) \in \delta(\inquotes{c})$, (b) holds because $\psi' = \top$, and (a) holds
because $\tau,i\models c$ and the assumption that $c$ has safe lookback if $i=0$ implies $\lambda$-consistency of $\{c\}$.
$(\Longleftarrow)$
Suppose there is some
$(\inquotes{\psi'}, \varsigma)\in \delta(\inquotes{c})$ such that (a) and (b) hold. By definition of $\delta$, $\psi'$ is either $\top$ or $\bot$, but the latter can be excluded, so that $constr(\varsigma) = \{c\}$.
By $\lambda$-consistency, we have either $i=0$, $\varsigma$ does not mention $V_{\mathit{pre}}$, and $\alpha_0 \models constr(\varsigma)$, or $i > 0$ and $\combine{\alpha_{i-1}}{\alpha_{i}} \models constr(\varsigma) = c$, so $\tau,i\models c$, and $c$ is well-defined at instant $i$ of $\tau$, so safe lookback holds if $i=0$.
\item
Let $\psi = \neg c$ for a constraint $c\in \mc C(V_{\mathit{pre}}\cup V_{\mathit{cur}})$.
$(\Longrightarrow)$
Suppose $\tau,i\models \neg c$, so $\tau,i \not\models c$. We have $(\inquotes{\top}, \{neg(c)\}) \in \delta(\inquotes{\neg c})$. Then (b) holds because $\psi' = \top$, and (a) holds
because $\tau,i\not\models c$ and the assumption that $c$ is well-defined implies
$\tau,i \models neg(c)$, and implies $\lambda$-consistency.
$(\Longleftarrow)$
Let $(\inquotes{\psi'}, \varsigma)\in \delta(\inquotes{\neg c})$ such that (a) and (b) hold. By definition of $\delta$, $\psi'$ is either $\top$ or $\bot$, but the latter can be excluded, so that $constr(\varsigma) = \{neg(c)\}$.
By $\lambda$-consistency, either $i\,{=}\,0$, $\varsigma$ does not mention $V_{\mathit{pre}}$, and $\alpha_0 \models neg(c)$, or $i\,{>}\, 0$ and $\combine{\alpha_{i-1}}{\alpha_{i}} \models neg(c)$, so $\tau,i\models neg(c)$, and safe lookback if $i=0$ follows from $\lambda$-consistency.
\item
We have $\tau, i \models \psi_1 \wedge \psi_2$ iff $\tau, i \models \psi_1$ and
$\tau, i \models \psi_2$.
By the induction hypothesis, this is the case iff there are some $(\inquotes{\psi_1'}, \varsigma_1) \in \delta(\inquotes{\psi_1})$ and $(\inquotes{\psi_2'}, \varsigma_2) \in \delta(\inquotes{\psi_2})$
such that $\varsigma_1$, $\varsigma_2$ are $\lambda$-consistent with $\tau$ at $i$;
and either $i<n$ and $\tau,i+1 \models \psi_1'$ and $\tau,i+1 \models \psi_2'$, or
$\psi_1' = \psi_2' = \top$.
We have $(\inquotes{\psi_1' \wedge \psi_2'}, \varsigma_1 \cup \varsigma_2) \in \delta(\inquotes{\psi_1 \wedge \psi_2})$,
where
$\varsigma_1 \cup \varsigma_2$ is $\lambda$-consistent with $\tau$ at $i$ iff both $\varsigma_1$ and $\varsigma_2$ are.
Moreover, if $i<n$ then $\tau,i+1 \models \psi_1'\wedge \psi_2'$ iff $\tau,i+1 \models \psi_1'$ and $\tau,i+1 \models \psi_2'$ hold; and if $i=n$ then $\psi_1' \wedge \psi_2' = \top$ iff $\psi_1' = \psi_2' = \top$.
In addition, $\psi_1 \wedge \psi_2$ has safe lookback iff this holds for both $\psi_1$ and $\psi_2$.
\item
We have $\tau, i \models \psi_1 \vee \psi_2$ iff $\tau, i \models \psi_1$ or
$\tau, i \models \psi_2$. Note that $\psi_1 \vee \psi_2$ has safe lookback iff this holds for both $\psi_1$ and $\psi_2$.
Wlog, assume the former.
By the induction hypothesis, this is the case iff there are some $(\inquotes{\psi_1'}, \varsigma_1) \in \delta(\inquotes{\psi_1})$
such that $\varsigma_1$ is $\lambda$-consistent with $\tau$ at $i$;
and either $i<n$ and $\tau,i+1 \models \psi_1'$, or
$\psi_1' = \top$.
By Lem.~\ref{lem:delta:total}, there is some $(\inquotes{\psi_2'}, \varsigma_2) \in \delta(\inquotes{\psi_2})$ such that $\varsigma_1$ is $\lambda$-consistent with $\tau$ at $i$;
We have $(\inquotes{\psi_1' \vee \psi_2'}, \varsigma_1 \cup \varsigma_2) \in \delta(\inquotes{\psi_1 \vee \psi_2})$,
where
$\varsigma_1 \cup \varsigma_2$ is $\lambda$-consistent with $\tau$ at $i$ iff both $\varsigma_1$ and $\varsigma_2$ are.
Moreover, if $i<n$ then $\tau,i+1 \models \psi_1'\vee \psi_2'$ iff $\tau,i+1 \models \psi_1'$ or $\tau,i+1 \models \psi_2'$ hold; and if $i=n$ then $\psi_1' \vee \psi_2' = \top$ iff $\psi_1' = \top $ or $\psi_2' = \top$.
\item
($\Longrightarrow$)
If $\tau, i \models \mathsf{X}_s\xspace \psi$ then $i<n{-}1$ and $\tau, i+1 \models \psi$.
As $(\inquotes{\psi}, \{\neg \lambda\}) \in \delta(\inquotes{\mathsf{X}_s\xspace \psi})$ and $\{\neg \lambda\}$ is
$\lambda$-consistent with $\tau$ at $i$ because $i<n-1$, the claim holds.
($\Longleftarrow$)
If $(\inquotes{\psi'}, \varsigma) \in \delta(\inquotes{\mathsf{X}_s\xspace \psi})$ such that
$\varsigma$ is $\lambda$-consistent and $\tau, i+1 \models \psi'$ or $\psi' = \top$, by the
definition of $\delta$ it must be $\psi' = \psi$ and $\varsigma = \{\neg\lambda\}$.
By $\lambda$-consistency, $i<n-1$, so $\tau, i+1 \models \psi$, and hence $\tau, i \models \mathsf{X}_s\xspace \psi$.
Safe lookback holds by definition.
\item
($\Longrightarrow$)
If $\tau, i \models \mathsf{X}_w\xspace \psi$ then $i=n-1$, or $i<n-1$ and $\tau, i+1 \models \psi$.
In the latter case, we reason as for $\mathsf{X}_s\xspace$.
If $i=n$, we take $(\inquotes{\top}, \{\lambda\}) \in \delta(\inquotes{\mathsf{X}_w\xspace \psi})$ and $\{\lambda\}$ is
$\lambda$-consistent with $\tau$ at $i$, so the claim holds.
($\Longleftarrow$)
If $(\inquotes{\psi'}, \varsigma) \in \delta(\inquotes{\mathsf{X}_w\xspace \psi})$ such that
$\varsigma$ is $\lambda$-consistent and $\tau, i+1 \models \psi'$ or $\psi' = \top$, by the
definition of $\delta$ it must be either $\psi' = \psi$ and $\varsigma = \{\neg\lambda\}$, or $\psi' = \top$ and $\varsigma = \{\lambda\}$.
In the former case, we reason as for $\mathsf{X}_s\xspace$, otherwise, $\tau, i \models \mathsf{X}_w\xspace \psi$ holds anyway.
\item
($\Longrightarrow$)
If $\tau, i \models \psi_1 \U \psi_2$, either (i) $\tau, i \models \psi_2$, or (ii) $i<n{-}1$,
$\tau, i \models \psi_1$, and $\tau, i+1 \models \psi_1 \U \psi_2$.
In case (i), by the induction hypothesis there is some $(\psi', \varsigma') \in \delta(\inquotes{\psi_2})$
such that (a) and (b) hold.
By (a), $\varsigma'$ is $\lambda$-consistent with $\tau$ at $i$. By Lem.~\ref{lem:delta:total}, there are some $(\psi_1', \varsigma_1) \in \delta(\inquotes{\psi_1})$ and $(\psi_2', \varsigma_2) \in \delta(\inquotes{\mathsf{X}_s\xspace (\psi_1 \U \psi_2)})$ such that $\varsigma_1$ and $\varsigma_2$ are $\lambda$-consistent with $\tau$ at $i$. We have that $(\inquotes{\psi}, \varsigma) \in \delta(\inquotes{\psi_1 \U \psi_2})$ for $\psi = \psi' \vee (\psi_1' \wedge \psi_2')$ and $\varsigma = \varsigma' \cup \varsigma_1 \cup \varsigma_2$, and $\varsigma$ is $\lambda$-consistent with $\tau$ at $i$. Moreover, by (b) either $i<n{-}1$ and $\tau,i+1 \models \psi'$, or $i=n{-}1$ and
$\psi' = \top$. Thus, also $i<n{-}1$ and $\tau,i+1 \models \psi$, or $i=n{-}1$ and
$\psi = \top$ hold.
In case (ii) we have $i<n{-}1$. As safe lookback holds for $\psi_1$ if $i=0$, by the induction hypothesis there is some $(\psi_1', \varsigma_1') \in \delta(\psi_1)$
such that (a) and (b) hold, so as $i<n{-}1$ it is $\tau, i+1 \models \psi_1'$ ($\star$). Moreover, $(\inquotes{\psi_1 \U \psi_2}, \{\neg \lambda\}) \in \delta(\inquotes{\mathsf{X}_s\xspace (\psi_1 \U \psi_2)})$ and $\{\neg \lambda\}$ is
$\lambda$-consistent with $\tau$ at $i$ because $i<n{-}1$.
By Lem.~\ref{lem:delta:total}, there is also some $(\psi_2', \varsigma_2') \in \delta(\psi_2)$ such that $\varsigma_2'$ is $\lambda$-consistent with $\tau$ at $i$.
Now, we have $(\inquotes{\psi}, \varsigma) \in \delta(\inquotes{\psi_1 \U \psi_2})$ for $\psi = \psi_2' \vee (\psi_1' \wedge (\psi_1 \U \psi_2))$ and $\varsigma = \varsigma' \cup \varsigma_1 \cup \varsigma_2$.
Then $\varsigma$ as a union is also $\lambda$-consistent with $\tau$ at $i$, and $\tau, i+1 \models \psi$ because of ($\star$) and the assumption of case (ii).
($\Longleftarrow$) Suppose there is some $(\inquotes{\psi}, \varsigma) \in \delta(\inquotes{\psi_1 \U \psi_2})$ such that (a) and (b) holds.
By the definition of $\delta$, we can write $\psi$ and $\varsigma$ as
$\psi = \psi_2' \vee (\psi_1' \wedge \psi_3')$ and $\varsigma = \varsigma_1 \cup \varsigma_2 \cup \varsigma_3$, where $(\inquotes{\psi_2'}, \varsigma_2) \in \delta(\inquotes{\psi_2})$,
$(\inquotes{\psi_1'}, \varsigma_1) \in \delta(\inquotes{\psi_1})$, and
$(\inquotes{\psi_3'}, \varsigma_3) \in \delta(\inquotes{\mathsf{X}_s\xspace (\psi_1 \U \psi_2)})$.
By (a), all of $\varsigma_1$, $\varsigma_2$, $\varsigma_3$ must be $\lambda$-consistent.
By (b), either $i<n{-}1$ and $\tau,i+1 \models \psi_2' \vee (\psi_1' \wedge \psi_3')$, or
$i=n{-}1$ and $\psi_2' \vee (\psi_1' \wedge \psi_3') = \top$.
We distinguish these two cases: if $i=n{-}1$ then either $\psi_2' = \top$ or $\psi_1' \wedge \psi_3' = \top$, but the latter is impossible
because it would imply $\psi_3' = \top$, but by $\lambda$-compatibility this is not possible if $i=n$.
So $\psi_2' = \top$. By the induction hypothesis, $\tau, i \models \psi_2$, and hence $\tau, i \models \psi_1 \U \psi_2$.
If $i<n$ then $\tau,i+1 \models \psi_2' \vee (\psi_1' \wedge \psi_3')$, so either
$\tau,i+1 \models \psi_2'$ or $\tau,i+1 \models \psi_1' \wedge \psi_3'$.
In the former case, by the induction hypothesis $\tau, i \models \psi_2$, and hence $\tau, i \models \psi_1 \U \psi_2$. In the latter case, $\tau,i+1 \models \psi_1'$ and $\tau,i+1 \models \psi_3'$.
By the induction hypothesis, $\tau,i \models \psi_1$. By the definition of $\delta$, we must have
$\psi_3' = \psi_1 \U \psi_2$. As $\tau,i \models \psi_1$ and $\tau,i+1 \models \psi_1 \U \psi_2$, we obtain again $\tau,i \models \psi_1 \U \psi_2$.
\item The case for $\mathsf{G}\xspace$ is similar.
\qedhere
\end{compactitem}
\end{proof}
Let a word be $\lambda$-consistent with a trace $\tau$ if it is $\lambda$-consistent with $\tau$ at all instants $i$.
\begin{lemma}
\label{lem:deltastar}
Let $\psi$ have safe lookback.
Then $\rho \models \psi$
iff there is a word $w\in \Sigma_\lambda^*$ that is $\lambda$-consistent with a trace $\tau$ such that $\inquotes{\top} \in \delta^*(\inquotes{\psi},w)$.
\end{lemma}
\begin{proof}
($\Longrightarrow$)
Suppose that $\tau \models \psi$, i.e., $\tau,0 \models \psi$.
We show that, more generally, for all $i$, $0\,{\leq}\,i\,{<}\,n$,
and every property $\chi \in \mathcal L_\back$,
if $\tau, i \models \chi$ and $\chi$ has safe lookback in the case where $i=0$, then
there is a word $w_i = \langle\varsigma_i, \varsigma_{i+1}, \dots, \varsigma_{n-1}\rangle$
such that
$\inquotes{\top} \in \delta^*(\inquotes{\chi},w_i)$,
and
$\varsigma_j$ is $\lambda$-consistent with $(\tau,j)$ for all $j$, $i\,{\leq}\,j\,{<}\,n$.
The proof is by induction on $n-i$.
In the base case where $i=n{-}1$, we assume that $\tau,n \models \chi$.
By Lem. \ref{lem:delta} there is some $\varsigma_n$ such that
$(\inquotes{\top}, \varsigma_n)\in \delta(\inquotes{\chi})$,
and $\varsigma_n$ is $\lambda$-consistent with $(\tau,n)$.
For the induction step, assume $i\,{<}\,n-1$ and $\tau, i \models \chi$.
By Lem. \ref{lem:delta} there is some
$(\inquotes{\chi'}, \varsigma_i) \in \delta(\inquotes{\chi})$ such that
$\tau, i{+}1 \models \chi'$, and
$\varsigma_i$ is $\lambda$-consistent with $(\tau, i)$.
By the induction hypothesis,
there is a word $w_{i+1} = \langle\varsigma_{i+1}, \dots, \varsigma_{n-1}\rangle$
such that
$\inquotes{\top} \in \delta^*(\inquotes{\chi'},w_{i+1})$,
and
$\varsigma_j$ is $\lambda$-consistent with $(\tau,j)$ for all $j$, $i\,{<}\,j\,{<}\, n$.
Thus, we can define $w_{i} = \langle\varsigma_i,\varsigma_{i+1}, \dots, \varsigma_{n}\rangle$,
which satisfies
$\inquotes{\top} \in \delta^*(\inquotes{\chi},w_{i})$ and
$\varsigma_j$ is $\lambda$-consistent with $\tau$ at instant $j$ for all $j$, $i\,{\leq}\,j\,{<}\, n$.
This concludes the induction step.
By assumption, $\tau,0 \models \psi$ holds, and
$\psi$ has safe lookback.
From the case $i = 0$ of the above statement, we obtain a word $w$
such that
$\inquotes{\top} \in \delta^*(\inquotes{\psi},w)$ and $w$ is
$\lambda$-consistent with $\tau$.
($\Longleftarrow$)
Let $w =\langle \varsigma_0, \dots, \varsigma_{n-1}\rangle$ be $\lambda$-consistent with $\tau = \langle\alpha_0,\dots, \alpha_{n-1}\rangle$.
If $\inquotes{\top} \in \delta^*(\inquotes{\psi},w)$, there must be properties
$\chi_0,\chi_1,\dots, \chi_{n}$ such that $\chi_0 = \psi$, $\chi_{n} = \top$,
and $(\inquotes{\chi_{i{+}1}}, \varsigma_{i}) \in \delta(\inquotes{\chi_i})$
for all $i$, $0\leq i < n$.
As $w$ is $\lambda$-consistent with $\tau$,
$\varsigma_i$ is $\lambda$-consistent with
$(\tau, i)$ for all $i$, $0\,{\leq}\,i\,{<}\,n$.
In order to show that $\tau \models \psi$, we verify that
$\tau, i \models \chi_i$
for all $i$, $0\,{\leq}\,i\,{<}\,n$.
The reasoning is by induction on $n-i$.
In the base case $i\,{=}\,n{-}1$.
Thus $\chi_{n} = \top$ and
$(\inquotes{\chi_{n}}, \varsigma_{n}) \in \delta(\inquotes{\chi_{n-1}})$, so that
with $\lambda$-consistency it follows from
Lem. \ref{lem:delta} that $\tau, n-1 \models \chi_{n-1}$.
In the induction step $i\,{<}\,n{-}1$, and we assume by the induction hypothesis that $\tau, i{+}1 \models \chi_{i{+}1}$.
We have
$(\inquotes{\chi_{i{+}1}}, \varsigma_{i+1}) \in \delta(\inquotes{\chi_i})$, so
$\tau, i \models \chi_i$ follows again from Lem. \ref{lem:delta} using $\lambda$-consistency. This concludes the induction step, and the claim follows for the case $i\,{=}\,0$ because
$\chi_0 = \psi$.
\end{proof}
\noindent
It remains to connect this key property of $\delta$ with the NFA $\NFA$ where $\lambda$ and $\neg \lambda$ are removed. To this end,
we next establish auxiliary facts about occurrences of $\lambda$'s,
which is straightforward to prove following \cite[Lem. A.5]{FMW22a}.
\begin{lemma}
\label{lem:delta:last}
Let $\psi \in \mathcal L_\back$ and
$(\inquotes{\chi},\varsigma) \in \delta(\inquotes{\psi})$.
\begin{compactenum}
\item[(1)] If $\lambda \in \varsigma$
then $\chi = \top$ or $\chi = \bot$.
\item[(2)] Suppose $\neg \lambda \in \varsigma$, $\lambda \not\in\varsigma$,
and $\chi = \top$, and $\varsigma$ is $\lambda$-consistent with some step $i$ of some run $\rho$.
Then there is some $(\inquotes{\top},\varsigma') \in \delta(\inquotes{\psi})$
such that $\neg \lambda\not\in \varsigma'$ and $\varsigma'$ is $\lambda$-consistent with step $i$ of $\rho$ as well.
\item[(3)] If $\chi$ is not $\top$ or $\bot$ then
$\varsigma$ contains $\lambda$ or $\neg \lambda$.
\end{compactenum}
\end{lemma}
\lemmaNFA*
\begin{proof}
First, $\tau \models \psi$ iff
$\tau \models \psi_\back$ according to Lem.~\ref{lem:lookback:lookahead}.
Next, note that $\psi_\back$ has safe lookback, as can be seen by inductive reasoning on $\psi$: If $\psi$ is a constraint $c$, then if $c$ has no lookahead, $\back(c)$ does not contain variables $v_{\mathit{pre}}$, and otherwise $\back(c)=\mathsf{X}_w\xspace c'$, has safe lookback by definition; and similar for $\neg c$.
For the remaining cases the claim follows from the induction hypothesis.
We now show that $\NFA[\psi_\back]$ accepts $w$ iff $\tau \models \psi_\back$.
($\Longrightarrow$)
Let $w = \varsigma_0 \varsigma_1 \cdots \varsigma_{n-1}$, and
$q_0 \goto{\varsigma_0} q_1 \goto{\varsigma_1} \dots \goto{\varsigma_{n-1}} q_{n}$ ($\star$)
be the respective accepting run of $\NFA[\psi_\back]$.
By Def.~\ref{def:NFA}, there are $\varsigma_i'$,
such that $\varsigma_i = \varsigma_i' \setminus \{\lambda, \neg \lambda\}$
for all $0\leq i < n$, and $w' = \varsigma_0' \varsigma_1' \cdots \varsigma_{n-1}'$
satisfies $\inquotes{\top} \in \delta^*(\inquotes{\psi},w')$.
By Lem.~\ref{lem:delta:last} (2) we can choose $\varsigma_{n-1}'$ such that
$\neg \lambda \not\in \varsigma_{n-1}'$, and $\varsigma_{n-1}'$ is consistent with $\tau$ at $n-1$.
Moreover, we can assume that none of $q_0, \dots, q_{n-1}$ is $\bot$ or $\top$, so
by Lem.~\ref{lem:delta:last} (1)and (3) we have $\lambda\not\in \varsigma_i'$ for $i<n-1$.
Since moreover $w$ is consistent with $\tau$, the augmented word $w'$ is $\lambda$-consistent with $\tau$.
Thus $\tau \models \psi_\back$ follows from Lem.~\ref{lem:deltastar}.
($\Longleftarrow$)
If $\tau \models \psi_\back$ then by Lem.~\ref{lem:deltastar} there is a
word
$w = \varsigma_0 \varsigma_1 \cdots \varsigma_{n}$
that is $\lambda$-consistent with $\tau$ such that $\inquotes{\top} \in \delta^*(\inquotes{\psi_\back},w)$, so $\NFA[\psi_\back]$ accepts $w$.
\end{proof}
\begin{lemma}
\label{lem:word:for:trace}
For every non-empty trace $\tau$ there is a unique word $w \in \Theta_{\mathit{cur}} \Theta^*$ consistent with $\tau$.
\end{lemma}
\begin{proof}
Let $\tau = \langle\alpha_0, \dots, \alpha_{n-1}$, and $C$ be the constraints in $\psi_\back$.
Since for every constraint $c\in C_{\mathit{cur}}$, either $\alpha\models c$ or $\alpha\models neg(c)$, and $\Theta_{\mathit{cur}}$ contains all maximal satisfiable subsets of $C_{\mathit{cur}}\cup C_{\mathit{cur}}^-$, there must be exactly one subset $\varsigma_0\in \Theta_{\mathit{cur}}$ such that
$\alpha \models \bigwedge \varsigma_0$.
Similarly, $\combine{\alpha_i}{\alpha_{i+1}}$ must model either $c$ or $neg(c)$
for all constraints in $c$, so there must be exactly one $\varsigma_{i}\in \Theta$
such that $\combine{\alpha_i}{\alpha_{i+1}} \models \bigwedge \varsigma_{i}$, for all $0<i \leq n-1$. Thus, the word $w = \langle \varsigma_0, \dots, \varsigma_{n-1}\rangle$
is uniquely defined and consistent with $\tau$.
\end{proof}
\lemmaDFANFA*
\begin{proof}
Let $\leq$ be the partial order on $\Sigma^n$ defined by the pointwise subset relation, i.e., $w \leq w'$ iff
$w = \langle\varsigma_1,\dots,\varsigma_n\rangle$,
$w' = \langle\varsigma_1',\dots,\varsigma_n'\rangle$,
and $\varsigma_i \subseteq \varsigma_i'$ for all $1\leq i \leq n$ and $n\geq 0$.
($\Longrightarrow$)
We show the slightly more general statement $(\star)$ that if $\{q_0\} \gotos{w} P$ in $\DFA$ for some $w\in \Theta_{\mathit{cur}}\Theta^* \cup \{\epsilon\}$ and $P\in\mathcal Q$,
then for all $q\in P$ there is some word $u \leq w$ such that $q_0 \gotos{u} q$ in $\NFA$.
The reasoning is by induction on $w$.
If $w$ is empty, we set also $u$ to the empty word and the statement is obvious.
In the inductive step, suppose $w = w'\varsigma$, so there is some
$P'$ such that $q_0 \gotos{w} P'$ and $\Delta(P',\varsigma) = P$.
By definition of $\Delta$, for all $q\inn P$, there is some $q'\inn P'$
such that $(q',\varsigma',q) \in \varrho$ and $\varsigma' \subseteq \varsigma$.
By the induction hypothesis, there is a word $u \leq w$ such that $q_0 \gotos{u} q'$ in $\NFA$. We have $u\varsigma' \leq w\varsigma$
and $q_0 \gotos{u\varsigma'} q$ in $\NFA$, so the claim holds.
Now suppose $\DFA$ accepts a word $w$ consistent with a trace $\tau$, so $\{q_0\} \gotos{w} P$ for a final state $P$.
As $P$ is final, it must contain a state $q_F$ which is final in $\NFA$. By $(\star)$, there is a word $u \leq w$ such that $q_0 \gotos{u} q_F$ in $\NFA$, so $u$ is accepted. As $w$ is consistent with $\tau$, $u\leq w$, and by definition of $\leq$, also $u$ is consistent with $\tau$.
($\Longleftarrow$)
We show the slightly more general statement $(\star\star)$ that
if $q_0 \gotos{u} q$ in $\NFA$ for some $u\in \Sigma^*$ and $q \in Q$ then for all $w\in \Theta_{\mathit{cur}}\Theta^* \cup \{\epsilon\}$ such that $u\leq w$ it holds that
$\{q_0\} \gotos{w} P$ in $\DFA$ for some $P$ such that $q\in P$.
The reasoning is by induction on $u$.
If $u$ is empty, we set also $w$ to the empty word and the statement is obvious.
In the inductive step, consider a word $u\varsigma$, so there is some $q'$ such that $q_0 \gotos{u} q'$ in $\NFA$ and $(q', \varsigma,q) \in \varrho$. By the induction hypothesis,
for all $w\in \Theta_{\mathit{cur}}\Theta^* \cup \{\epsilon\}$ such that $u\leq w$ it holds that
$\{q_0\} \gotos{w} P'$ in $\DFA$ for some $P'$ such that $q'\in P'$.
Then, for all such $P'$ and $\varsigma'$ such that
$\varsigma \subseteq \varsigma'$ we have $u\varsigma \leq w\varsigma'$. By definition of $\Delta$ it holds that
$P = \Delta(P', \varsigma')$ contains $q$, i.e., $\{q_0\}\gotos{w} P' \goto{\varsigma'} P$ in $\DFA$, so the claim holds.
Now suppose $\NFA$ accepts a word $u$ consistent with $\tau$, so
$q_0 \gotos{u} q_F$ for some $q_F \in Q_F$.
Then $u$ is well-formed and non-empty.
By Lem.~\ref{lem:word:for:trace} there is some $w\in \Theta_{\mathit{cur}}\Theta^*$
consistent with $\tau$. By construction of $\Theta_{\mathit{cur}}$ and $\Theta$ as set of
maximal satisfiable subsets, we must have $u\leq w$.
By $(\star\star)$, $\{q_0\} \gotos{w} P$ in $\DFA$ for some $P$ such that $q_F\in P$,
that is, $\DFA$ accepts $w$.
\end{proof}
\subsection{Finite summary}
\begin{example}
The constraint graphs $\CG_\psi(A)$ and $\CG_\psi(B)$ for the automaton $\DFA[\psi_\back]$ from
Ex.~\ref{exa:lookahead} is shown in Fig.~\ref{fig:cgs}.
\label{exa:cgs}
\begin{figure*}
\begin{tikzpicture}[node distance = 15mm]
\node[node] (0) {\cgnode{$A$}{$x\,{=}\,x_0$}};
\node[node, below of=0, xshift=55mm, final] (1)
{\cgnode{$B$}{$x\,{=}\,x_0 \wedge x_0\,{=}\,2$}};
\node[node, below of=0, xshift=-55mm] (2)
{\cgnode{$C$}{$x\,{=}\,x_0 \wedge x_0\,{\neq}\,2$}};
\node[node, below of=1, xshift=20mm, final] (11)
{\cgnode{$B$}{$x\,{\geq}\,x_0 \wedge x_0\,{=}\,2$}};
\node[node, below of=1, xshift=-20mm] (12)
{\cgnode{$D$}{$x\,{<}\,x_0 \wedge x_0\,{=}\,2$}};
\node[node, below of=11, xshift=-20mm] (111)
{\cgnode{$D$}{$x_0\,{=}\,2$}};
\node[node, below of=2, xshift=-45mm] (21)
{\cgnode{$C$}{$x_0\,{\neq}\,2 \wedge x \geq x_0 \wedge x \neq 2$}};
\node[node, below of=2, final] (22)
{\cgnode{$B$}{$x_0\,{<}\,2 \wedge x = 2$}};
\node[node, below of=2, xshift=45mm] (23)
{\cgnode{$D$}{$x_0\,{\neq}\,2$}};
\node[node, below of=22, final] (221)
{\cgnode{$B$}{$x_0\,{<}\,2 \wedge x \geq 2$}};
\node[node, below of=23] (222)
{\cgnode{$D$}{$x_0\,{<}\,2$}};
\draw[goto, bend left=10] (0) to node[action, above, anchor=south west]{$\{\cur{x}{=}2\}$} (1);
\draw[goto, bend right=10] (0) to node[action, above, anchor=south east]{$\{\cur{x}{\neq}2\}$} (2);
\draw[goto, bend left=10] (1) to node[action, above, anchor=south west, near end]{$\{\cur{x}{\geq}\pre{x}\}$} (11);
\draw[goto, loop right, out=5, in=-5, looseness=7] (11) to node[action, right]{$\{\cur{x}{\geq}\pre{x}\}$} (11);
\draw[goto, loop right, out=5, in=-5, looseness=7] (111) to node[action, right]{$\Theta$} (111);
\draw[goto] (11) to node[action, right, anchor=west]{$\{\cur{x}{<}\pre{x}\}$} (111);
\draw[goto] (12) to node[action, left, anchor=east, near end]{$\{\cur{x}{\geq}\pre{x}\}$} (111);
\draw[goto, loop left, out=200, in=220, looseness=7] (12) to node[action, left]{$\{\cur{x}{<}\pre{x}\}$} (12);
\draw[goto, bend right=10] (1) to node[action, above, anchor=south east, near end]{$\{\cur{x}{<}\pre{x}\}$} (12);
\draw[goto, bend right=15] (2) to node[action, above, anchor=south east]{$\{\cur{x}{\geq}\pre{x}\wedge \cur{x}{\neq}2\}$} (21);
\draw[goto] (2) to node[action, right, anchor= west, near end]{$\{\cur{x}{\geq}\pre{x}\wedge \cur{x}{=}2\}$} (22);
\draw[goto, bend left=15] (2) to node[action, above, anchor=south west]{$\{\cur{x}{<}\pre{x}\}$} (23);
\draw[goto, loop right, out=5, in=-5, looseness=7] (23) to node[action, right]{$\Theta$} (23);
\draw[goto] (22) to node[action, above, anchor=south west, near end]{$\{\cur{x}{<}\pre{x}\}$} (222);
\draw[goto] (22) to node[action, right, near end]{$\{\cur{x}{\geq}\pre{x}\}$} (221);
\draw[goto, loop right, out=175, in=185, looseness=7] (221) to node[action, left]{$\{\cur{x}{\geq}\pre{x}\}$} (221);
\draw[goto] (221) to node[action, below]{$\{\cur{x}{<}\pre{x}\}$} (222);
\draw[goto, loop left, out=169, in=175, looseness=6] (21) to node[action, above]{$\{\cur{x}{\geq}\pre{x}\wedge \cur{x}{\neq}2\}$} (21);
\draw[goto, bend right=20] (21) to node[action, below]{$\{\cur{x}{\geq}\pre{x}\wedge \cur{x}{=}2\}$} (22);
\draw[goto, loop right, out=5, in=-5, looseness=7] (222) to node[action, right]{$\Theta$} (222);
\end{tikzpicture}
\begin{tikzpicture}[node distance = 15mm]
\node[node, below of=0, xshift=52mm, final] (1)
{\cgnode{$B$}{$x\,{=}\,x_0$}};
\node[node, below of=1, xshift=20mm, final] (11)
{\cgnode{$B$}{$x\,{\geq}\,x_0$}};
\node[node, below of=1, xshift=-20mm] (12)
{\cgnode{$D$}{$x\,{<}\,x_0$}};
\node[node, below of=11, xshift=-20mm] (111)
{\cgnode{$D$}{$\top$}};
\draw[goto, bend left=10] (1) to node[action, above, anchor=south west, near end]{$\{\cur{x}{\geq}\pre{x}\}$} (11);
\draw[goto, loop right, out=5, in=-5, looseness=7] (11) to node[action, right]{$\{\cur{x}{\geq}\pre{x}\}$} (11);
\draw[goto, loop right, out=5, in=-5, looseness=7] (111) to node[action, right]{$\Theta$} (111);
\draw[goto] (11) to node[action, right, anchor=west]{$\{\cur{x}{<}\pre{x}\}$} (111);
\draw[goto] (12) to node[action, left, anchor=east]{$\{\cur{x}{\geq}\pre{x}\}$} (111);
\draw[goto, loop left, out=175, in=185, looseness=7] (12) to node[action, left]{$\{\cur{x}{<}\pre{x}\}$} (12);
\draw[goto, bend right=10] (1) to node[action, above, anchor=south east, near end]{$\{\cur{x}{<}\pre{x}\}$} (12);
\end{tikzpicture}
\caption{\label{fig:cgs}Constraint graphs $\CG_\psi(A)$ and $\CG_\psi(B)$.}
\end{figure*}
\end{example}
\lemmacg*
\begin{proof}
(a) By induction on $w$.
If $w$ is empty then $(P_0, \varphi_{\mathit{init}}) = (P, \varphi)$, and since $h(w) = \varphi_{\mathit{init}}$,
the claim holds.
For the inductive step, let $w = w'\cdot\langle\varsigma\rangle$ and consider a path
$(P_0, \varphi_{\mathit{init}}) \gotos{w'} (P',\varphi') \goto{\varsigma} (P, \varphi)$.
By the induction hypothesis,
$P_0 \gotos{w'} P'$ and $\varphi' \sim h(w')$.
By Def.~\ref{def:cg}, the edge $(P',\varphi') \goto{\varsigma} (P, \varphi)$ exists
because $P' \goto{\varsigma}P$ in $\DFA$, and $\update(\varphi', \varsigma) \sim \varphi$. We thus have $P_0 \gotos{w} P$.
Moreover, by Def.~\ref{def:summary}, $\update(\varphi', \varsigma) \sim \update(h(w'), \varsigma)$, and as $\update(\varphi', \varsigma) \sim \varphi$ and $\update(h(w'), \varsigma) = h(w)$, we have $\varphi \sim h(w)$.
(b) By induction on $w$.
If $w$ is empty, $P_0 = P$. Then the empty path satisfies the claim.
For the inductive step, let $w = w'\cdot\langle\varsigma\rangle$ and suppose
$P_0 \gotos{w'} P' \goto{\varsigma} P$ and $h(w)$ is satisfiable.
Then also $h(w')$ is satisfiable, and by the induction hypothesis
there is a path $(P_0, \varphi_{\mathit{init}}) \gotos{w'} (P',\varphi')$ such that $\varphi' \sim h(w')$.
As $h(w) = \update(h(w'), \varsigma)$ is satisfiable, also
$\update(\varphi', \varsigma)$ is satisfiable by Def.~\ref{def:summary},
so there must be an edge
$(P',\varphi') \goto{\varsigma} (P, \varphi)$ in the constraint graph such
that $\varphi \sim \update(\varphi', \varsigma)$.
Again by Def.~\ref{def:summary}, $\varphi' \sim h(w')$ implies
$\update(\varphi', \varsigma) \sim \update(h(w'), \varsigma)$, so $\varphi \sim h(w)$.
\end{proof}
\lemmaabstraction*
\begin{proof}
($\Longrightarrow$)
Suppose $h(w)$ is satisfied by $\nu$.
We construct a respective trace $\tau$ by induction on $n$.
In the base case, $w$ is empty and $h(w) = \varphi_{\mathit{init}}$, so for $\nu$ it must hold that $\nu(v_0) = \nu(v)$ for all $v\in V$.
For $\alpha$ the assignment with domain $V$ such that $\alpha(v)=\nu(v)$,
the trace $\langle\alpha\rangle$ satisfies the claim as it is consistent with $\langle\emptyset\rangle$.
In the induction step, $w = \langle \varsigma_0, \dots, \varsigma_{n}\rangle$ and we assume that
$h(w)$ is satisfied by $\nu$.
For $w' = \langle \varsigma_0, \dots, \varsigma_{n-1}\rangle$,
we have $h(w) = \update(h(w'), \varsigma_{n}) = \exists \vec U. h(w')(\vec U) \wedge \bigwedge \varsigma_{n}(\vec U, \vec V)$.
As $\nu \models h(w)$,
there must be an assignment $\beta$ with domain $U\cup V \cup V_0$ that satisfies
$h(w')(\vec U) \wedge \bigwedge \varsigma_{n}(\vec U, \vec V)$ ($\star$)
such that $\beta$ coincides with $\nu$ on $V$ and $V_0$.
Let $\nu'$ be the assignment with domain $V\cup V_0$ such that
$\nu'(\vec V) = \beta(\vec U)$ and $\nu'(\vec V_0) = \beta(\vec V_0)$,
which must satisfy $h(w')$.
By the induction hypothesis there is a trace $\tau' = \langle\alpha_0, \dots, \alpha_n\rangle$ consistent with $\langle\emptyset\rangle\cdot w'$ and $\nu'(v_0) = \alpha_0(v)$ and $\nu'(v) = \alpha_n(v)$ for all $v\in V$.
Let $\alpha_{n+1}$ be the assignment with domain $V$ such that $\alpha_{n+1}(v)=\nu(v)$ for all $v\in V$. By ($\star$), $\combine{\alpha_n}{\alpha_{n+1}} \models \bigwedge \varsigma_{n}$, so $\tau = \langle\alpha_0, \dots, \alpha_{n+1}\rangle$ is consistent with $\langle\emptyset\rangle\cdot w$ and
satisfies the claim because
$\nu(v_0) = \nu'(v_0) = \alpha_0(v)$ and $\nu(v) = \alpha_{n+1}(v)$ for all $v\in V$
by construction.
($\Longleftarrow$)
Suppose $\langle\alpha_0, \dots, \alpha_{n}\rangle$ is consistent with
$\langle\emptyset\rangle\cdot w$.
We show that the assignment $\nu$ such that $\nu(v_0) = \alpha_0(v)$ and $\nu(v) = \alpha_n(v)$ for all $v\in V$ satisfies $h(w)$, by induction on the length $n$ of $w$.
If $n=0$, i.e., $w$ is empty, then $h(w) = \varphi_{\mathit{init}}$.
As $\tau$ has length 1, $\alpha_0 = \alpha_n$, so the assignment
$\nu$ must satisfy $\nu(v_0) = \nu(v)$ for all $v\in V$, hence $\nu \models h(w)$ by definiiton of $\varphi_{\mathit{init}}$.
In the induction step, let
$w = \langle \varsigma_0, \dots, \varsigma_{n}\rangle$ and suppose
$\tau = \langle\alpha_0, \dots, \alpha_{n+1}\rangle$
is consistent with $\langle\emptyset\rangle\cdot w$.
In particular, $\combine{\alpha_n}{\alpha_{n+1}} \models \bigwedge \varsigma_{n}$ ($\star$).
Thus, $\tau' = \langle\alpha_0, \dots, \alpha_{n}\rangle$ is
consistent with $\langle\emptyset\rangle\cdot w'$ for $w' = \langle \varsigma_0, \dots, \varsigma_{n-1}\rangle$.
By the induction hypothesis, the assignment $\nu'$ with domain $V \cup V_0$
given by
$\nu'(v_0) = \alpha_0(v)$ and $\nu'(v) = \alpha_n(v)$ for all $v\in V$
satisfies $h(w')$.
We have $h(w) = \update(h(w'), \varsigma_{n}) = \exists \vec U.\, h(w')(\vec U) \wedge \bigwedge \varsigma_{n}(\vec U, \vec V)$.
As $\nu' \models h(w')$, and because of ($\star$), assignment $\nu$ given by
$\nu(v_0) = \alpha_0(v)$ and $\nu(v) = \alpha_{n+1}(v)$ for all $v\in V$
satisfies $h(w)$.
\end{proof}
\subsection{Concrete criteria for solvability}
\theoremMC*
\begin{proof}
Our definition of history constraints (Def.~\ref{def:history constraint}) differs slightly from that in \cite{FMW22a} (due to a different notion of $\update$ and no fixed initial assignment).
However, the proof proceeds almost exactly as \cite[Thm.~5.2]{FMW22a} -- we sketch it here for completeness:
As all constraints in $\DFA$ are MC$_{\mathbb Q}$'s, there is a finite set $K$ of constants occurring therein.
Let MC$_K$ be the set of quantifier-free boolean formulas where all atoms are MCs over variables $V_0 \cup V$ and constants in $K$, so MC$_K$ is finite up to equivalence.
We show that $\Phi := \mathcal Q \times \text{MC}_K$ is a finite history set, by showing that for any history constraint $h(w)$ of $\DFA$, there is a formula $\varphi \in \text{MC}_K$ s.t. $\varphi \equiv h(w)$, by induction on $w$.
If $w$ is empty, $h(w) = \varphi_{\mathit{init}} \in \text{MC}_K$.
If $w = \langle\varsigma\rangle\cdot w'$ then $h(w) = \update(h(w'), \varsigma) = \exists \vec U.\,h(w')(\vec U) \wedge \chi$ for some $\chi \in \text{MC}_K$.
By induction hypothesis, $h(w')$ is equivalent to some $\varphi' \in \chi$.
Thus, $h(w) \equiv \exists \vec U.\,\varphi'(\vec U) \wedge \chi$, and
a quantifier elimination procedure \'{a} la Fourier-Motzkin ~\cite[Sec. 5.4]{KS16}
can produce a quantifier-free formula equivalent to the above that is again in MC$_K$.
As $\Phi$ is a finite history set, $(\Phi, \equiv)$ is a finite summary, so by Cor.~\ref{cor:main}, monitoring is solvable.
\end{proof}
\paragraph{Bounded lookback.}
Given a property $\psi$ with over $V_{\mathit{cur}} \cup V_{\mathit{pre}}$ and $\DFA[\psi]$ with states $P$, $P'$,
let $w=\langle\varsigma_0, \dots, \varsigma_{n-1}\rangle\in \Theta_{\mathit{cur}}\Theta^*$ be a word such that $P \to^*_w P'$.
For each $0\,{\leq}\,i\,{<}\,n$, let $W_i$ be a fresh set of variables of the same size and sorts as $V$, and $\mathcal W = \bigcup_{i=0}^{n-1} W_i$.
The \emph{computation graph} $G_w$ of a word $w$ is the undirected graph with nodes $\mathcal W$ and an edge from $x\in W$ to $y\in W$ iff the two variables occur in a common literal of
$\varsigma_0(\vec W_0)$, or $\varsigma_i(\vec W_{i-1}, \vec W_i)$ for $0<i<n$.
The subgraph of $G_{w}$ of all edges corresponding to equality literals $x=y$ for $x, y \in \mc V$ is denoted $E_{w}$.
Moreover, we denote by $[G_{w}]$ the graph obtained from $G_{w}$ by collapsing
all edges in $E_{w}$.
\begin{definition}
$\DFA[\psi]$ has \emph{bounded lookback} if there is some $K$ such that for all
$w \in \Theta_{\mathit{cur}}\Theta^*$
all acyclic paths in $[G_{w}]$ have length at most $K$.
\end{definition}
\begin{example}
\label{exa:computation graphs}
For $\psi = \mathsf{X}_w\xspace (\mathsf{G}\xspace (\cur{x}{>}\pre{y} \wedge \cur{x}{=}\cur{y})$, a DFA $\DFA$ is shown below, where we abbreviate $c_1 = \cur{x}{>}\pre{y}$ and $c_2 = \cur{x}{=}\cur{y}$.\\
\resizebox{\columnwidth}{!}{
\begin{tikzpicture}[node distance=20mm]
\node[state, minimum width=6mm] (0) {$0$};
\node[state, minimum width=6mm, right of =0, final] (1) {$1$};
\node[state, right of=1, minimum width=6mm, xshift=20mm] (2) {$2$};
\draw[edge] ($(0) + (-.5,0)$) -- (0);
\draw[edge] (0) -- node[action, above] {$\Theta_{\mathit{cur}}$} (1);
\draw[edge] (1) -- node[action, above] {\begin{tabular}{c}$\{neg(c_1), c_2\}$\\$\{c_1, neg(c_2)\}$\\$\{neg(c_1), neg(c_2)\}$\end{tabular}} (2);
\draw[edge] (1) to[loop above, looseness=6] node[action, above] {$\{c_1, c_2\}$} (1);
\draw[edge] (2) to[loop above, looseness=6] node[action, above] {$\Theta$} (2);
\begin{scope}[xshift=50mm, xscale=.6, yscale=.8]
\node[scale=.7] at (-1,.5) {$x$};
\node[scale=.7] at (-1,.1) {$y$};
\node[scale=.7] at (-1,1) {state};
\foreach \i/\l in {0/0,1/1,2/1,3/1,4/2} {
\node[scale=.65] at (\i,1.3) {\i};
\node[scale=.65] (state\i) at (\i,1) {$\m\l$};
\node[fill, circle, inner sep=0pt, minimum width=1mm] (x\i) at (\i,.5) {};
\node[fill, circle, inner sep=0pt, minimum width=1mm] (y\i) at (\i,.1) {};
}
\foreach \s/\t in {0/1, 1/2, 2/3, 3/4} {
\draw[->, shorten >=.6mm, shorten <=.6mm] (state\s) -- (state\t);
}
\draw (x0) -- (y0);
\draw (x1) -- (y1);
\draw (x2) -- (y2);
\draw (x3) -- (y3);
\draw (x4) -- (y4);
\draw[dotted] (y0) -- (x1);
\draw[dotted] (y1) -- (x2);
\draw[dotted] (y2) -- (x3);
\draw[dotted] (y3) -- (x4);
\end{scope}
\end{tikzpicture}
}
The computation graph for the word
$w = \{c_2\},\{c_1, c_2\}, \{c_1, c_2\}, \{c_1, neg(c_2)\}$ is shown on the right,
where equality edges are drawn solid, and other edges dotted.
In $G_w$ the maximal path length is 9, while in $[G_w]$ it is 4 (i.e., after collapsing equality edges).
However, as the loop in state 1 can be executed an unbounded number of times, the path length is unbounded as the pattern in the above $G_w$ repeats.
Thus $\DFA$ does not have bounded lookback, and neither does $\psi$.
\end{example}
\theoremboundedlookback*
\begin{proof}
Let $\psi$ have $K$-bounded lookback, for some $K>0$, and $\Phi$ be the set of formulas with free variables $V\cup V_0$,
quantifier depth at most $K$, and using as atoms all constraints in
$\DFA$, but where variables in $V_{\mathit{cur}}\cup V_{\mathit{pre}}$ may be replaced by $V$ or any of the quantified variables.
Being a set of formulae with bounded quantifier depth over a finite vocabulary, $\Psi$ is finite up to equivalence.
To prove that $\mathcal Q \times\Phi$ is a history set,
we show that for every $w\in \Theta_{\mathit{cur}}\Theta^*$, $\Phi$ contains a formula $\varphi$ such that $\varphi \equiv h(w)$.
It then follows that $(\Phi, \equiv)$ is a finite summary.
The proof is by induction of $w$.
If $w$ is empty, $h(w) = \varphi_{\mathit{init}}$ has quantifier depth 0, so there is
a formula in $\Phi$ equivalent to $h(w)$ by definitio of $\Phi$.
Otherwise, $w = w'\cdot\langle\varsigma\rangle$, and
$h(w) = \update(h(w'), \varsigma)$.
By induction hypothesis there is some $\varphi' \in \Phi$ with $\varphi' \equiv h(w')$.
By definition of $\update$, we have $h(w) \equiv \exists \vec U. \varphi'(\vec U) \wedge \chi$ for some quantifier free formula $\chi\in \Phi$.
Let $[\varphi]$ be obtained from $\varphi$ by eliminating all equality literals $x=y$ in $\varphi$ and uniformly substituting all variables in an equivalence class by some arbitrary representative.
Since $\DFA$ has $K$-bounded lookback, and $[\varphi]$ encodes a part of
$[G_{w}]$,
$[\varphi]$ is equivalent to a formula $\phi$ of quantifier depth at most $K$ over the same vocabulary,
obtained by dropping irrelevant literals and existential quantifiers, so that $\phi \in \Phi$.
Since $\psi$ admits a finite summary, monitoring is solvable by Cor.~\ref{cor:main}.
\end{proof}\
\begin{example}
\label{exa:bounded}
Consider a reactive system with two sensors $x$ and $y$ that are updated in each cycle.
The system has two clients who issue requests if conditions $x+y \leq 5$ and $2x - y > 7$ are satisfied, respectively.
Additionally, values of $y$ are non-negative, and it is known that if at some point $x \geq 5$ then $x$ will never be lower than this threshold in the future. In order to check whether the two requests can be issued at the same time, the conjunction of the
following properties can be monitored:
$\mathsf{G}\xspace(x+y \leq 5 \to \mathsf{X}_w\xspace \mathit{req}_1)$,
$\mathsf{G}\xspace(2x-y > 7 \to \mathsf{X}_w\xspace \mathit{req}_2)$,
$\mathsf{G}\xspace (y \geq 0)$,
$\mathsf{G}\xspace (x\geq 5 \to x' \geq 5)$, and
$\mathsf{F}\xspace (\mathit{req}_1 \wedge \mathit{req}_2)$
Note that the variables $\mathit{req}_1$ and $\mathit{req}_2$ are here used as booleans, but they can easily be modeled as integers.
This property has 1-bounded lookback, because in all atoms with multiple variables, comparisons are only among variables at the same instant. Thus, monitoring is solvable and can be used to e.g. detect that once $x$ is larger than 5, the property is permanently violated.
\end{example}
\theoremMCZ*
\begin{proof}
We modify our monitoring approach as indicated in the proof sketch, and describe here only the missing details:
Let $\alpha := \alpha_n$ be the last assignment of a given trace, as in procedure \textsc{Monitor}.
Let $\mathcal K$ be the finite set of integers that contains all constants occuring in $\psi$ and $\alpha$, as well as $0$.
We use the finite summary $(\text{GC}_K, \sim_K)$ described in \cite{FMW22a} when computing constraint graphs, where $K = max \{k-k' \mid k, k'\in \mathcal K\}$.
When computing CGs in line 5 of the procedure, we start from the formula $\varphi_\alpha := \bigwedge v = \alpha(v)$ instead of $\varphi_{\mathit{init}}$.
For the correctness proof, the notion of a history constraints changes such that
for the empty word $w$, $h(w) = \varphi_\alpha$.
Thus, history constraints are formulas with free variables $V$ (the variables $V_0$ are no longer necessary).
Lem.~\ref{lem:abstraction} changes to the following statement:
For $w\in \Theta^*$ of length $k$,
$h(w)$ is satisfied by assignment $\nu$ with domain $V$ iff
$\langle\emptyset\rangle\,{\cdot}\,w$ is consistent with a trace $\alpha_0, \dots, \alpha_{k}$
such that $\nu(v_0)\,{=}\, \alpha(v)$ and $\nu(v)\,{=}\, \alpha_k(v)$ for all $v\in V$.
That is, the statement is as before, but the initial assignment is fixed to $\alpha$.
The notions of a history set and a summary as well as Lem.~\ref{lem:cg}, are as before, but with the updated notion of history constraints.
By reasoning as in \cite[Thm.~5.5]{FMW22a} a finite summary exists, so the CG computation will terminate.
The statement of Thm.~\ref{thm:lookahead1:monitoring} changes as follows:\\
\emph{For a DFA $\DFA$ for $\psi$ and a trace $\tau$, let $w\in \Theta_{\mathit{cur}}\Theta^*$ be
the word consistent with $\tau$ and
$P$ the $\DFA$ state
s.t. $\{q_0\} \gotos{w} P$. For $G:= \CG_\psi(P, \sim_K)$ the constraint graph from $P$,
\begin{compactitem}
\item
if $P\,{\in}\,P_F$ then $\tau \models \llbracket \psi{=}\textsc{cs} \rrbracket$ if
$G$ has a non-empty path to a non-final state, and $\tau \models \llbracket \psi{=}\text{\textsc{ps}} \rrbracket$ otherwise,
\item
if $P\,{\not\in}\,P_F$ then $\tau \models \llbracket \psi{=}\textsc{cv} \rrbracket$ if
$G$ has a non-empty path to a final state, and $\tau \models \llbracket \psi{=}\textsc{pv} \rrbracket$ otherwise.
\end{compactitem}}
The proof of the theorem is almost as before. E.g. for the first case, if $P\,{\in}\,P_F$ and $G$ has a path to a non-final state $(P',\varphi)$, then by Lem.~\ref{lem:cg} $P \to_u^+ P'$ and $\varphi \sim h(u)$ is satisfiable. By the modified Lem.~\ref{lem:abstraction} there is a trace consistent with $u$ starting with $\alpha$. We can build the extension $\tau''$ of $\tau$ as in the proof of Thm.~\ref{thm:lookahead1:monitoring}, which is consistent with $wu$ and leads to the non-accepting state $P'$, so by the results on automata $\tau'' \not\models \psi$ and hence $\tau \models \llbracket \psi{=}\textsc{cs} \rrbracket$.
\end{proof}
| {'timestamp': '2022-12-01T02:19:30', 'yymm': '2211', 'arxiv_id': '2211.17166', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17166'} | arxiv |
\section{Introduction}
\firstword{T}{ he
Research in natural language processing aims to gather knowledge on how human beings understand and use a particular language so that appropriate tools and techniques can be developed to make computer systems understand languages to perform the desired task. NLP is the ability of a computer program to understand human language as it is spoken and written. \\
ASR( Automatic Speech Recognition) deals with audio inputs and delivers a transcript on a particular device. Data coming from customer care service phone calls/products or a service inquiry call/ product or a service complaint call or a service review call recordings can come through by passing them through a speech-to-text converter. Sensing vibrations via the phone call recordings and measuring and detailing those waves to distinguish the relevant sounds land in a suitable format to segment the data to match them with phenomes that are run through a mathematical model. Fairly accurate textual data is obtained through this process which can save the conversation transcription for further processing.
The conversation audio is passed to the model which is based on Wav2Vec transformer. It is a state of the art model which is trained in 2 phases. It is an Automatic Speech Recognition model based on self supervised training.[12][15] The two phases include:\\
1. Self supervised Mode: This contains the unlabelled data.\\
2. Supervised Fine tuning: during which the labelled data is used to teach model to predict particular words or phenomes.
For extracting primary details such as name, residential area, product details such as the brand, its pricing, and detailing regarding that product, Named Entity Recognition can be used for processing that data. It involves the identification of key information in the text and classification into a set of predefined categories. Here, an entity is a key that is consistently referred to in the text.
NER involves detecting the entities initially and then classifying the data into different categories. Here in this case although the classification of entities might not play a major role, the detection of the entities accurately and including all key details seem to be a necessity. NER can be done using multi-class classification, NLP speech tagging, and by using Deep learning. The model that is aimed to be used is the BERT-base-NER which is a fine-tuned Bidirectional Encoder Representation from Transformers. It's primarily trained to recognize location, organizations, persons, and miscellaneous details.
Deep learning can be categorized into various domains, among which transformers are a fairly recent development in the field. Transformers are designed to process sequential data and this process is done in one go. The context to every word is understood from the position in the input sequence. Transformer is an architecture for transforming one sequence to another with the help of 2 parts: Encoder and Decoder.
\includegraphics[scale=0.5]{transformer.png}
\textit{Image Courtesy :The
credit of this image is for (Vaswani et al., 2017). }\\
The Encoder is on the left and the Decoder is on the right. Both Encoder and Decoder are composed of modules that can be stacked on top of each other multiple times.
\section{Motivation}
As technology has progressed, the amount of data generated has grown exponentially. The business sector needs an efficient way to manage and handle data. So there has to be a productive way you can systematically gather the information and specific entities from the clients for the betterment and upgradation of their businesses. Customer reviews and customer satisfaction is a key factor in the improvisation of the product/service offered by the company.
As machine learning and artificial intelligence have been developing rapidly since the dawn of this century, various new algorithms and technologies are coming forward which are used to tackle a vast set of problems. Natural Language Processing is a subset of AI/ML that deals with giving computers the ability to understand text and spoken words in much the same way human beings can. Handling customer reviews can be simplified by using suitable NLP algorithms.
\section{Scope}
To understand the customer details transcribing the audio from the calls recorded using speech recognition Wav2Vec model, and then extracting key entities from the text generated using Named Entity Recognition. This simplifies the entire process of understanding the customer's review and would help the company for the betterment of the product/services.
\section{Literature Survey}
\subsection{Speech Recognition models:}
\subsubsection{Deep Speech by Baidu and Listen Attend Spell (LAS) by Google:}
Deep Speech and Listen Attend Spell both use recurrent neural network-based architectures for speech recognition. Deep Speech uses the Connectionist Temporal Classification (CTC) loss function to predict the speech transcript. LAS uses a sequence-to-sequence network architecture for its predictions. These models are built and trained in such a way that they can build and understand from larger datasets. With enough data, in theory, one would be able to build a super robust speech recognition model that can account for all the nuance in speech without having to spend a ton of time and effort hand-engineering acoustic features or dealing with complex pipelines in more old-school GMM-HMM model architectures.[3]
\subsubsection{Wav2Vec Model:}
Wav2vec is a speech recognition algorithm that uses raw, unlabeled audio to train automatic speech recognition (ASR) models which beats the traditional ASR systems that rely solely on transcribed audio, including a 22 percent accuracy improvement over Deep Speech 2 while using two orders of magnitude less labeled data.Wav2vec trains models to learn the difference between original speech examples and modified versions, often repeating this task hundreds of times for each second of audio and predicting the correct audio milliseconds into the future. Wav2Vec reduces the need for data to be manually annotated for developing systems of limited training sets and non english languages. Wav2Vec 2.0 comes under the category of self-supervised learning and development which requires self-training, where a teacher model is used to improve the performance of a student model by generating labels for the unlabeled set the student can train on. Self-training has been a popular technique in ASR studied extensively in the literature [7][15].\\
There is little domain mismatch between the unlabeled data for pre-training, the labeled data for fine-tuning and the domain of the test data, or the target domain. Domain is like an area where we are particularly working. Due to this, the performance of ASR systems trained from scratch with conventional supervised objectives can degrade significantly when tested on domains mismatched from training data [5]. Adding unlabeled in-domain data improves performance, even when the fine-tuning data does not match the
test domain[6]. The need for large annotated data in training remains a challenge for research in this area, especially for specific domains as per survey [8].
\begin{figure*}[thpb]
\centering
\includegraphics[width=\textwidth, height=110mm]{dark_web.png}
\caption{NER based on BERT}\vspace{4 mm}
\textit{Image Courtesy: S. Hu, H. Zhang, X. Hu and J. Du, "Chinese Named Entity Recognition based on BERT-CRF Model," }
\label{fig:my_label}
\end{figure*}
\subsection{Named entity recognition models}
\subsubsection{Ontology-based NER}
Ontology-based NER refers to understanding through knowledge bases that are normally a collection of datasets containing terms and their interrelations. This type of learning strongly relies on updates. Otherwise, it can’t keep up with the ever-growing publicly available knowledge. This model includes a knowledge-based recognition process where datasets containing terms are interrelated together using dictionaries and other mapping techniques.[2]
\subsubsection{Deep learning NER}
Deep Learning NER is much more precise than its Ontological NER as it is able to cluster words. This could be possible due to word embedding, that can understand the syntactic and semantic relationship between words. Deep learning can recognize terms \& concepts not present in Ontology because it is trained on the way various concepts are used in the written life science language. It is able to learn automatically and analyzes topic-specific as well as high-level words. This makes deep learning NER applicable for a variety of tasks. Researchers, for example, can use their time more efficiently as deep learning does most of the repetitive work. They can focus more on research. Currently, there are several deep-learning methods for NER available. But due to competitiveness and recency of developments, it is difficult to pinpoint the best one on the market. [4]
A machine learning technique is also presented in [13] to improve the precision of extracting entities related to organizations and persons. The first seed utilizes building and training the machine learning algorithm for some categories across domains, languages, and other applications. Multiple NER models can be constructed and implemented in order to emphasize the importance of certain architectural elements of the model as well as the features being used. [11]
\subsubsection{NER based on BERT}
The bert-based NER is divided into 3 layers:
the BERT pre-training layer, BiLSTM-IDCN-ELU neural network layer, and the CRF inference layer
\emph{Pre-training:} in this step, the corpus is divided into 2 levels: word level and character level. the effect of entity recognition based on character vectors is more accurate. the BERT embedding layer is chosen to add position information to the characters, and its structure consists of Token Embeddings, Segment Embeddings, and Position Embeddings, respectively.[1]
\begin{figure*}
\centering
\includegraphics[width=\textwidth]{speech.png}
\caption{Wav2Vec Model}\vspace{4 mm}
\textit{Image Courtesy: https://neurosys.com/blog/wav2vec-2-0-framework}
\end{figure*}
\emph{BiLSTM-IDCNN-ELU Neural Network Layers:} Long Short-Term Memory Neural Networks are a special kind of RNN. Its neurons have three parts: input gate, forgetting gate, and output gate. The input gate controls which information is input, the forgetting gate controls which information is forgotten in the neuron, and the output gate controls which information is output. to avoid the problem of losing the historical features due to the long sentences by splicing the features in both directions, to better learn the contextual features and solve the long-distance dependency problem so we use bidirectional LSTM.
Dilated Convolutional Neural Networks (DCNN) are a particular type of CNN with a convolution kernel that adds a dilation distance d, which can learn local features better. Iterated Dilated Convolutional Neural Networks (CNN) are composed of multiple layers of DCNNs with different dilation widths.ELU is Exponential Linear Unit. [1]\\
\emph{CRF:} They can effectively check the labels of columns and improve recognition accuracy. Therefore, CRF Conditional random fields are used as an inference layer to avoid label position errors.[1] Deep learning has developed rapidly and
received increasingly attention, and neural network meth-
ods are widely used in many NLP tasks, including the
CNER task. Neural network approaches, especially for
BiLSTM-CRF model, can significantly
improve the performance of the NER task.[9][10]
\section{Model Description}
\subsection{Speech Recognition:}
Raw data is more easily available and accessible. This raw data is not labelled. self-supervised learning is such a new technique which is beneficial in pre-training a model which is unlabelled. Wav2Vec 2.0 is a state of the art model for Automatic Speech Recognition using this self supervised training.
The Wav2Vec model is trained in 2 phases. The first phase is the pre-training phase, which used the unlabelled data, does self-supervised learning on it and attempts to achieve best speech representation as possible. This basically generates word embeddings of audio. The second phase of training is supervised fine tuning, here a labelled data is used to teach the model to predict particular words or phenomes.[14] Phenome here refers to a unit of sound. For this second phase, an appropriate labelled training set is a requirement which is not easily available. This phase tailors the model to predict words according to our own requirement.\vspace{0.8mm}
Wav2Vec 2.0 Model Architecture
The architecture of the final model used for prediction is divided into 3 main parts:
convolutional layers that process the raw waveform input to get latent representation - Z,
transformer layers, creating contextualized representation - C,
linear projection to output - Y.\vspace{0.8mm}
Contrastive learning is a machine learning technique in which unlabelled data points are placed against each other to determine their similarities and their differences. Self-supervised training is based on the idea of contrastive learning. As labelled dataset is not readily available, this technique is of immense help in getting satisfying results.\vspace{0.8mm}
It uses convolutional layers to preprocess raw waveform and then it applies transformer to it. Transformer enhances the speech representation with context.
\subsection{Named Entity Recognition}
BERT stands for Bidirectional Encoder Representations from Transformers. This is a pre-trained transformer. This model was trained based keeping in mind the left and right contexts of a particular word. As both the right and left contexts are considered, all words in the sentence are considered. Their effect on the focus word is considered.
BERT model achieves state-of-the-art accuracy on several tasks as compared to other RNN architectures. However, it needs high computational power and it takes a lot of time to train a model. After this we fine tune the model to get our desired results.
BERT is a language transformer heavily based on Transformers. It takes embedding tokens of one or more sentences as input. The first token is called as CLS. The sentences are separated by tokens called SEP. BERT outputs an embedding token called hidden state. Bert was trained on the masked language model and next sentence prediction tasks.
In the masked language model (MLM), an input word (or token) is masked and BERT has to try to figure out what the masked word is. The next task is next sentence prediction (NSP), here 2 sentences are taken as input. BERT then figures out whether the second sentence sematically follows the first sentence or not.
If you think about it, solving the named entity recognition task means classifying each token with a label like person name, location, etc. The hidden state of each token is obtained and fed to a classification layer.
The words of a sentence are tokenized. In this model, we have used bert-base-NER.
BERT uses a method of masked language modeling to keep the word in focus from "seeing itself" or having a fixed meaning independent of its context. BERT then identifies the masked word based on context alone. In BERT, words are defined by their surroundings. It relies on self attention mechanism.
\section{Algorithm}
\begin{enumerate}
\item The recorded audio is passed to the speech recognition model. The speech recognition model is based on transformers, particularly Wav2Vec.
\item The model transcribes the speech to text and gives it as an output.
\item The generated output is then based on the Entity recognition model which is based on the BERT transformer.
\item The model then extracts the entities from the generated text and presents them as the output of the process.
\item The output contains the important information which is present in the audio like the order id and thus makes it easier to get information easily from conversations.
\end{enumerate}
\section{Limitations and Future work}
\subsection{Limitations}
This research provides the first step toward understanding customer requirements and reviews through conversations. The main limitation is the efficiency of the model due to the unavailability of sufficient data regarding this domain and the specific design of a platform that can handle this scenario.
The main problem here lies during NER, as the model is predefined we just need to fine tune it. This requires a properly annotated dataset. The topic of our choosing is extracting entities from customer conversations, so there should be a dataset available for the same which isnt readily available. So the requirement of the dataset is a limitation for the model's fine-tuning.
\subsection{Future Work}
Design of an end-to-end application or development of an API that can directly extract entities with a highly accurate recognition model.
\begin{center}
\includegraphics[scale=0.6]{flowchart.png}\\
\textbf{Fig 4.} Flowchart of working
\end{center}
\section{Conclusions}
Using the methodology of Transfer learning we have fine-tuned the model to extract appropriate entities from the customer conversations that would help in the improvement of the business and services. With the help of Named Entity Recognition models and Speech recognition models, customer reviews can be efficiently extracted and that can work in the enhancement of the performance of the product. Wav2Vec model proved to be a suitable model when it comes to the efficient speech to text translation. \\
\begin{filecontents*}{Bibliografy.bib}
\end{filecontents*}
\bibliographystyle{plainnat}
\section{Introduction}
\firstword{T}{ he
Research in natural language processing aims to gather knowledge on how human beings understand and use a particular language so that appropriate tools and techniques can be developed to make computer systems understand languages to perform the desired task. NLP is the ability of a computer program to understand human language as it is spoken and written. \\
ASR( Automatic Speech Recognition) deals with audio inputs and delivers a transcript on a particular device. Data coming from customer care service phone calls/products or a service inquiry call/ product or a service complaint call or a service review call recordings can come through by passing them through a speech-to-text converter. Sensing vibrations via the phone call recordings and measuring and detailing those waves to distinguish the relevant sounds land in a suitable format to segment the data to match them with phenomes that are run through a mathematical model. Fairly accurate textual data is obtained through this process which can save the conversation transcription for further processing.
The conversation audio is passed to the model which is based on Wav2Vec transformer. It is a state of the art model which is trained in 2 phases. It is an Automatic Speech Recognition model based on self supervised training.[12][15] The two phases include:\\
1. Self supervised Mode: This contains the unlabelled data.\\
2. Supervised Fine tuning: during which the labelled data is used to teach model to predict particular words or phenomes.
For extracting primary details such as name, residential area, product details such as the brand, its pricing, and detailing regarding that product, Named Entity Recognition can be used for processing that data. It involves the identification of key information in the text and classification into a set of predefined categories. Here, an entity is a key that is consistently referred to in the text.
NER involves detecting the entities initially and then classifying the data into different categories. Here in this case although the classification of entities might not play a major role, the detection of the entities accurately and including all key details seem to be a necessity. NER can be done using multi-class classification, NLP speech tagging, and by using Deep learning. The model that is aimed to be used is the BERT-base-NER which is a fine-tuned Bidirectional Encoder Representation from Transformers. It's primarily trained to recognize location, organizations, persons, and miscellaneous details.
Deep learning can be categorized into various domains, among which transformers are a fairly recent development in the field. Transformers are designed to process sequential data and this process is done in one go. The context to every word is understood from the position in the input sequence. Transformer is an architecture for transforming one sequence to another with the help of 2 parts: Encoder and Decoder.
\includegraphics[scale=0.5]{transformer.png}
\textit{Image Courtesy :The
credit of this image is for (Vaswani et al., 2017). }\\
The Encoder is on the left and the Decoder is on the right. Both Encoder and Decoder are composed of modules that can be stacked on top of each other multiple times.
\section{Motivation}
As technology has progressed, the amount of data generated has grown exponentially. The business sector needs an efficient way to manage and handle data. So there has to be a productive way you can systematically gather the information and specific entities from the clients for the betterment and upgradation of their businesses. Customer reviews and customer satisfaction is a key factor in the improvisation of the product/service offered by the company.
As machine learning and artificial intelligence have been developing rapidly since the dawn of this century, various new algorithms and technologies are coming forward which are used to tackle a vast set of problems. Natural Language Processing is a subset of AI/ML that deals with giving computers the ability to understand text and spoken words in much the same way human beings can. Handling customer reviews can be simplified by using suitable NLP algorithms.
\section{Scope}
To understand the customer details transcribing the audio from the calls recorded using speech recognition Wav2Vec model, and then extracting key entities from the text generated using Named Entity Recognition. This simplifies the entire process of understanding the customer's review and would help the company for the betterment of the product/services.
\section{Literature Survey}
\subsection{Speech Recognition models:}
\subsubsection{Deep Speech by Baidu and Listen Attend Spell (LAS) by Google:}
Deep Speech and Listen Attend Spell both use recurrent neural network-based architectures for speech recognition. Deep Speech uses the Connectionist Temporal Classification (CTC) loss function to predict the speech transcript. LAS uses a sequence-to-sequence network architecture for its predictions. These models are built and trained in such a way that they can build and understand from larger datasets. With enough data, in theory, one would be able to build a super robust speech recognition model that can account for all the nuance in speech without having to spend a ton of time and effort hand-engineering acoustic features or dealing with complex pipelines in more old-school GMM-HMM model architectures.[3]
\subsubsection{Wav2Vec Model:}
Wav2vec is a speech recognition algorithm that uses raw, unlabeled audio to train automatic speech recognition (ASR) models which beats the traditional ASR systems that rely solely on transcribed audio, including a 22 percent accuracy improvement over Deep Speech 2 while using two orders of magnitude less labeled data.Wav2vec trains models to learn the difference between original speech examples and modified versions, often repeating this task hundreds of times for each second of audio and predicting the correct audio milliseconds into the future. Wav2Vec reduces the need for data to be manually annotated for developing systems of limited training sets and non english languages. Wav2Vec 2.0 comes under the category of self-supervised learning and development which requires self-training, where a teacher model is used to improve the performance of a student model by generating labels for the unlabeled set the student can train on. Self-training has been a popular technique in ASR studied extensively in the literature [7][15].\\
There is little domain mismatch between the unlabeled data for pre-training, the labeled data for fine-tuning and the domain of the test data, or the target domain. Domain is like an area where we are particularly working. Due to this, the performance of ASR systems trained from scratch with conventional supervised objectives can degrade significantly when tested on domains mismatched from training data [5]. Adding unlabeled in-domain data improves performance, even when the fine-tuning data does not match the
test domain[6]. The need for large annotated data in training remains a challenge for research in this area, especially for specific domains as per survey [8].
\begin{figure*}[thpb]
\centering
\includegraphics[width=\textwidth, height=110mm]{dark_web.png}
\caption{NER based on BERT}\vspace{4 mm}
\textit{Image Courtesy: S. Hu, H. Zhang, X. Hu and J. Du, "Chinese Named Entity Recognition based on BERT-CRF Model," }
\label{fig:my_label}
\end{figure*}
\subsection{Named entity recognition models}
\subsubsection{Ontology-based NER}
Ontology-based NER refers to understanding through knowledge bases that are normally a collection of datasets containing terms and their interrelations. This type of learning strongly relies on updates. Otherwise, it can’t keep up with the ever-growing publicly available knowledge. This model includes a knowledge-based recognition process where datasets containing terms are interrelated together using dictionaries and other mapping techniques.[2]
\subsubsection{Deep learning NER}
Deep Learning NER is much more precise than its Ontological NER as it is able to cluster words. This could be possible due to word embedding, that can understand the syntactic and semantic relationship between words. Deep learning can recognize terms \& concepts not present in Ontology because it is trained on the way various concepts are used in the written life science language. It is able to learn automatically and analyzes topic-specific as well as high-level words. This makes deep learning NER applicable for a variety of tasks. Researchers, for example, can use their time more efficiently as deep learning does most of the repetitive work. They can focus more on research. Currently, there are several deep-learning methods for NER available. But due to competitiveness and recency of developments, it is difficult to pinpoint the best one on the market. [4]
A machine learning technique is also presented in [13] to improve the precision of extracting entities related to organizations and persons. The first seed utilizes building and training the machine learning algorithm for some categories across domains, languages, and other applications. Multiple NER models can be constructed and implemented in order to emphasize the importance of certain architectural elements of the model as well as the features being used. [11]
\subsubsection{NER based on BERT}
The bert-based NER is divided into 3 layers:
the BERT pre-training layer, BiLSTM-IDCN-ELU neural network layer, and the CRF inference layer
\emph{Pre-training:} in this step, the corpus is divided into 2 levels: word level and character level. the effect of entity recognition based on character vectors is more accurate. the BERT embedding layer is chosen to add position information to the characters, and its structure consists of Token Embeddings, Segment Embeddings, and Position Embeddings, respectively.[1]
\begin{figure*}
\centering
\includegraphics[width=\textwidth]{speech.png}
\caption{Wav2Vec Model}\vspace{4 mm}
\textit{Image Courtesy: https://neurosys.com/blog/wav2vec-2-0-framework}
\end{figure*}
\emph{BiLSTM-IDCNN-ELU Neural Network Layers:} Long Short-Term Memory Neural Networks are a special kind of RNN. Its neurons have three parts: input gate, forgetting gate, and output gate. The input gate controls which information is input, the forgetting gate controls which information is forgotten in the neuron, and the output gate controls which information is output. to avoid the problem of losing the historical features due to the long sentences by splicing the features in both directions, to better learn the contextual features and solve the long-distance dependency problem so we use bidirectional LSTM.
Dilated Convolutional Neural Networks (DCNN) are a particular type of CNN with a convolution kernel that adds a dilation distance d, which can learn local features better. Iterated Dilated Convolutional Neural Networks (CNN) are composed of multiple layers of DCNNs with different dilation widths.ELU is Exponential Linear Unit. [1]\\
\emph{CRF:} They can effectively check the labels of columns and improve recognition accuracy. Therefore, CRF Conditional random fields are used as an inference layer to avoid label position errors.[1] Deep learning has developed rapidly and
received increasingly attention, and neural network meth-
ods are widely used in many NLP tasks, including the
CNER task. Neural network approaches, especially for
BiLSTM-CRF model, can significantly
improve the performance of the NER task.[9][10]
\section{Model Description}
\subsection{Speech Recognition:}
Raw data is more easily available and accessible. This raw data is not labelled. self-supervised learning is such a new technique which is beneficial in pre-training a model which is unlabelled. Wav2Vec 2.0 is a state of the art model for Automatic Speech Recognition using this self supervised training.
The Wav2Vec model is trained in 2 phases. The first phase is the pre-training phase, which used the unlabelled data, does self-supervised learning on it and attempts to achieve best speech representation as possible. This basically generates word embeddings of audio. The second phase of training is supervised fine tuning, here a labelled data is used to teach the model to predict particular words or phenomes.[14] Phenome here refers to a unit of sound. For this second phase, an appropriate labelled training set is a requirement which is not easily available. This phase tailors the model to predict words according to our own requirement.\vspace{0.8mm}
Wav2Vec 2.0 Model Architecture
The architecture of the final model used for prediction is divided into 3 main parts:
convolutional layers that process the raw waveform input to get latent representation - Z,
transformer layers, creating contextualized representation - C,
linear projection to output - Y.\vspace{0.8mm}
Contrastive learning is a machine learning technique in which unlabelled data points are placed against each other to determine their similarities and their differences. Self-supervised training is based on the idea of contrastive learning. As labelled dataset is not readily available, this technique is of immense help in getting satisfying results.\vspace{0.8mm}
It uses convolutional layers to preprocess raw waveform and then it applies transformer to it. Transformer enhances the speech representation with context.
\subsection{Named Entity Recognition}
BERT stands for Bidirectional Encoder Representations from Transformers. This is a pre-trained transformer. This model was trained based keeping in mind the left and right contexts of a particular word. As both the right and left contexts are considered, all words in the sentence are considered. Their effect on the focus word is considered.
BERT model achieves state-of-the-art accuracy on several tasks as compared to other RNN architectures. However, it needs high computational power and it takes a lot of time to train a model. After this we fine tune the model to get our desired results.
BERT is a language transformer heavily based on Transformers. It takes embedding tokens of one or more sentences as input. The first token is called as CLS. The sentences are separated by tokens called SEP. BERT outputs an embedding token called hidden state. Bert was trained on the masked language model and next sentence prediction tasks.
In the masked language model (MLM), an input word (or token) is masked and BERT has to try to figure out what the masked word is. The next task is next sentence prediction (NSP), here 2 sentences are taken as input. BERT then figures out whether the second sentence sematically follows the first sentence or not.
If you think about it, solving the named entity recognition task means classifying each token with a label like person name, location, etc. The hidden state of each token is obtained and fed to a classification layer.
The words of a sentence are tokenized. In this model, we have used bert-base-NER.
BERT uses a method of masked language modeling to keep the word in focus from "seeing itself" or having a fixed meaning independent of its context. BERT then identifies the masked word based on context alone. In BERT, words are defined by their surroundings. It relies on self attention mechanism.
\section{Algorithm}
\begin{enumerate}
\item The recorded audio is passed to the speech recognition model. The speech recognition model is based on transformers, particularly Wav2Vec.
\item The model transcribes the speech to text and gives it as an output.
\item The generated output is then based on the Entity recognition model which is based on the BERT transformer.
\item The model then extracts the entities from the generated text and presents them as the output of the process.
\item The output contains the important information which is present in the audio like the order id and thus makes it easier to get information easily from conversations.
\end{enumerate}
\section{Limitations and Future work}
\subsection{Limitations}
This research provides the first step toward understanding customer requirements and reviews through conversations. The main limitation is the efficiency of the model due to the unavailability of sufficient data regarding this domain and the specific design of a platform that can handle this scenario.
The main problem here lies during NER, as the model is predefined we just need to fine tune it. This requires a properly annotated dataset. The topic of our choosing is extracting entities from customer conversations, so there should be a dataset available for the same which isnt readily available. So the requirement of the dataset is a limitation for the model's fine-tuning.
\subsection{Future Work}
Design of an end-to-end application or development of an API that can directly extract entities with a highly accurate recognition model.
\begin{center}
\includegraphics[scale=0.6]{flowchart.png}\\
\textbf{Fig 4.} Flowchart of working
\end{center}
\section{Conclusions}
Using the methodology of Transfer learning we have fine-tuned the model to extract appropriate entities from the customer conversations that would help in the improvement of the business and services. With the help of Named Entity Recognition models and Speech recognition models, customer reviews can be efficiently extracted and that can work in the enhancement of the performance of the product. Wav2Vec model proved to be a suitable model when it comes to the efficient speech to text translation. \\
\begin{filecontents*}{Bibliografy.bib}
\end{filecontents*}
\bibliographystyle{plainnat}
| {'timestamp': '2022-12-01T02:18:10', 'yymm': '2211', 'arxiv_id': '2211.17107', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17107'} | arxiv |
\section{Introduction}
\label{sec:introduction}
From Darwinian evolution, a process of local optimization,
emerged highly complex organisms.
An organism is, in a sense, a program encoded by DNA
determining physical actions based on observed data.
It is therefore natural to ask
whether it would also be possible to evolve through natural selection
computer code that solves a given problem.
This is the task at the heart of Genetic Programming.
This paper is aimed at describing a hill-climbing algorithm for
evolving a programs,
taking an approach that is quite different
from established Genetic Programming methods.
As a starting point,
let us consider an extremely simple hill-climbing algorithm
for evolving programs for a programming language $\mathscr L$.
For that algorithm,
we will need
\begin{enumerate}[(1)]
\item
an initial program $P_0 \in \mathscr L$,\footnote{
For example, this could be a randomly generated program
or a program that we are trying to debug.
}
\item
a scoring function $S : \mathscr L \to [0, 1]$
assessing how well a program is performing at solving a given task
with $1$ meaning perfect,\footnote{
$S$ will typically work by
running the program on a pre-defined list of inputs and
then comparing the actual outputs to the desired outputs,
assigning a score based on how many of these cases are correct.
} and
\item
for each program $P \in \mathscr L$,
a probability distribution $M(P)$ on $\mathscr L$
of \q{mutations} of $P$.
\end{enumerate}
The (non-deterministic) algorithm produces
a sequence of programs $P_0, P_1, \ldots \in \mathscr L$
where $P_0$ is the initial program and for $k \geq 1$
\[
P_k \defeq
\begin{cases}
P_k',
& \text{if $S(P_k') > S(P_{k - 1})$;} \\
P_{k - 1},
& \text{otherwise.}
\end{cases}
\]
where $P_k'$ is randomly sampled from $M(P_{k - 1})$.
The algorithm terminates with solution $P_k$ when $S(P_k) = 1$,
which may or may not happen eventually.
A good choice of the distribution $M(P)$ should minimize
the expected score loss
$
L(P) \defeq S(P) - \mathbb E[S(M(P))].
$
In particular, likely mutations should ideally
only affect the program behavior slightly.
However, small changes in code often have major effect on the behavior of the program,
so typically $L > 0$.
The objective of this paper is to describe
ways to improve and refine this primitive idea to make it feasible:
\begin{enumerate}[(1)]
\item
In \cref{sec:local},
we shall see how assign a score to each expression in a program
as opposed to the entire program at once.
In this way,
we get a more precise understanding of which parts of a program are buggy.
Later, these \q{local scores} are leveraged to choose mutations so that
the expressions that are the most buggy are
the most likely to be mutated.
\item
In \cref{sec:suppose},
we introduce $\mathbf{suppose}$-expressions.
These are expressions that are waiting to be promoted into $\mathbf{if}$-conditionals.
This two-stage process gives an efficient and precise way
to evolve conditions for $\mathbf{if}$-conditionals.
\item
In \cref{sec:principles},
we discuss greedy criteria
for when a mutation should be regarded successful.
Specifically, we will mutate one expression at a time,
and the mutation is regarded successful
if the score of the new expression is
strictly greater than the score of the old expression.
\item
In \cref{sec:cyclic},
we describe an evolutionary process which consists of \emph{cycles}.
Each cycle is divided into four stages:
stretching, mutation, rewinding, and compression.
This design allows us to probe new program structures
while avoiding endless program expansion.
\item
In \cref{sec:poc},
we present a basic proof-of-concept implementation of these ideas and
show that it is able to generate correct code for several small problems.
On one well-known problem, the even-parity problem,
we also compare our implementation to some found in the literature
and find that our methods outperforms the best of the considered implementations
by more than an order of magnitude.
\item
In \cref{sec:future},
we discuss future theoretical and practical directions,
including integration with Deep Learning techniques.
\end{enumerate}
\subsection{Functional Programming as a setting for Genetic Programming}
This paper is focused on functional programs,
although some of its techniques are applicable to other paradigms as well.
The lack of side effects lends itself to Genetic Programming
as it means that changing a part of the code has
a more predictable effect on the program behavior:
we need not worry about how a state change could affect
the behavior of expressions elsewhere in the program.
\section{Local Scoring}
\label{sec:local}
When evolving programs,
we need to be able to quantify how well a program is performing.
As we discussed in the introduction,
one could do that by assigning the program a score
based on how well it adheres to its test cases.
However, with such an approach to scoring,
if a test case fails,
we gain little insight into what parts of the code could be the root cause of the failure.
If we were able to trace back such failure to specific parts of the code,
we could focus on mutating those parts.
In this section, we explain a simple method for assigning each expression a score.
We assume that every type is an Algebraic Data Type
so that values can be viewed as trees;
each node corresponds to a value constructor
and its children correspond to its arguments.
Then, the idea is to augment each node in the value tree with a \emph{trace},
which is a list of expressions that could affect the value at that node.
To state this method precisely,
we formally describe a small programming language
implementing this idea.
\subsection{A programming language with traced values}
\label{subsec:language}
As the setting for this paper,
we consider a simplistic, functional programming language
whose values are \q{traced}.
We first describe its syntax:
\begin{align*}
f
\Coloneqq\ & g_1 \mid g_2 \mid \cdots
&
\text{function}
\\
c
\Coloneqq\ & \mathbf{True} \mid \mathbf{False} \mid d_1 \mid d_2 \mid \cdots
&
\text{value constructor}
\\
x
\Coloneqq\ & y_1 \mid y_2 \mid \cdots
&
\text{variable}
\\
t
\Coloneqq\ & 1 \mid 2 \mid \cdots
&
\text{expression tag}
\\
E
\Coloneqq\ &
x \mid
c(e, \ldots, e) \mid
f(e, \ldots, e)
&
\\
\mid\ &
\mathbf{case}\mathop{} e \mathop{}\mathbf{of}\mathop{}
c(x, \ldots, x) \to e;
\cdots;
c(x, \ldots, x) \to e
\mathop{}\mathbf{end}
\\
\mid\ &
\mathbf{if}\mathop{} e \mathop{}\mathbf{then}\mathop{}
e
\mathop{}\mathbf{else}\mathop{}
e
\mathop{}\mathbf{end}
\\
\mid\ &
\mathbf{suppose}\mathop{} e \mathop{}\mathbf{then}\mathop{}
e
\mathop{}\mathbf{end}
\\
e
\Coloneqq\ &
E^{(t)}
&
\text{tagged expression}
\\
D
\Coloneqq\ &
f(x, \ldots, x) = e
&
\text{function definition}
\\
P
\Coloneqq\ &
D \mid D; P
&
\text{program}
\end{align*}
We moreover stipulate that
\begin{enumerate}[(1)]
\item
in a program $P$,
each function $g_i$ may be declared at most once,
\item
in a program $P$,
each participating expression has a unique tag,
that is,
among all the bodies of functions and all their subexpressions,
each tag $i$ appears at most once,
\item
cases in a $\mathbf{case}$-expression should be disjoint,
that is,
the constructors appearing on the left-hand side of the arms
should be pairwise distinct,
\item
a variable can be bound at most once in each case of a $\mathbf{case}$-expression,
that is,
the left-hand side of the arm takes the form $c(x_1, \ldots, x_n)$
where $x_1, \ldots, x_n$ are pairwise distinct variables, and
\item
variables bound by a case of a $\mathbf{case}$-expression cannot
overshadow variables that are already bound.
\end{enumerate}
We now describe the typing rules.
We use a simple nominal type system with types
\[
\tau \Coloneqq \mathbf{Bool} \mid \tau_1 \mid \tau_2 \mid \cdots.
\]
A \emph{typing context} $\Gamma$ is a collection of judgments of the forms
\begin{enumerate}[(1)]
\item
a variable typing:
$x : \tau$,
\item
a function signature:
$f : (\tau, \ldots, \tau) \to \tau$, or
\item
a type definition:
$\tau \Coloneqq c(\tau, \ldots, \tau) \mid \cdots \mid c(\tau, \ldots, \tau)$.
\end{enumerate}
The typing rules are
\[
\inferrule[TrueType]
{}
{\Gamma \vdash \mathbf{True}^{(t)} : \mathbf{Bool}}
\qquad
\inferrule[FalseType]
{}
{\Gamma \vdash \mathbf{False}^{(t)} : \mathbf{Bool}}
\quad
\inferrule[VarType]
{x : a \in \Gamma}
{\Gamma \vdash x^{(t)} : a}
\]
\[
\inferrule[FunctionType]
{
\Gamma \vdash e_1 : a_1, \ldots, e_n : a_n
\\
f : (a_1, \ldots, a_n) \to b \in \Gamma
}
{\Gamma \vdash f(e_1, \ldots, e_n)^{(t)} : b}
\]
\[
\inferrule[ConstructorType]
{
\Gamma \vdash e_1 : a_1, \ldots, e_n : a_n
\\
a \Coloneqq \cdots \mid c(a_1, \ldots, a_n) \mid \cdots \in \Gamma
}
{\Gamma \vdash c(e_1, \ldots, e_n)^{(t)} : a}
\]
\[
\inferrule[CaseType]
{
a \Coloneqq
c_1(a_{1, 1}, \ldots, a_{1, n_1})
\mid
\cdots
\mid
c_m(a_{m, 1}, \ldots, a_{m, n_m})
\in \Gamma
\\
\Gamma \vdash
d : a
\\
\Gamma, \forall j. x_{1, j} : a_{1, j} \vdash e_1 : b
\\
\cdots
\\
\Gamma, \forall j. x_{m, j} : a_{m, j} \vdash e_m : b
}
{
\Gamma
\vdash
\mathbf{case}\mathop{} d \mathop{}\mathbf{of}\mathop{}
c_1(x_{1, 1}, \ldots, x_{1, n_1}) \to e_1;
\cdots;
c_m(x_{m, 1}, \ldots, x_{m, n_m}) \to e_n
\mathop{}\mathbf{end}^{(t)}
: b
}
\]
\[
\inferrule[IfType]
{\Gamma \vdash e_1 : a, e_2 : a, c : \mathbf{Bool}}
{
\Gamma \vdash
\mathbf{if}\mathop{} c \mathop{}\mathbf{then}\mathop{}
e_1
\mathop{}\mathbf{else}\mathop{}
e_2
\mathop{}\mathbf{end}^{(t)}
: a
}
\qquad
\inferrule[SupposeType]
{\Gamma \vdash e : a, c : \mathbf{Bool}}
{
\Gamma \vdash
\mathbf{suppose}\mathop{} c \mathop{}\mathbf{then}\mathop{}
e
\mathop{}\mathbf{end}^{(t)}
: a
}
\]
We shall often write just $P$ when we mean
a well-typed program $(P, \Gamma)$,
letting the typing context $\Gamma$ containing all the
type definitions and
function signatures
be implicit.
At last, we explain the semantics of our programming language.
The values of the programming language are
\[
v \Coloneqq c^{[\pm t, \ldots, \pm t]}(v, \ldots, v)
\]
where $\pm \Coloneqq + \mid -$.
Conceptually, each value constructor is tagged with a \emph{trace},
a list of expressions that could affect the value.
Its trace need not contain the traces of the arguments $(v, \ldots, v)$
whose traces in turn consist of expressions
that could affect the arguments but not the parent value constructor.
A sign $\pm$ should be thought of as measuring the \q{influence} of an expression:
$+$ means that if the value is bad then the expression should be punished, and
$-$ means that if the value is bad then the expression should be rewarded.
The relevance of $-$ will be revealed in \cref{sec:suppose}.
An \emph{evaluation context} $\sigma$ is a collection of bindings of the form
\[
B \Coloneqq x = v \mid f(x, \ldots, x) = e
\]
such that each variable $x$ and each function $f$
appears at most once in the left-hand sides.
For a program $P$,
one extracts an evaluation context $\sigma(P)$ by collecting all its function definitions.
We use the notation $\sigma \vdash e \downarrow v$ to denote that
an expression $e$
evaluates to a value $v$
in the evaluation context $\sigma$.
Furthermore, we make use of the notation
\[
\(c^{[t_{k + 1}, \ldots, t_n]}(v_1, \ldots, v_k)\)^{[t_0, \ldots, t_k,]}
\defeq
c^{[t_0, t_1, \ldots, t_n]}(v_1, \ldots, v_k)
\]
where $t_i$ are signed tags.
We shall sometimes elide the $+$ in $+ t$ for notational convenience.
The rules for evaluation are as follows.
\[
\inferrule[Var]
{}
{\sigma, x = v \vdash x^{(t)} \downarrow v^{[t,]}}
\qquad
\inferrule[Cons]
{\sigma \vdash e_1 \downarrow v_1, \ldots, e_n \downarrow v_n}
{\sigma \vdash c(e_1, \ldots, e_n)^{(t)} \downarrow c^{[t]}(v_1, \ldots, v_n)}
\]
\[
\inferrule[Call]
{
\sigma \vdash e_1 \downarrow v_1, \ldots, e_n \downarrow v_n
\\
x_1 = v_1, \ldots, x_n = v_n \vdash e \downarrow v
}
{\sigma, f(x_1, \ldots, x_n) = e \vdash f(e_1, \ldots, e_n)^{(t)} \downarrow v^{[t,]}}
\]
\[
\inferrule[Case]
{
\sigma \vdash d \downarrow c^{[t_1, \ldots, t_k]}(v_1, \ldots, v_n)
\\
\sigma, x_1 = v_1, \ldots, x_n = v_n \vdash e \downarrow v
}
{
\sigma \vdash
\mathbf{case}\mathop{} d \mathop{}\mathbf{of}\mathop{}
\cdots;
c(x_1, \ldots, x_n) \to e;
\cdots
\mathop{}\mathbf{end}^{(t_0)}
\downarrow v^{[t_0, t_1, \ldots, t_k,]}
}
\]
\[
\inferrule[IfTrue]
{
\sigma \vdash
c \downarrow \mathbf{True}^{[t_1, \ldots, t_n]},
e_1 \downarrow v
}
{
\sigma \vdash
\mathbf{if}\mathop{} c \mathop{}\mathbf{then}\mathop{}
e_1
\mathop{}\mathbf{else}\mathop{}
e_2
\mathop{}\mathbf{end}^{(t_0)}
\downarrow v^{[t_0, t_1, \ldots, t_n,]}
}
\]
\[
\inferrule[IfFalse]
{
\sigma \vdash
c \downarrow \mathbf{False}^{[t_1, \ldots, t_n]},
e_2 \downarrow v
}
{
\sigma \vdash
\mathbf{if}\mathop{} c \mathop{}\mathbf{then}\mathop{}
e_1
\mathop{}\mathbf{else}\mathop{}
e_2
\mathop{}\mathbf{end}^{(t_0)}
\downarrow v^{[t_0, t_1, \ldots, t_n,]}
}
\]
We postpone stating the semantics of $\mathbf{suppose}$-expressions to \cref{sec:suppose}.
Note that whenever an expression is evaluated,
the value it produces is tagged with a unique identifier for that expression.
The rules are defined in such a way that
each value ends up carrying traces of expressions that could affect the value.
To illustrate, let us elaborate a bit on the \textsc{Case} rule.
The rule says that what a $\mathbf{case}$-expression
evaluates to may be affected by
\begin{enumerate}[(1)]
\item
the $\mathbf{case}$-expression $t_0$ itself since, trivially,
replacing the entire $\mathbf{case}$-expression could change its value,
\item
those expressions $t_1, \ldots, t_n$ that
could affect the entirety, even the value constructor,
of the value attained by $d$ that we are casing on, and
\item
those expressions that could affect the value attained by
the body $e$ of the chosen arm.
\end{enumerate}
The rules \textsc{IfTrue} and \textsc{IfFalse} are quite similar.\footnote{
The reason that we include $\mathbf{if}$-conditionals
in spite of having $\mathbf{case}$-expressions
is that they simplify our discussion of $\mathbf{suppose}$-expressions
in \cref{sec:suppose}.
}
\subsection{Extracting local scores}
\label{subsec:local_score_algo}
We shall need to consider values with other kinds of tags.
Define
\[
v^u \Coloneqq c^{u}(v^u, \ldots, v^u).
\]
Of particular use are
untagged values $v^{()}$,
traced values $v = v^{[\pm t, \ldots, \pm t]}$ (recall the definitions from \cref{subsec:language}), and
score-tagged values $v^{[0, 1]}$.
Fix a base typing context $\Gamma_{\f{types}}$
containing just the type definitions we shall use.
To assign scores to expressions in a program $(P, \Gamma)$
with $\Gamma_{\f{types}} \subseteq \Gamma$,
we will need a \emph{test criterion}
consisting of the data
\begin{enumerate}[(1)]
\item
a name and signature $f : (a_1, \ldots, a_n) \to b$ for the function we are testing,
where $a_1, \ldots, a_n, b$ are types defined in $\Gamma_{\f{types}}$,
\item
untagged input values $(v_{1, k} : a_1, \ldots, v_{n, k} : a_n)$ for $k = 1, \ldots, N$, and
\item
for each $k = 1, \ldots, N$, an \emph{assessment function}
\[
s_{(v_{1, k}, \ldots, v_{n, k})} :
\{w \in v^{()} \mid w : b\}
\to
\{w \in v^{[0, 1]} \mid w : b\}
\]
which takes a $b$-typed value
and sets the tag at each node to a score
(but does not change the underlying value)
such that all the tags in
$
s_{(v_{1, k}, \ldots, v_{n, k})}(w)
$
are $1$
if and only if $w$ is the desired result of $f(v_{1, k}, \ldots, v_{n, k})$.\footnote{
Moreover,
scores above $0.5$ ought to represent \q{closer to right than to wrong} and
scores below $0.5$ \q{closer to wrong than to right}.
(This will later become important for $\mathbf{suppose}$-expressions.)
}
\end{enumerate}
We call the function specified in (1) the \emph{primary function}.
For example,
suppose $P$ consisted of
just one function definition $\text{swap}(x, y) = \cdots$ and
$\Gamma$ consisted of
the type definition
$\mathbf{Bool2} \Coloneqq \mathbf{Pair}(\mathbf{Bool}, \mathbf{Bool})$ and
the function signature
$\text{swap} : \mathbf{Bool2} \to \mathbf{Bool2}$.
If we were to assess how well $\text{swap}$ swaps the booleans in the pair
like $(x, y) \mapsto (y, x)$,
the test criterion could consist of
\begin{itemize}
\item[($1'$)]
the name and signature
$
\text{swap} : \mathbf{Bool2} \to \mathbf{Bool2},
$
\item[($2'$)]
the inputs
$\mathbf{Pair}^{()}(\mathbf{True}^{()}, \mathbf{True}^{()})$,
$\mathbf{Pair}^{()}(\mathbf{False}^{()}, \mathbf{True}^{()})$,
\\
$\mathbf{Pair}^{()}(\mathbf{True}^{()}, \mathbf{False}^{()})$,
$\mathbf{Pair}^{()}(\mathbf{False}^{()}, \mathbf{False}^{()})$, and
\item[($3'$)]
the assessment functions
\[
s_{\mathbf{Pair}(a_1^{()}, a_2^{()})} :
\mathbf{Pair}^{()}(b_1^{()}, b_2^{()})
\mapsto
\mathbf{Pair}^{(\delta(b_1, a_2) + \delta(b_2, a_1))/2}
(b_1^{\delta(b_1, a_2)}, b_2^{\delta(b_2, a_1)})
\]
where $\delta(x, y)$ is $1$ if $x = y$ and $0$ otherwise.
\end{itemize}
The assessment functions are defined in such a way
that the resulting tag to the $\mathbf{Pair}$ constructor measures
how close the value is to the desired value $\mathbf{Pair}(a_2^{()}, a_1^{()})$,
and the resulting tag to the boolean in each coordinate measures
how close the respective coordinate is to the desired value.
Notice how the assessment functions give perfect scores
when the behavior is as desired:
\[
s_{\mathbf{Pair}(a_1^{()}, a_2^{()})}(\mathbf{Pair}^{()}(a_2^{()}, a_1^{()}))
=
\mathbf{Pair}^{1}(a_2^{1}, a_1^{1}).
\]
Let us return to the general setup $(1)$-$(3)$
and explain how to compute a score for each expression in the program $P$.
We will assume that $f$ always terminates.\footnote{
This restriction can be dealt with
by imposing limits to the number of execution steps allowed
or by restricting what kinds of recursion are allowed.
The minutiae are dealt with in our proof-of-concept implementation;
see \cref{subsec:rec}.
}
The process for obtaining expression-level scores is as follows.
\begin{enumerate}[(a)]
\item
For each $k = 1, \ldots, N$,
evaluate the function call
$
f(\f{tr}(v_{1, k}), \ldots, \f{tr}(v_{n, k}))
$
and call its (traced) value $w_k$.
Here, $\f{tr}(v)$ is the traced value obtained from the untagged value $v$ by
setting each tag to the empty trace $[]$.
\item
For each $k = 1, \ldots, N$,
compute
$
w_k' \defeq s_{(v_{1, k}, \ldots, v_{n, k})}(\f{untag}(w_k))
$
where $\f{untag}(w_k)$ is the untagged value obtained from the traced value $w_k$ by
replacing each tag with $()$.
\item
For each node in $w_k$, extract
the positively charged tags $+ t_1, \ldots, + t_p$ from its trace,
the negatively charged tags $- u_1, \ldots, - u_q$ from its trace, and
the tag $s \in [0, 1]$ of the corresponding node in $w_k'$;
then collect all the tuples
$(t_i, s)$ for $i = 1, \ldots, p$ and
$(u_i, 1 - s)$ for $i = 1, \ldots, q$
into a list $\ell$.
\item
An expression in $P$ with the tag $t$ is assigned the score,
\[
S_P(t) \defeq
\frac
{\sum_{(t, s) \in \ell} s}
{\sum_{(t, s) \in \ell} 1}
\]
averaging over all the scores in $\ell$ associated to the tag $t$.
\end{enumerate}
Note how
a positively charged tag $+t$ in some trace in $w_k$ contribute to the average defining $S_P(t)$
with the score produced by
$
s_{(v_{1, k}, \ldots, v_{n, k})}
$
corresponding to the trace
whereas a negatively charged tag $- t$ contribute
with the inversion of that score.
The net effect is that
an expression with tag $t$ that appears in a trace positively charged
(resp.~negatively charged)
is incentivized to maximize (resp.~minimize) the score corresponding to that trace
if we are to maximize the score $S_P(t)$.
For the rest of the paper,
we shall fix a test criterion (with respect to the fixed $\Gamma_{\f{types}}$).
Moreover, from now on,
we will only consider programs $P$
that contain
the type definitions $\Gamma_{\f{types}}$ and
a function definition for the primary function (1).
In particular, for each such program $P$,
we get a scoring function $S_P$.
If $e$ is an expression in $P$ with expression tag $t$,
we write $S_P(e) \defeq S_P(t)$.
Also, when the context resolves ambiguity,
we shall omit the subscript $P$,
writing $S$ instead of $S_P$.
\section{\texttt{suppose}-expressions}
\label{sec:suppose}
Let us informally consider the problem of evolving code for
the minimum function
$
\f{min} : \Z \times \Z \to \Z.
$
We may assess a candidate implementation
based on some example arguments $A \subseteq \Z \times \Z$
ranging over small numbers.
Start with the initial program
\[
\tag{$P_0$}
\f{min}(n, m) = 0.
\]
This is not faring particularly well:
perhaps,
there are a few $(n, m) \in A$ with $0 = n \leq m$ or $0 = m \leq n$
but they make up an increasingly small fraction as $|A|$ grows.
If we try to mutate $P_0$ by replacing the body of $\f{min}(n, m)$
by various randomly chosen expressions and testing it on $A$,
it is not hard to find the improved program
\[
\tag{$P_1$}
\f{min}(n, m) = n,
\]
which performs a lot better:
it is correct whenever $n \leq m$
which is roughly $\frac12$ of the time.
However, at this point, we stagnate.
The next program we want is
\[
\tag{$P_2$}
\f{min}(n, m) = \mathbf{if}\mathop{} n \leq m \mathop{}\mathbf{then}\mathop{} n \mathop{}\mathbf{else}\mathop{} m \mathop{}\mathbf{end},
\]
but this is quite a leap from $P_1$ and
would therefore take a long time
to discover through picking out random expressions.
More complex examples are even less tractable.
How do we overcome this problem of evolving $\mathbf{if}$-conditionals?
$\mathbf{suppose}$-expressions allow us to separate
the problem of evolving the condition
from the problem of evolving the $\mathbf{else}$-branch.
In the above informal example,
small intermediate steps between $P_1$ and $P_2$ could be
\begin{align*}
&\f{min}(n, m) = n
\\
\becomes\ &
\f{min}(n, m) = \mathbf{suppose}\mathop{} \mathbf{True} \mathop{}\mathbf{then}\mathop{} n \mathop{}\mathbf{end}
\\
\becomes\ &
\f{min}(n, m) = \mathbf{suppose}\mathop{} n \leq m \mathop{}\mathbf{then}\mathop{} n \mathop{}\mathbf{end}
\\
\becomes\ &
\f{min}(n, m) = \mathbf{if}\mathop{} n \leq m \mathop{}\mathbf{then}\mathop{} n \mathop{}\mathbf{else}\mathop{} n \mathop{}\mathbf{end},
\\
\becomes\ &
\f{min}(n, m) = \mathbf{if}\mathop{} n \leq m \mathop{}\mathbf{then}\mathop{} n \mathop{}\mathbf{else}\mathop{} m \mathop{}\mathbf{end},
\end{align*}
Conceptually, $\mathbf{suppose}$-expressions encourage the condition,
initially constant $\mathbf{True}$,
to evolve to be $\mathbf{True}$ whenever the body is correct and $\mathbf{False}$ otherwise.
When the condition for the $\mathbf{suppose}$-expression is good enough,
we will promote the $\mathbf{suppose}$-expression into an $\mathbf{if}$-conditional:
\[
\mathbf{suppose}\mathop{} c \mathop{}\mathbf{then}\mathop{} e \mathop{}\mathbf{end}
\quad
\becomes
\quad
\mathbf{if}\mathop{} c \mathop{}\mathbf{then}\mathop{} e \mathop{}\mathbf{else}\mathop{} e \mathop{}\mathbf{end}.
\]
This evolutionary strategy is established in \cref{sec:cyclic}.
With this discussion in mind,
let us now state the semantics of $\mathbf{suppose}$-expressions.
We use the notation established in \cref{sec:local}.
Define ${-}{-}t \defeq +t$.
The rules are then as follows.
\[
\inferrule[SupposeTrue]
{
\sigma \vdash
c \downarrow \mathbf{True}^{[t_1, \ldots, t_n]},
e \downarrow v
}
{
\sigma \vdash
\mathbf{suppose}\mathop{} c \mathop{}\mathbf{then}\mathop{}
e
\mathop{}\mathbf{end}^{(t_0)}
\downarrow v^{[t_0, t_1, \ldots, t_n,]}
}
\]
\[
\inferrule[SupposeFalse]
{
\sigma \vdash
c \downarrow \mathbf{False}^{[t_1, \ldots, t_n]},
e \downarrow v
}
{
\sigma \vdash
\mathbf{suppose}\mathop{} c \mathop{}\mathbf{then}\mathop{}
e
\mathop{}\mathbf{end}^{(t_0)}
\downarrow v^{[t_0, -t_1, \ldots, -t_n,]}
}
\]
Thus, if we disregard traces,
$\mathbf{suppose}$-expressions just evaluate their bodies.
However, if we follow the Local Scoring model set out in \cref{sec:local},
we see that if $c$ evaluates to $\mathbf{True}$,
the better $e$ performs,
the higher score is assigned to $c$,
whereas if $c$ evaluates to $\mathbf{False}$,
the better $e$ performs,
the lower score is assigned to $c$.
We will need the following lemma in \cref{sec:cyclic}.
\begin{lemma}\label{lem:suppose_true}
Let $P$ be a program.
Suppose $P$ contains an expression
$
\mathbf{suppose}\mathop{} \mathbf{True}^{(t)} \mathop{}\mathbf{then}\mathop{}
e
\mathop{}\mathbf{end}^{(u)}.
$
Then $S(t) = S(u)$.
\end{lemma}
\begin{proof}
Recall the algorithm specified in \cref{subsec:local_score_algo}.
Note that the steps (a)-(c) are the same
no matter whether we are computing $S(t)$ or $S(u)$.
From the rule \textsc{SupposeTrue},
we see that during step (a),
$+u$ (resp.~$-u$) will always appear coupled with $+t$ (resp.~$-t$) in traces.
It follows that
$\ell$ has exactly $m$ pairs $(t, s)$
if and only if it has exactly $m$ pairs $(u, s)$.
Therefore,
\[
S(t)
=
\frac
{\sum_{(t, s) \in \ell} s}
{\sum_{(t, s) \in \ell} 1}
=
\frac
{\sum_{(u, s) \in \ell} s}
{\sum_{(u, s) \in \ell} 1}
=
S(u),
\]
completing the proof.
\end{proof}
\section{Some mutation principles}
\label{sec:principles}
We discuss here some simple principles for how to mutate programs
by leveraging Local Scoring.
These will be used in combination with
the methods presented in \cref{sec:cyclic}.
\subsection{Mutually exclusive mutation}
\label{subsec:mutex}
Changing a single expression has a high chance of breaking the program,
but changing multiple expressions has an even higher chance of doing so.
It therefore makes sense to change just one expression
in each mutation step.
A simple scheme to mutate a program $P$ is to first pick a random expression.
The probability for picking a given expression $e$
should be proportional to $1 - S(e)$,
so that
we are more likely to mutate what is broken and
we never mutate what works perfectly.\footnote{
In particular, under this scheme, dead code is never mutated.
}
This expression is then replaced by a new, randomly generated expression of the same type
(with expression tags disjoint from the expression tags used in $P$),
giving a new program $P'$, the mutant of $P$.
\subsection{Greedy Principle of Mutation}
\label{subsec:greedy}
Suppose we use a hill-climbing algorithm
which has as state a program $P$
that it repeatedly tries to mutate
until it finds a good mutant, a successor,
which then replaces $P$,
repeating this process until the program solves some task perfectly.
How do we determine if a given mutant $P'$ should replace $P$ as its successor?
If we go purely by some kind of global score based on the behavior of the program,
as in \cref{sec:introduction},
we fail to evolve the conditions for $\mathbf{suppose}$-expressions
changing which has no exterior effect on the program behavior.
We therefore propose another criterion.
Recall that we mutate a program $P$ to a program $P'$
by replacing some expression $e$ with a new expression $e'$.
The \emph{Greedy Principle of Mutation} stipulates
that $P'$ should be the successor to $P$ if and only if $S_{P'}(e') > S_P(e)$.
The principle is \q{greedy} since
the mutation can (and usually does) change the scores of
expressions that are not $e$ and
yet we only focus on how the score of $e$ changes.
Notice how the condition is
$S_{P'}(e') > S_P(e)$ as opposed to $S_{P'}(e') \geq S_P(e)$.
This is a deliberate choice.
It means that we prefer doing no mutation to mutating:
we only accept mutations that strictly improve the expression they change.
We shall refer to this property as \emph{mutation conservativity}.
\section{Cyclic Evolution}
\label{sec:cyclic}
We have described $\mathbf{suppose}$-expressions
but we have yet to explain
how $\mathbf{suppose}\mathop{}$ should be introduced during evolution and
when these should be promoted into $\mathbf{if}$-conditionals.
When mutating a program $P$,
we would like to sometimes replace an expression
\[
e \quad \becomes \quad \mathbf{suppose}\mathop{} \mathbf{True} \mathop{}\mathbf{then}\mathop{} e \mathop{}\mathbf{end}
\]
after which mutations can begin to improve $\mathbf{True}$ to a more meaningful condition.
If we were to just follow the simplistic scheme set out in \cref{sec:principles},
such replacement might happen
but the resulting program will never succeed the existing program
because the score of the replaced expression is the same as
the score of the original expression $e$.
One could circumvent this issue
by making an exception to mutation conservativity,
making this specific type of mutation always succeed.
This, however, is not a very good solution to the problem at hand:
the program would then grow unbounded
as we add more and more redundant $\mathbf{suppose}$-expressions.
What we propose instead is to divide the evolution into
phases of growth,
phases of mutation, and
phases of reduction;
similar to how a person
who is trying to gain muscle
might divide their eating into phases of bulking and phases of cutting.
Specifically, instead of proceeding one mutation at a time,
the basic unit of the algorithm will be a \emph{cycle}
consisting of four phases:
\begin{enumerate}[(1)]
\item
\emph{Stretching} in which a program is
replaced by an equivalent, more redundant program
by introducing
redundant $\mathbf{suppose}$-expressions,
redundant $\mathbf{if}$-conditionals,
redundant $\mathbf{case}$-expressions, and
redundant new functions.
\item
\emph{Mutation} in which a number small changes are made to the program,
replacing the program
whenever a mutation satisfying the Greedy Principle of Mutation is found.
\item
\emph{Rewinding} in which we try to undo the stretches done in (a).
\item
\emph{Compression} in which we try to
rewrite the program to an equivalent, smaller form.
\end{enumerate}
The algorithm we propose evolves programs by
repeatedly applying cycles until a program
performing perfectly (in accord with the test criterion) is found.
We describe basic ways to implement each phase.
We emphasize that each can be extended and refined in many ways,
some of which will be discussed in \cref{sec:future}.
\subsection{Stretching}
\label{subsec:stretch}
The stretching phase makes the program more redundant,
setting the scene for the mutation phase
to turn that redundancy into useful structure.
The stretching phase consists of $N_\f{stretch}$ \emph{stretches}
for some fixed constant $N_\f{stretch} > 0$.
Each stretch picks out a random expression in the program
with the probability of choosing an expression $e$
being proportional to $1 - S(e)$.
The stretched program $P'$ is constructed from $P$
by picking randomly among the following possibilities:
\begin{enumerate}[(1)]
\item
replacing
$e \becomes \mathbf{suppose}\mathop{} \mathbf{True} \mathop{}\mathbf{then}\mathop{} e \mathop{}\mathbf{end},$
\item
if $e = \mathbf{suppose}\mathop{} c \mathop{}\mathbf{then}\mathop{} e' \mathop{}\mathbf{end}$ and $S(c) > S(e')$,
replacing $e \becomes \mathbf{if}\mathop{} c \mathop{}\mathbf{then}\mathop{} e' \mathop{}\mathbf{else}\mathop{} e' \mathop{}\mathbf{end}$,
\item
picking a variable $x : \tau$ bound in the context of $e$
and replacing
\begin{align*}
e
\becomes\
&\mathbf{case}\mathop{} x \mathop{}\mathbf{of}\mathop{}
\\&
c_1(x_1, \ldots, x_{n_1})
\to
e[x/c_1(x_1, \ldots, x_{n_1})];
\\&
\cdots;
\\&
c_k(x_1, \ldots, x_{n_k})
\to
e[x/c_k(x_1, \ldots, x_{n_k})]
\\
&\mathop{}\mathbf{end},
\end{align*}
where
(a) $x_1, \ldots$ are variables that do not participate in $e$,
(b) $c_1, \ldots, c_k$ are the value constructors for $\tau$:
\[
\tau \Coloneqq
c_1(\cdots \text{($n_1$ arguments)})
\mid
\cdots
\mid
c_k(\cdots \text{($n_k$ arguments)}),
\]
and (c) $e[x/e']$ denotes $e$ with all occurrences of $x$ replaced by $e'$, or
\item
for
$
x_1 : a_1, \ldots, x_n : a_n
$
the variables bound in the context of $e : b$,
adding a new function
\begin{align*}
&f :
(b, a_1, \ldots, a_n)
\to
b
\\
&f(y, x_1, \ldots, x_n) = y
\end{align*}
and replacing
$
e \becomes f(e, x_1, \ldots, x_n).
$
\end{enumerate}
In each case, the replacing expression
should be tagged with some tags disjoint from those used in $P$,
but we elide this for notational simplicity.
Let us elaborate on the condition
$
S(c) > S(e')
$
in stretch (2).
The justification for this condition comes from \cref{lem:suppose_true}
which precludes stretch (2) from happening when $c = \mathbf{True}$.
In this way,
when a stretch (1) introduces a $\mathbf{suppose}$-expression,
the condition must first improve
(which can happen in the mutation phase)
before a stretch (2) can promote it into an $\mathbf{if}$-conditional.
As such, we don't end up immediately creating a lot of redundant $\mathbf{if}$-conditionals.
\subsection{Mutation}
The mutation phase consists of $N_\f{mutate}$ mutations, successful or not,
where $N_\f{mutate} > 0$ is some fixed constant.
A mutation changes the program in the way described \cref{subsec:mutex}.
A mutation is considered successful if it satisfies
the Greedy Principle of Mutation (see \cref{subsec:greedy})
in which case the mutant program replaces the program and the search continues.
\subsection{Rewinding}
The purpose of stretching was to create new program structures
that the mutation phase could make use of.
However, not all stretches create useful program structures.
If we return to our informal example of \cref{sec:suppose} with evolving the $\min$ function,
we could have the stretch
\begin{align*}
&\min(n, m) = \mathbf{if}\mathop{} n \leq m \mathop{}\mathbf{then}\mathop{} n \mathop{}\mathbf{else}\mathop{} n \mathop{}\mathbf{end}
\\
\becomes\ &
\min(n, m) = \mathbf{if}\mathop{} n \leq m \mathop{}\mathbf{then}\mathop{} n \mathop{}\mathbf{else}\mathop{} (\mathbf{suppose}\mathop{} \mathbf{True} \mathop{}\mathbf{then}\mathop{} n \mathop{}\mathbf{end}) \mathop{}\mathbf{end}
\end{align*}
But that wouldn't be of much use
because in the $\mathbf{else}$-branch $n$ is never the right expression.
So, unless the second $n$ is mutated,
the condition for the $\mathbf{suppose}$-expression will just converge to $\mathbf{False}$.
We must be able to deal effectively with such \q{useless stretches}
to stop the program that is being evolved from accumulating redundancy.
After the mutation phase has completed,
we propose to clean up the stretches
by \q{rewinding} them.
Specifically, for each stretching operation $s$,
we define a corresponding \emph{rewinding operation} $\overline s$,
which is a transformation of programs that undoes
(is left-inverse to)
$s$.
Then, if stretches
$
s_1, \ldots, s_{N_\f{stretch}}
$
were made in the stretching phase in that order,
the rewinding phase applies rewinding operations
$
\overline s_{N_\f{stretch}}, \ldots, \overline s_1
$
in that order
(notice the reversal of order).
For a stretch $s$ out of the $N_\f{stretch}$ stretches done in the stretching phase,
we will now describe its corresponding rewinding operation $\overline s$.
$\overline s$ depends on which type (1)-(4) of stretch $s$ is:
\begin{itemize}
\item[$(\overline 1)$]
If $s$ is a stretch of type (1),
$\overline s$ is the following program transformation.
Let $e_1, \ldots, e_n$ be the $\mathbf{suppose}$-expressions
that originated from $s$.
Let
$c_1, \ldots, c_n$ be their respective condition expressions and
$e_1', \ldots, e_n'$ their respective bodies.
For $i = 0, \ldots, n$,
replace $e_i \becomes e_i'$ if $S(c_i) \leq S(e_i)$.
\item[$(\overline 2)$]
If $s$ is a stretch of type (2),
$\overline s$ is the following program transformation.
Let $e_1, \ldots, e_n$ be the $\mathbf{if}$-conditionals
that originated from $s$.
Let
$c_1, \ldots, c_n$ be their respective condition expressions and
$e_1', \ldots, e_n'$ their respective $\mathbf{True}$-branches.
For $i = 0, \ldots, n$,
replace $e_i \becomes \mathbf{suppose}\mathop{} c_i \mathop{}\mathbf{then}\mathop{} e_i' \mathop{}\mathbf{end}$
if the latter expression attains a score in the program with this replacement made
at least the score $S(e_i)$.
\item[$(\overline 3)$]
If $s$ is a stretch of type (3),
$\overline s$ is the following program transformation.
Let $x$ be the variable chosen in $s$.
Let $e_1, \ldots, e_n$ be the expressions $\mathbf{case}\mathop{} x \mathop{}\mathbf{of}\mathop{} \cdots$
that originated from $s$.
Let
$
c_1(x_1, \ldots, x_{n_1}),
\ldots,
c_k(x_1, \ldots, x_{n_k})
$
be the cases that appear in each of those $\mathbf{case}$-expressions.
For $i = 1, \ldots, n$,
do the following.
\begin{enumerate}[(a)]
\item
Look for a $1 \leq j \leq k$ such that
(i) $n_j > 0$,
(ii) the expression
$
e_{i, j}' \defeq
e_{i, j}[c_j(x_1, \ldots, x_{n_j})/x],
$
where $e_{i, j}$ is the body of the $\mathbf{case}$-expression $e_i$ to the case $c_j$,
does not reference the variables $x_1, \ldots, x_{n_j}$, and
(iii) after replacing $e_i$ with $e_{i, j}'$,
the new $e_{i, j}'$ attains a score at least the score $S(e_i)$.
If such a $j$ exists,
replace $e_i \becomes e_{i, j}'$ in the program.
\item
If not, look instead for a $1 \leq j \leq k$ such that
(i) $n_j = 0$ and
(ii) after replacing $e_i$ with $e_{i, j}$,
the new $e_{i, j}$ attains a score at least the score $S(e_i)$.
If such a $j$ exists,
replace $e_i \becomes e_{i, j}$ in the program.
\item
If such a $j$ could not be found either, do nothing.
\end{enumerate}
\item[$(\overline 4)$]
If $s$ is a stretch of type (4),
$\overline s$ is the following program transformation.
Let $e_1, \ldots, e_n$ be the call-expressions
that originated from $s$.
Let $f$ be the name of the function they are calling.
Suppose its definition in the program is
$
f(x_1, \ldots, x_k) = e.
$
If $e$ contains a subexpression $f(\cdots)$, do nothing.
Otherwise, do the following.
For each $i = 1, \ldots, n$,
replace $e_i = f(a_1, \ldots, a_k) \becomes e[x_1/a_1]\cdots[x_k/a_k]$.
If after this transformation the expression $f(\cdots)$ appears nowhere in the program,
furthermore remove the function definition
$
f(x_1, \ldots, x_k) = e
$
from the program.
\end{itemize}
As before, we elide tags in notation,
implicitly tagging expressions with unique tags.
And again, $e[a/b]$ denotes the expression $e$ with all occurrences of $a$ replaced by $b$.
Note that in each of these rewinding operations,
we talk of possibly multiple expressions $e_1, \ldots, e_n$.
This is because an expression created by one stretch may be duplicated by another
(stretches of type (2) or (3)).
It is therefore necessary to track
what expressions originate in what stretches.
This can be done by tagging each expression by some extra bookkeeping data
of which we shall not deal with the details.
The condition $S(c_i) \leq S(e_i)$ in $(\overline 1)$
is again justified by \cref{lem:suppose_true}.
In particular, the condition is only fulfilled
if the condition $c_i$ is at least as bad as the initial condition $\mathbf{True}$.
In effect, we throw away a $\mathbf{suppose}\mathop{}$
if its condition didn't manage to improve at all during the mutation phase.
\subsection{Compression}
\label{subsec:compression}
The final phase is compression,
replacing the program by an equivalent, shorter form.
There are indeed many ways to approach this problem of removing excess;
we present one which we found works reasonably well in practice.
As input for the algorithm,
we need to run the program on the examples in the test criterion
that we fixed in \cref{subsec:local_score_algo}
(see step (a))
and collect for each expression $e$ an \emph{input--output table}:
the set with an element $(\sigma, \f{untag}(v))$
for each evaluation $\sigma \vdash e \downarrow v$ done.
We say that an expression $e$ is \emph{linear} if either
$e = x^{(t)}$ for $x$ a variable or
$e = c(e_1, \ldots, e_n)^{(t)}$ for
$c$ a value constructor and
$e_1, \ldots, e_n$ linear expressions.
Recall that we defined a program to consist of
a list of function declarations $f(x_1, \ldots, x_n) = e$.
The compression algorithm first applies the following procedure to each of the bodies $e$.
\begin{enumerate}[(1)]
\item
If $e = c(e_1, \ldots, e_n)^{(t)}$ for $c$ a value constructor,
apply the procedure recursively to $e_1, \ldots, e_n$.
\item
If $e = \mathbf{suppose}\mathop{} c \mathop{}\mathbf{then}\mathop{} b \mathop{}\mathbf{end}^{(t)}$,
apply the procedure recursively to $c$ and $b$;
and if after doing so
$e$ became
$e' = \mathbf{suppose}\mathop{} c' \mathop{}\mathbf{then}\mathop{} b' \mathop{}\mathbf{end}^{(t)}$
where $c'$ admits no variable $x^{(u)}$ as a subexpression,
further replace $e' \becomes b'$.
\item
If neither of the above cases apply, try to find
a linear expression $\ell$ with the behavior specified by the input--output table of $e$.
(The algorithm for finding $\ell$ is postponed to \cref{subsubsec:lexprs}.)
If such $\ell$ exists,
pick one and
replace $e \becomes \ell$
(in which we tag $\ell$ with expression tags disjoint from those used in $P$),
and we're done.
If not,
continue to the next steps.
\item
If $e = \mathbf{if}\mathop{} c \mathop{}\mathbf{then}\mathop{} a \mathop{}\mathbf{else}\mathop{} b \mathop{}\mathbf{end}^{(t)}$,
apply the procedure recursively to $c$, $a$, and $b$.
Suppose that after doing so
$e$ became
$e' = \mathbf{if}\mathop{} c' \mathop{}\mathbf{then}\mathop{} a' \mathop{}\mathbf{else}\mathop{} b' \mathop{}\mathbf{end}^{(t)}$.
If $c' = \mathbf{True}^{(u)}$ for some $u$,
further replace $e' \becomes a'$.
Or, if $c' = \mathbf{False}^{(u)}$ for some $u$,
further replace $e' \becomes b'$.
\item
If $e = f(e_1, \ldots, e_n)^{(t)}$ for $f$ a function,
apply the procedure recursively to $e_1, \ldots, e_n$.
\end{enumerate}
After this, the algorithm removes from the program function definitions
$
g(\cdots) = \cdots
$
for functions $g$ that are not reachable from the primary function $f$ in the call graph.
The resulting program is the result of the compression phase.
Note that, in each step
the $w_k$ used in
the definition of $S$ in \cref{subsec:local_score_algo}
remain unchanged if we disregard traces.
This is the sense in which the original program is equivalent to the compressed program,
that is,
they are equivalent on known input.
\subsubsection{An algorithm for finding linear expressions}
\label{subsubsec:lexprs}
We are presented with the problem of
listing the linear expressions $\ell$ satisfying a given specification.
Let us be more precise.
We are given
a type $\tau$,
a typing context $\Gamma$ containing a definition of $\tau$, and
an input--output table $T = \{(\sigma_1, v_1), \ldots, (\sigma_n, v_n)\}$
such that for each $i = 1, \ldots, n$,
(i) $\sigma_i$ is an evaluation context and $v_i$ an untagged value of type $\tau$ and
(ii) all variables found in $\sigma_i$ are found in $\Gamma$ and vice versa.
The task is then to compute the (untagged) linear expressions $\ell$
that evaluate\footnote{
according to semantics like those given in \cref{subsec:language}
but ignoring traces
}to $v_i$ in context $\sigma_i$ for every $i = 1, \ldots, n$.
If $n = 0$ (that is, the input--output table is empty),
the problem is equivalent to finding all linear expressions of type $\tau$.
This possibly infinite list can easily be computed by a breadth-first search
applied to the recursive definition of linear expressions
given near the beginning of \cref{subsec:compression}.
Now, suppose $n > 0$.
For convenience,
we shall rename the variables in $\Gamma$
so that they are called $x_1, \ldots, x_n$.
Recall the notation for tagged values established in \cref{subsec:local_score_algo}.
An \emph{$\ell$-value} is a tagged value $\in v^{\mathscr P(\{\circ, 1, \ldots, n\})}$
where $\mathscr P$ denotes the power set operator.
Moreover, given an $\ell$-value $w = c^A(w_1, \ldots, w_k)$,
define
\[
\ell(w)
\defeq
\{x_i^{()} \mid i \in \N \cap A\}
\cup
\begin{cases}
\{c^{()}(w_1', \ldots, w_k') \mid w_i' \in \ell(w_i)\},
& \text{if $\circ \in A$;} \\
\emptyset,
& \text{otherwise.}
\end{cases}
\]
\begin{lemma}
$\ell(w)$ is a finite set.
\end{lemma}
\begin{proof}
Proceed by induction over $w$:
assume that the lemma is true for every proper subvalue of $w$.
Note that $A$ is finite.
Since each $\ell(w_i)$ is finite by the induction hypothesis,
the induction step follows from the formula defining $\ell(w)$.
\end{proof}
To an input--output pair $(\sigma, v)$
where
$
v = c^{()}(v_1, \ldots, v_k),
$
we associate an $\ell$-value
\[
w(\sigma, v)
\defeq
c^{\{\circ\} \cup \{i \mid (x_i = v) \in \sigma\}}
(w(\sigma, v_1), \ldots, w(\sigma, v_k)).
\]
\begin{lemma}
$\ell(w(\sigma, v))$ is the set of linear expressions
that evaluates to $v$ in the evaluation context $\sigma$.
\end{lemma}
\begin{proof}
Proceed by induction on $v$:
assume that the lemma is true for every proper subvalue of $v$.
The linear expressions evaluating to $v$ in the context $\sigma$ are
the variables $x_i$ such that $(x_i = v) \in \sigma$ and
expressions $c(e_1, \ldots, e_k)$
where each $e_i$ is a linear expression evaluating to $v_i$ in the context $\sigma$.
The induction step follows from unfolding definitions.
\end{proof}
Given $\ell$-values
$w_1 = c_1^A(w_{1, 1}, \ldots, w_{1, p})$ and
$w_2 = c_2^B(w_{2, 1}, \ldots, w_{2, q})$,
define
\[
w_1 * w_2
\defeq
\begin{cases}
c_1^{A \cap B}(w_{1, 1} * w_{2, 1}, \ldots, w_{1, p} * w_{2, p}),
& \text{if $c_1 = c_2$;} \\
c_1^{A \cap B \setminus \{\circ\}}(w_{1, 1}, \ldots, w_{1, p}),
& \text{otherwise.}
\end{cases}
\]
\begin{lemma}
$\ell(w_1 * w_2) = \ell(w_1) \cap \ell(w_2)$.
\end{lemma}
\begin{proof}
Proceed by induction on $w_1$:
assume that the lemma is true
when $w_1$ is replaced by any $w_{1, i}$.
\para{Case: $c_1 = c_2$}
Using the induction hypothesis,
\begin{align*}
\ell(w_1 * w_2)
&=
\ell(c_1^{A \cap B}(w_{1, 1} * w_{2, 1}, \ldots, w_{1, p} * w_{2, p}))
\\
&=
\{x_i^{()} \mid i \in \N \cap A \cap B\}
\\
&\quad \cup
\begin{cases}
\{c_1^{()}(w_1', \ldots, w_n') \mid w_i' \in \ell(w_{1, i} * w_{2, i})\},
& \text{if $\circ \in A \cap B$;} \\
\emptyset,
& \text{otherwise.}
\end{cases}
\\
&=
\{x_i^{()} \mid i \in \N \cap A \cap B\}
\\
&\quad\cup
\begin{cases}
\{c_1^{()}(w_1', \ldots, w_n') \mid w_i' \in \ell(w_{1, i}) \cap \ell(w_{2, i})\},
& \text{if $\circ \in A \cap B$;} \\
\emptyset,
& \text{otherwise.}
\end{cases}
\\
&{{}=}
\(
\{x_i^{()} \mid i \in \N \cap \mask{B}{A}\}
\cup
\begin{cases}
\{c_1^{()}(w_1', \ldots, w_n') \mid w_i' \in \ell(w_{1, i})\},
& \text{if $\circ \in A$;} \\
\emptyset,
& \text{otherwise.}
\end{cases}
\)
\\
&\mask{{}=}{\cap}
\(
\{x_i^{()} \mid i \in \N \cap B\}
\cup
\begin{cases}
\{c_1^{()}(w_1', \ldots, w_n') \mid w_i' \in \ell(w_{2, i})\},
& \text{if $\circ \in B$;} \\
\emptyset,
& \text{otherwise.}
\end{cases}
\)
\\
&= \ell(w_1) \cap \ell(w_2).
\end{align*}
\para{Case: $c_1 \neq c_2$}
Unfolding definitions,
\begin{align*}
\ell(w_1 * w_2)
&=
\ell(c_1^{A \cap B \setminus \{\circ\}}(w_{1, 1}, \ldots, w_{1, p}))
\\
&=
\{x_i^{()} \mid i \in \N \cap A \cap B\}
\cup
\emptyset
\\
&{{}=}
\(
\{x_i^{()} \mid i \in \N \cap \mask{B}{A}\}
\cup
\begin{cases}
\{c_1^{()}(w_1', \ldots, w_n') \mid w_i' \in \ell(w_{1, i})\},
& \text{if $\circ \in A$;} \\
\emptyset,
& \text{otherwise.}
\end{cases}
\)
\\
&\mask{{}=}{{\cap}}
\(
\{x_i^{()} \mid i \in \N \cap B\}
\cup
\begin{cases}
\{c_2^{()}(w_1', \ldots, w_n') \mid w_i' \in \ell(w_{2, i})\},
& \text{if $\circ \in B$;} \\
\emptyset,
& \text{otherwise.}
\end{cases}
\)
\\
&=
\ell(w_1) \cap \ell(w_2).
\end{align*}
\end{proof}
We can now describe the algorithm for finding linear expressions.
Combining the lemmata above,
we find that the set
\[
\ell(w(\sigma_1, v_1) * \cdots * w(\sigma_n, v_n))
\]
contains exactly the linear expressions coforming to the input--output table $T$.
Since the definitions of $\ell$, $w$, and $*$ deal with
finite data in finite numbers of steps,
we can compute this set in its entirety by unfolding definitions,
thus giving an algorithm.
\section{A proof-of-concept implementation}
\label{sec:poc}
We provide a proof-of-concept implementation
which can be found at \url{https://gitlab.com/maxvi/ssgp}.
Excluding comments and blank lines,
it consists of a little less than 2700 lines of Haskell code.
Great care was taken to document the API and every piece of code,
amounting to over 1300 lines of comments.
Various QuickCheck tests are also included.
We emphasize that the implementation is a \emph{minimum viable product};
for instance, it is completely unoptimized
(see \cref{subsec:optimize}).
The implementation deviates from a naïve implementation of the theoretical ideas described above
in a number of ways,
many of which we shall cover in this section.
It produces code written in
what is, sparring $\mathbf{suppose}$-expressions, a subset of Haskell.
\subsection{Results}
\label{subsec:results}
We have chosen a few examples, tabulated below,
which highlight some strengths and weaknesses of our implementation.
\begin{figure}
\begin{tabular}{| l | l | l | c | r |}
\hline
Name
& Signature
& Avail.~funcs.
& Convergence
& Avg.~iter.
\\
\hline
$\f{sum}$
& $[\Z] \to \Z$
& $+ : (\Z, \Z) \to \Z$
& $5/5 = 100\%$
& 149.4
\\
$\f{min}$
& $(\Z, \Z) \to \Z$
& $\leq : (\Z, \Z) \to \mathbf{Bool}$
& $5/5 = 100\%$
& 373.6
\\
$\f{min}'$
& $[\Z] \to \Z$
& $\leq : (\Z, \Z) \to \mathbf{Bool}$
& $5/5 = 100\%$
& 1076.4
\\
$\f{insert}$
& $(\Z, [\Z]) \to [\Z]$
& $\leq : (\Z, \Z) \to \mathbf{Bool}$
& $5/5 = 100\%$
& 1485.6
\\
$\f{helloworld}$
& $() \to [\Z]$
&
& $5/5 = 100\%$
& 2611.0
\\
$\f{sort}$
& $[\Z] \to [\Z]$
& $\leq : (\Z, \Z) \to \mathbf{Bool}$
& $0/5 = \ \ \ 0\%$
& NA
\\
$\f{reverse}$
& $[\Z] \to [\Z]$
&
& $0/5 = \ \ \ 0\%$
& NA
\\
\hline
\end{tabular}
\caption{Some benchmarks of our proof-of-concept implementation.}
\end{figure}
\begin{figure}
\begin{minted}{haskell}
insert :: Int -> [Int] -> [Int]
insert x0 (Cons[Int] x1 (Cons[Int] x2 x3)) =
if f0 x0 x1 (Cons[Int] x2 x3) then
Cons[Int] x1 (insert x0 (Cons[Int] x2 x3))
else
Cons[Int] x0 (Cons[Int] x1 (Cons[Int] x2 x3))
insert x0 Nil[Int] = Cons[Int] x0 Nil[Int]
insert x0 (Cons[Int] x1 Nil[Int]) =
if f0 x0 x1 Nil[Int] then
Cons[Int] x1 (Cons[Int] x0 Nil[Int])
else
Cons[Int] x0 (Cons[Int] x1 Nil[Int])
f0 :: Int -> Int -> [Int] -> Bool
f0 x0 x1 x2 = leq x1 x0
\end{minted}
\caption{Example of code produced by our proof-of-concept implementation.}
\end{figure}
Each example was run five times.
Each run was set to have a maximum of 10 cycles (see \cref{sec:cyclic}),
after which we would declare the evolution to not converge.
The constants used were
$N_\f{stretch} = 3$ and
$N_\f{mutate} = 300$.
The last column records the average number of
iterations (stretches, mutations, rewindings, compressions) that occured
before evolution converged to correct code.
At each iteration,
a new program is proposed and
this program is then run on a pre-fixed set of examples
through which local scores are assigned.
Every type is an Algebraic Data Type.
Integers are encoded by their binary representation.
Lists are defined recursively in a left-biased way as
$
[\Z] \Coloneqq \mathbf{Cons}(\Z, [\Z]) \mid \mathbf{Nil}.
$
There is no standard library;
each example can only use the functions specified in the third column,
nothing else.
If one were to add more useful functions there,
one would get better convergence rates.
Let us elaborate on the behavior of some of the tabulated functions.
\q{$\min'$} picks out the smallest number from a list,
defaulting to $0$ if the list is empty.
\q{$\f{insert}$} inserts a number into a list of numbers before the first entry
that is greater than or equal to the number.
\q{$\f{helloworld}$} lists the ASCII codes for the string \q{Hello World}.
The rest are self-explanatory.
\subsection{Comparison with other works}
\label{subsec:compare}
Koza \cite{koza94} established the \emph{even-parity problem}
as a benchmark for Genetic Programming.
The goal is to evolve code for the function $[\mathbf{Bool}] \to \mathbf{Bool}$
which returns
$\mathbf{True}$ if the list has even number of $\mathbf{True}$s and
$\mathbf{False}$ otherwise.
Briggs and O'Neill \cite{briggs06} use this problem
to compare a number of approaches found in literature.
We reproduce their benchmarks below,
adding a benchmark of our own proof-of-concept implementation.
\begin{figure}
\begin{tabular}{| l | l | r |}
\hline
Approach
& Citation
& Assessments
\\
\hline
GP with Local Scoring
& This paper
& 674
\\
Exhaustive enumeration
& \cite{briggs06}
& 9478
\\
PolyGP
& \cite{yu99}
& 14,000
\\
GP with combinators
& \cite{briggs06}
& 58,616
\\
GP with iteration
& \cite{kirshenbaum01}
& 60,000
\\
Generic GP
& \cite{wong96}
& 220,000
\\
OOGP
& \cite{agapitos06}
& 680,000
\\
GP with ADFs
& \cite{koza94}
& 1,440,000
\\
\hline
\end{tabular}
\caption{
Comparison of the smallest number of program assessments needed
for $99\%$ convergence rate on the even-parity problem
across various approaches.
Smaller numbers are better.
(No claims as to exhaustiveness of listed approaches are made.)
}
\end{figure}
The last column records estimates for the smallest number of program assessments
needed during evolution
for an algorithm to find a correct solution with 99\% probability.
A \emph{program assessment} scores a program
by running it on a number of examples.
We ran our proof-of-concept implementation 100 times on the even-parity problem.
Every run eventually converged on correct code,
with the average number of programs tested before convergence being 335.3.
The best run needed to test just 79 programs and the worst 677 programs.
Generalizing from our data,
we find that if we stop evolution after 674 programs,
we arrive at a correct solution with $99\%$ probability.
The only built-in function made available from the onset was the binary operation,
$
\f{not} : \mathbf{Bool} \to \mathbf{Bool}.
$
\subsection{Local scores and deep recursion}
For scores $S(e)$,
we use instead a weighted average in which
each summand is weighted by the reciprocal of the call-stack depth.
In effect, deep recursive calls have less influence on scores.
\subsection{Continuous scoring}
\label{subsec:continuous}
The Hello World example uses a \q{continuous} scoring function,
meaning that it takes into account
how close the string that $\f{helloworld}()$ produces
is to the desired string \q{Hello World},
instead of just rewarding $1$ when correct and $0$ when incorrect
(in which case evolving the correct code would be virtually impossible).
Local scoring means that if $\f{helloworld}()$ returned the string \q{Hello Gorld},
we trace the problematic character, G, back to the expression that produced it
and then change that expression little by little,
inching in on the correct character, W.
\subsection{Timeouts and restrictions to recursion}
\label{subsec:rec}
A fundamental issue is that the problem of bounding the running time of
an arbitrary program in a Turing-complete language
is undecidable
as was famously shown by Turing in 1936 \cite{turing36}.
To overcome this issue,
we imposed restrictions on what is allowed during execution:
\begin{enumerate}[(1)]
\item
We impose a limit on
how many function calls can be made in one program execution.
If exceeded,
the local score of
every expression that was evaluated during the execution
gets punished.
\item
We impose restrictions on what forms of recursions are allowed.
Specifically, we shall only allow a call $f(v_1, \ldots, v_n)$
if there is an $i$
such that for all calls $f(w_1, \ldots, w_n)$ on the call-stack,
$|v_i| < |w_i|$.
Here, $|v|$ denotes the \q{size} of a value $v$,
that is, its number of nodes.
If this condition is violated,
the local score of every expression on the \q{expression stack}
(the expression-level analogue of the call-stack)
gets punished.
\end{enumerate}
The restriction (2) alone ensures termination,
as the following lemma shows.
\begin{lemma}
There is no infinite sequence $a_1, a_2, \ldots \in \N^n$
with the property that each $a_i$ has a coordinate $a_{i, j} \in \N$
such that $a_{i, j} < a_{i', j}$ for any $i' < i$.
\end{lemma}
\begin{proof}
Assume for contradiction that such sequence $a_*$ exists.
The sequence may be partitioned into $n$ subsequences,
$
p_{1, *}, \ldots, p_{n, *}
$
such that for each $i = 1, \ldots, n$,
$
p_{i, k, i} < p_{i, k', i}
$
for any $k' < k$.
Since $a_*$ is infinite,
one of these subsequences, say $p_{j, *}$, is infinite.
But then
$
p_{j, 1, j} > p_{j, 2, j} > \cdots
$
is an infinite descending sequence in $\N$,
which is not possible.
\end{proof}
\subsection{Controlled Recursion}
\label{subsec:controlled}
When a recursive function is broken,
it is usually catastrophically broken.
This is because errors propagate (and multiply) upwards through recursion.
This affects negatively the quality of the local scores
which we want to reflect \q{closeness} to a solution.
For example, if we were to define natural numbers inductively using successors,
$
\N \Coloneqq 0 \mid S(\N),
$
then the recursive definition
\begin{align*}
0 \oplus m &\defeq m
\\
S(n) \oplus m &\defeq n \oplus m
\end{align*}
is only one $S$ away from being the correct definition of addition
($S(n) \oplus m = S(n \oplus m)$),
yet in terms of actual behavior it is quite far away:
$n \oplus m = m$.
To deal with this issue,
we employ a technique we shall call \emph{Controlled Recursion},
in which we answer recursive calls using training data.
For example, if we were trying to evolve $\oplus$ to be addition,
we would,
when producing the values $w_1, \ldots, w_N$ in \cref{subsec:local_score_algo},
evaluate the recursive call $n \oplus m$
in the body of the second equation above as $n + m$
instead of using the actual code for $\oplus$.
That means that the output only differs by $1$ from the desired output,
and the score is accordingly better
(that is, if we use a continuous scoring function as in \cref{subsec:continuous})
than if we were to answer recursive calls using the actual code.
To discourage degenerate self-referential definitions like
$
S(n) \oplus m \defeq S(n) \oplus m,
$
we only answer recursive calls like this that are \q{smaller}
than the calls on the call-stack,
a la the restriction (2) we imposed in \cref{subsec:rec}.
\subsection{Stretches}
Since the examples did not appear to need it,
we disabled the stretch (4) described in \cref{subsec:stretch}.
Moreover, for stretch (1),
we only introduce $\mathbf{suppose}$-expressions
at the top of bodies of equations.\footnote{
It would probably be better to allow them to be introduced wherever
but have a mechanism pushing them up the expression tree (\q{generalization})
before they are promoted into $\mathbf{if}$-conditionals
so as to not have to reinvent the same conditions for various subexpressions.
}
\subsection{Limitations}
A significant issue is the performance suboptimality of our proof-of-concept implementation.
With optimized code execution,
we could perhaps try many times more mutations in the same amount of time,
thereby searching much deeper for new mutations.
We discuss this further in \cref{subsec:optimize}.
Another striking issue is that of overfitting.
For example, overfitting obstructs discovery of correct code for the function
$
\f{reverse} : [\Z] \to [\Z]
$
reversing the items of a list.
Instead of attacking the problem algorithmically,
it generates more and more cases:
one for the empty list $[]$,
one for $[x_1]$,
one for $[x_1, x_2]$,
and so on.
While it obviously does get closer to a correct solution in terms of behavior,
it does not approach a correct solution in terms of code.
The issue is that lists are defined recursively in a left-biased way,
making operations on the beginning of the list far easier to discover
than operations on the end.
A human is able to immediately tell that such code is bad style;
perhaps if one taught the same intuition to a neural network,
that could be used to stir away from overfitting.
See \cref{subsec:ml} for more discussion.
Overfitting was not an issue
in any of the converging examples from \cref{subsec:results}.
\section{Extensions and future work}
\label{sec:future}
\subsection{Crossover and parallelism}
In contrast to a lot of the literature (see \cref{subsec:compare}),
we use what is a kind of hill-climbing algorithm:
at every point in the algorithm,
we have exactly one program.
It is typical to instead evolve a population of programs,
mutating them and using a procedure called \emph{crossover}
to combine two programs producing one or more offspring programs.
We remark that
this could be added on top of our hill-climbing method,
making for highly parallelized Genetic Programming:
one could do $C$ cycles of hill-climbing (see \cref{sec:cyclic}) for each program in the population
$
\{P_{(1)}, \ldots, P_{(n)}\}
$
in parallel,
yielding a new population
$
\{P_{(1)}', \ldots, P_{(n)}'\}
$
which is then extracted for crossover
combining programs at random
and natural selection killing of all but $n$ of the resulting programs.
This procedure is repeated until a solution is found.
With this, many hill-climbing processes run in parallel but
still \q{share discoveries} once in a while,
avoiding too much duplicated effort.
\subsection{Optimizations}
\label{subsec:optimize}
By far the most significant component performance-wise is
that which executes programs.
As we were more focused on the theoretical background,
no serious attempt at optimizing this was made
in our proof-of-concept implementation written in Haskell.
Let us discuss some techniques and ideas
that could be used in a performant implementation.
\begin{enumerate}[(1)]
\item
Use a more performant language such as Rust or C.
\item
Currently, we represent code as an Abstract Syntax Tree
which is quite inefficient for a number of reasons.
For instance, execution requires dereferencing a lot of pointers
resulting in many cache misses.
A more efficient, flat representation of code,
such as a stack machine,
could be used instead.
\item
Expressions that attain high scores could be compiled,
making for extremely performant execution of those parts of the program
that are unlikely to change.
Compilation is typically a heavy process and
it is therefore unlikely that it is
worth it to recompile the entire program on every mutation,
but perhaps a good balance could be struck.
\item
Since we are running the same (or similar) code again and again,
it would make sense to make heavy use of memoization,
trading CPU cycles for increased memory usage.
\item
A significant amount of time is spent on testing out bad mutations,
typically scoring extremely poorly.
One could use heuristics for quickly discarding
large swaths of bad mutations with only few false positives.
Local Scoring is particularly apt for this.
For example, if one was to test a mutation $e \becomes e'$ of an expression $e$,
one could first compute the score of $e'$
with respect to a small, randomly chosen subset of $w_1, \ldots, w_N$
(see \cref{subsec:local_score_algo})
chosen so that for each $w_i$ in this subset
the expression $e'$ appears somewhere in one of its traces,
and then preemptively discard the mutation if this \q{approximate score} is
significantly smaller than $S(e)$.\footnote{
Or perhaps, instead of $S(e)$, it would be better to
use the corresponding approximate score computed for $e$.
This would necessitate storing not just the local scores
but also all summands of the averages,
so that averages of subsets can be computed at a later point.
}
\item
While our proof-of-concept implementation does ensure
that the exact same program isn't tried multiple times,
one could employ more advanced ways of ensuring
that equivalent mutations aren't attempted multiple times.
One would need to specify algorithms that are able to tell
if a mutation on a program $P$ corresponds
to a mutation on a program $P'$ equivalent to $P$ by a number of stretches
(see \cref{subsec:stretch}).
Perhaps a hash function could be devised for this purpose.
\end{enumerate}
\subsection{Integration with Deep Learning methods}
\label{subsec:ml}
We are choosing new code to try out essentially at random
instead of doing so intelligently and
drawing from an intuitive understanding of
what changes are needed in what situations.
Recently, there has been major breakthroughs on
the subject of using Deep Learning methods to generate code
(e.g., \cite{chen21} and \cite{li22}).
An interesting direction would be to hybridize the approaches,
combinining the \emph{overview} of Local Scoring with the \emph{intuition} of Deep Learning.
Let us speculate a bit on what that could look like.
\begin{enumerate}[(1)]
\item
One could incorporate into the scores an assessment of the \q{plausibility} of code,
as determined by a Deep Learning model,
rewarding code that looks like human-written code.
This could help guide the search in directions
of known patterns,
combating issues like overfitting and getting stuck in local minima.
\item
What kind of mutation or stretch to do could be chosen using a neural network
that is trained (on a fixed training set of code)
to predict what is most likely to cause improvements.
Deep Learning-based code generation could be used to
propose candidates for the replacing expressions
that we use when mutating
instead of generating these at random.
\item
Additionally, since we use mutation conservativity (see \cref{subsec:greedy}),
there will typically be long periods of attempting mutations
before a successful mutation is found.
One could collect data from these failed mutations.
An idea is to then use Deep Learning to
analyze these attempted mutations and their resulting local scores
in order to get a sense of which mutations do well,
which could then be leveraged to pick out qualified guesses for new mutations
making use of problem-specific knowledge.
Perhaps, one could even train a Deep Learning model during evolution on this data
to predict what mutations are likely successful.
\end{enumerate}
\bibliographystyle{alpha}
| {'timestamp': '2022-12-01T02:21:07', 'yymm': '2211', 'arxiv_id': '2211.17234', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17234'} | arxiv |
\section{Conclusion}
\label{sec:conclusion}
In this paper, we introduce GENNAPE, or Generalized Neural Architecture Performance Estimators, to address issues present in neural predictor design. Namely, that neural predictors typically operate within a fixed search space, and are not generalizable to unseen architecture families. GENNAPE receives Computation Graphs representing arbitrary network architectures as input, before using a Contrastive Learning encoder to generate embeddings. The embeddings pass through an MLP Ensemble, and we compute the prediction using a weighted summation according to Fuzzy C-Means clustering memberships. We extensively test GENNAPE against a number of known neural predictors on NB-101 and show that it yields high MAE and SRCC performance. Experimental results demonstrate the generalizability of our scheme in zero-shot and fine-tuning contexts in terms of SRCC and NDCG@10. When applied to search, GENNAPE can improve upon existing, high-performance NB-101, NB-201 and OFA-ResNet architectures. Finally, we introduce three new challenge families: HiAML, Inception and Two-Path, as open-source benchmarks.
\section{Architecture Families}
\label{sec:fam}
\begin{table}[t]
\centering
\caption{Architecture families
in terms of the number of architecture CGs, dataset and accuracy distribution in terms of mean and standard deviation (Acc. Dist) as well as range. Horizontal line demarcates public families.}
\label{table:datasets}
\scalebox{0.8}{
\begin{threeparttable}[hb]
\begin{tabular}{l|l|c|c|c}
\toprule
Family & Dataset & $\#$CGs & Acc. Dist [\%] & Range [\%] \\ \midrule
NB-101 & CIFAR-10 & 50k & 89.67 $\pm$ 5.73 & [10.00, 94.09] \\
NB-201 & CIFAR-10 & 4.1k\tnote{$\dagger$} & 89.44 $\pm$ 6.13 & [46.25, 93.37] \\
NB-301 & CIFAR-10 & 10k & 93.03 $\pm$ 0.74 & [88.28, 94.67] \\
PN & ImageNet & 8.2k & 75.41 $\pm$ 0.09 & [71.15, 77.81] \\
OFA-MBv3 & ImageNet & 7.5k & 76.94 $\pm$ 0.08 & [73.56, 78.83] \\
OFA-RN & ImageNet & 10k & 78.19 $\pm$ 0.07 & [75.25, 79.94] \\ \midrule
HiAML & CIFAR-10 & 4.6k & 92.36 $\pm$ 0.37 & [91.11, 93.44] \\
Inception & CIFAR-10 & 580 & 91.99 $\pm$ 0.75 & [89.08, 94.03] \\
Two-Path & CIFAR-10 & 6.9k & 89.94 $\pm$ 0.83 & [85.53, 92.34] \\\bottomrule
\end{tabular}
\begin{tablenotes}\footnotesize
\item{$\dagger$}We only use the 4096 architectures that do not contain the `none' operation.
\end{tablenotes}
\end{threeparttable}
}
\vspace{-3mm}
\end{table}
\begin{figure}[t]
\centering
\includegraphics[width=3.2in]{fig/HiAML.pdf}
\caption{The architecture backbone of HiAML, containing 4 stages. Each stage contains 2 identical blocks.}
\label{fig:hiaml}
\vspace{-3mm}
\end{figure}
We describe the neural network families used in this paper. We start with publicly available benchmarks before introducing three new families of networks. Table~\ref{table:datasets} provides a overall summary of each family.
\subsection{Public NAS Benchmark Families}
\label{sec:pubData}
\textbf{NAS-Bench-101} (NB-101) is one of the first and largest benchmarks for NAS. It consists of 423k unique architectures, individually evaluated on CIFAR-10. The architectures are cell-based, where each cell is a Directed Acyclic Graph (DAG) containing operations, stacked repeatedly to form a network. We sample 50k random architectures from this family to form our CG training family.
\textbf{NAS-Bench-201} (NB-201) and \textbf{NAS-Bench-301} (NB-301) are two additional benchmarks. Like NB-101, architectures consist of a fixed topology of cells, except they follow the DARTS search space. Additionally, NB-201 only contains 15.6k evaluated architectures, while NB-301 is a surrogate predictor for the DARTS search space. Therefore, we treat both as test families.
\textbf{ProxylessNAS} (PN)~\cite{cai2018proxylessnas} and \textbf{Once-for-All-MobileNetV3} (OFA-MBv3)~\cite{cai2020once} are based on the MobileNet~\cite{howard2019searching} architecture families, with ProxylessNAS and OFA implementing versions 2 and 3, respectively.
\textbf{Once-for-All-ResNet} (OFA-RN) is based on the classical ResNet~\cite{he2016deep} topology. All three evaluate on ImageNet. Architectures consist of searchable, macro features where the number of blocks is variable. We refer the reader to \cite{mills2021profiling} for further details regarding the PN, OFA-MBv3 and OFA-RN families.
\begin{figure}[t]
\centering
\subfloat[HiAML Accuracy]{\includegraphics[width=1.45in]{fig/HiAML_acc.pdf}}
\qquad
\subfloat[HiAML FLOPs]{\includegraphics[width=1.45in]{fig/HiAML_flops.pdf}}
\qquad
\subfloat[Inception Accuracy]{\includegraphics[width=1.45in]{fig/Inception_acc.pdf}}
\qquad
\subfloat[Inception FLOPs]{\includegraphics[width=1.45in]{fig/Inception_flops.pdf}}
\qquad
\subfloat[Two-Path Accuracy]{\includegraphics[width=1.45in]{fig/Two-Path_acc.pdf}}
\qquad
\subfloat[Two-Path FLOPs]{\includegraphics[width=1.45in]{fig/Two-Path_flops.pdf}}
\caption{Accuracy [\%] and FLOPs [10e6] histograms for the new benchmarks. Accuracy binning interval is 0.01\%.}
\label{fig:all_hists}
\vspace{-3mm}
\end{figure}
\subsection{Introduced NAS Benchmark Families}
\label{sec:newData}
We introduce the key attributes of the new network families and provide additional information in the supplementary. For all families, we define an \textit{operator} as a bundle of primitive operations, e.g., Conv3x3-BN-ReLU. A \textit{block} is a set of operators with different connection topologies, while a \textit{stage} contains a repetition of the same block type and the \textit{backbone} determines how we connect blocks to form distinct networks. For these network families, accuracy values are rounded to four decimal places. That is, we would represent 91.23\% as a terminating 0.9123. Figure~\ref{fig:all_hists} provides accuracy and FLOPs histograms.
\begin{figure*}[t]
\centering
\includegraphics[width=6.9in]{fig/GENNAPE.pdf}
\caption{An overview of GENNAPE. We utilize Computation Graphs and a Contrastive Learning Graph Encoder to generate embeddings, which are fed into a Fuzzy C-Means clustering algorithm. Cluster memberships act as weights in an MLP ensemble. Finally, we use FLOPs to apply a linear transform to the accuracy.
}
\label{fig:gennape}
\vspace{-1mm}
\end{figure*}
\textbf{HiAML} is a custom family of CIFAR-10 networks inspired by NAS-Bench-101. Networks are built using 14 pre-defined operation block structures found by GA-NAS~\cite{rezaei2021generative}. Specifically, a pair of identical blocks form a stage, and there are 4 stages per network. Since August 2021, HiAML networks have been in use as the backbone feature extractor in Huawei's mobile Facial Landmark Detection application, i.e., the family is not limited to Image Classification. HiAML networks are efficient enough to run entirely on the less powerful Ascend Tiny Core, which is a part of Da Vinci Architecture 2.0 in Huawei's Neural Processing Unit (NPU). Figure~\ref{fig:hiaml} provides a backbone illustration of HiAML.
As shown in Table~\ref{table:datasets}, we observe that
HiAML has the narrowest performance profile among all families considered, as
4.6k architectures fit into an accuracy range of
only 2.33\%. As a comparison, OFA-MBv3 has the second smallest accuracy range of 4.25\%.
This characteristic makes accurate prediction on
HiAML networks very difficult as there are many ties as Figure~\ref{fig:all_hists}(a) shows.
\textbf{Inception}
takes inspiration from
the Inception-v4~\cite{szegedy2016rethinking} classification
networks in literature.
Our custom Inception networks consist of a single-path backbone
with 3 stacked
stages, and inside each stage, there is a repetition of 2 to 4 blocks.
Like the original Inception, each block
may contain up to 4 branching paths.
The main advantage of Inception is that channels are divided among the paths, leading to lower computation costs.
The backbone follows a single-path topology with 3 stages.
\textbf{Two-Path} networks
are designed to be
more lightweight than other families.
As the name suggests,
the backbone consists of two
branching paths.
On each path, there are
2 to 4 blocks, each a sequence of up to 3 operators.
One may view the Two-path family as the complement of the Inception family. An Inception network has a single-path backbone with branching paths inside blocks. But a Two-Path network has two branching paths of blocks, while each block is a single path of operators.
\section{Introduction}
\label{sec:intro}
Understanding and predicting the
performance of neural networks is crucial to automated neural architecture design and neural architecture search (NAS). In fact, the amount of time and computational resources required by a NAS scheme is critically dependent on how evaluation is performed. Early methods~\cite{zoph2017NAS} rely on training individual architectures from scratch via intensive GPU usage.
Weight-sharing methodologies like
DARTS~\cite{liu2018DARTS} propose supernet models that superimpose the features of all
architectures in a search space, substantially reducing the cost of search. DARTS further reduces this cost by searching for an architecture on a small image classification dataset like CIFAR-10~\cite{Krizhevsky09CIFAR} before transferring the found architecture to a larger benchmark dataset, like ImageNet~\cite{russakovsky2015imagenet}. In contrast, Once-for-All (OFA)~\cite{cai2020once} employs strategies to effectively pre-train a re-usable supernet once on ImageNet prior to performing search.
Newer methods have seen the introduction of Zero-Cost Proxies~\cite{abdelfattah2021zero} which estimate performance from forward pass gradients.
Advancements in neural predictors~\cite{tang2020semi, wen2020neural}
allow for faster inference time, which significantly lowers the architecture evaluation cost incurred in NAS.
However, one major trade-off associated with using neural predictors is a lack of generalizability. The input to a neural predictor is usually a vector encoding of the architecture, whose scope is confined to the designated search space the predictor is meant to operate in. For example, to facilitate architecture search, Once-for-All, SemiNAS~\cite{luo2020semi}
and BANANAS~\cite{white2019bananas} design
specialized predictors, each performing in an individually defined search space. Such a restriction seriously limits the scope that a search algorithm~\cite{mills2021l2nas, mills2021exploring} can explore, regardless of how effective it is.
Furthermore, as a separate new predictor must be trained for each new search space created, there is an implied additional heavy cost associated with the laborious and resource-intensive task of labelling the performance of a suitable amount of neural architecture samples in this search space, since these architecture samples must be trained from scratch for evaluation.
Ideally, a
generalized neural predictor would not be subject to these constraints. Not only would it be able to receive input from multiple search spaces, but it would learn an architecture representation
that is robust enough to accurately estimate and rank the performance of networks from unseen search spaces.
In this paper we propose a \textbf{Gen}eralized \textbf{N}eural \textbf{A}rchitecture \textbf{P}erformance \textbf{E}stimator (GENNAPE), to perform a feasibility check on pretraining a robust and generalizable neural predictor based only on open neural network benchmarks and transferring it to a wide range of unseen architecture families for accurate accuracy ranking. GENNAPE accepts input architectures from any search space through a generic Computation Graph representation, and performs a two-stage process of graph encoding and cluster-based prediction
to achieve transferability to a new neural network design space under no or minimum fine-tuning. In designing GENNAPE, we make the following contributions:
First, we propose a generic embedding scheme based on \textit{Computation Graph} (CG) representations of any neural networks and a self-supervised Contrastive Learning (CL) loss as the starting point of our predictor. Specifically, we represent an input neural network as a graph of atomic neural operations, e.g., convolutions, pooling, activation functions, rather than macro units like MBConv blocks~\cite{howard2019searching} that are specific to architecture families.
This allows us to feed any neural network into our predictor. We then pass the CG through an
encoder to obtain a fixed-length embedding. The graph encoder is trained by
a carefully designed CL loss based on Laplacian Eigenvalues and dropout data augmentation, to distinguish graphical features between architecture families.
\begin{table}[t]
\centering
\caption{Spearman Rank Correlation coefficients for four Zero-Cost Proxy methods and a simple FLOPs-based predictor on all target families. Best results in bold.
}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c|c} \toprule
\textbf{Family} & \textbf{Synflow} & \textbf{Jacov} & \textbf{Fisher} & \textbf{Snip} & \textbf{FLOPs} \\ \midrule
NB-201 & 0.8230 & \textbf{0.8590} & 0.6870 & 0.7180 & 0.0002 \\
NB-301 & -0.2100 & -0.1900 & -0.3050 & -0.3360 & \textbf{0.5778} \\
OFA-PN & 0.0857 & -0.0219 & 0.6765 & \textbf{0.7309} & 0.6886 \\
OFA-MBv3 & 0.6477 & 0.0352 & 0.6018 & \textbf{0.6488} & 0.6141 \\
OFA-RN & 0.7243 & -0.0935 & 0.6507 & 0.7524 & \textbf{0.7850} \\ \midrule
HiAML & 0.1540 & -0.0100 & -0.1020 & -0.1680 & \textbf{0.2767} \\
Inception & 0.0850 & 0.1767 & -0.1518 & -0.0606 & \textbf{0.4115} \\
Two-Path & 0.2267 & -0.0712 & 0.0418 & -0.0268 & \textbf{0.3332} \\\bottomrule
\end{tabular}
}
\label{tab:zcp}
\vspace{-1mm}
\end{table}
Second, we propose to learn multiple prediction heads, each being an MLP and focusing on learning the characteristics of a local cluster of architectures in the training
family. We use Fuzzy C-Means (FCM) clustering to partition the training
family (in our case, NAS-Bench-101 due to its abundance of labelled samples)
into soft clusters, where a given input architecture can find soft memberships among the clusters. Based on the FCM partitions, we construct a Multi-Layer Perceptron-Ensemble (MLP-E) that
makes prediction for an architecture by soft aggregating the MLP heads according to the architecture's membership.
We verify the performance of GENNAPE on a wide range of public NAS families. Specifically, we pretrain our predictor
on NAS-Bench-101, and treat the search spaces of NAS-Bench-201, NAS-Bench-301, ProxylessNAS~\cite{cai2018proxylessnas}, OFA-MobileNetV3, OFA-ResNet as unseen target families. We show that our predictor is able to achieve over 0.85 SRCC and over 0.9 NDCG on all of these target families with minimal fine-tuning. When integrated into a downstream NAS search algorithm, GENNAPE further improves high-accuracy architectures from NAS-Bench-101, NAS-Bench-201
and
OFA-ResNet on ImageNet120.
To stress test the generalizability of GENNAPE, we further introduce three new challenging architecture benchmark sets: HiAML, Inception and Two-Path. These families contain certain properties, such as narrow accuracy range and ties,
which make it difficult for a predictor to accurately learn architecture rankings, and thus serve as challenging benchmarks for future NAS research. We show that GENNAPE can obtain over 0.78 NDCG on all three families. Finally, we
open-source\footnote{https://github.com/Ascend-Research/GENNAPE} these new benchmarks to facilitate further research on generalizable neural predictors.
\section{Methodology}
\label{sec:method}
Figure~\ref{fig:gennape} visualizes our overall scheme.
A predictor that generalizes to arbitrary architecture families should accept a generalizable neural network representation as input.
We consider the Computation Graph (CG) of a network structure based on the graph structures
deep learning libraries like TensorFlow~\cite{tensorflow2015-whitepaper} and PyTorch~\cite{NEURIPS2019_9015} use to facilitate
backpropagation. Specifically, nodes refer to
atomic operators in a network,
e.g., Convolution, Linear layers, Pooling layers, non-linearities and tensor operations like mean, add and concat.
Edges are directed and featureless.
This approach allows us to encode architectures from different families using a common format that represents all primitive network operations and the connections between them.
For example, both NB-101 and NB-201 include `Conv3x3' and `Conv1x1' as candidate operations.
These candidates are
actually
sequences of three primitive operations: Convolution, ReLU and Batch Normalization (BN), which are arranged differently for each search space. Wheras NB-101 consider a `Conv-BN-ReLU' ordering, NB-201 use `ReLU-Conv-BN'. Moreover, NB-101 encodes operations as nodes, while NB-201 follow DARTS and encode operations on edges. Our CG format reconciles these differences by representing each primitive as its own node with edges
defined by the
forward-pass of the network.
Figure~\ref{fig:simpleCG} illustrates a simple CG, where each node is a primitive operation. Node features consist of a one-hot category for operation type
as well as the height-width-channel (HWC) size of the input and output tensors. If an operation contains trainable weights, e.g., convolution and linear layers, we include a feature for the weight tensor dimensions, and a boolean for
whether bias is enabled.
As graphs can contain an arbitrary number of nodes and edges, it is necessary to process them into a common, fixed-length format prior to
prediction.
Therefore,
in this section, we introduce our Contrastive Loss-based (CL) graph embeddings scheme,
the Fuzzy C-Means (FCM) ensemble that forms the GENNAPE predictor and
describe a FLOPs-based accuracy transform.
\subsection{Embeddings from Contrastive Learning}
\label{sec:cl}
\begin{figure}[t]
\centering
\includegraphics[width=0.83in, angle=90]{fig/SimpleCG.pdf}
\caption{Example of a Compute Graph. Two parallel branches performing convolution and pooling operations process the input. A linear layer and activation then produce the output.}
\label{fig:simpleCG}
\end{figure}
We use Contrastive Learning (CL) to learn vector representations of CGs by adapting the two key components
of SimCLR~\cite{chen2020simple}. The first is data augmentation, where perturbations produce two different copies of every image in a batch. The second is the CL loss function, which aims to
identify positive and negative pairs within a batch.
Unlike images, random perturbations of CGs are unlikely to belong to the same architecture family. Therefore, to generate embedding variation,
we adopt dropout augmentation from
\citet{gao2021simcse}.
Consider a batch of $N$ CGs. We use dropout and apply a
graph encoder twice to make $2$ copies of each CG.
We then use an MLP head to project these embeddings of length $e$ into a lower dimensional space $p$ to optimize the CL loss.
Let $I=\{h_1,h_2,\dots,h_{2N}\}\subset\mathbb{R}^e$ be the
vector representations,
and let $z_i=proj(h_i)\in \{||z||=1: z \in \mathbb{R}^p\}$ be their projections. We define the cosine similarity $sim(z_i,z_j)=z_i\cdot z_j/\tau$, with
temperature $\tau>0$ and $\cdot$ as the dot product.
Then, our CL loss function is
\begin{equation}
\centering
\label{eq:cl_loss}
\mathcal{L}_{CL} = - \sum_{i\in I} \sum_{\ell \not=i} \alpha_\ell^{(i)} \log
\frac{\exp(sim(z_i,z_\ell))}{\sum_{r\not=i} \exp(sim(z_i,z_r))} ,
\end{equation}
where $\alpha_\ell^{(i)} \ge 0$ and $\sum_{\ell \not= i} \alpha_\ell^{(i)}=1$.
For each computational graph $i$, we calculate the convex combination $\alpha_*^{(i)}$
using the spectral distance of the underlying undirected graph as a similarity measure.
We
use topological properties to group architectures in the same family or separate architectures from different families,
because the arrangement of
operations differs for each
family.
Therefore, given a computation graph, let $G$ be its underlying undirected graph.
The normalized Laplacian of $G$ encodes important connectivity features.
Furthermore, it allows us to define a (pseudo) distance between computation graphs by
evaluating the Euclidean distance between the corresponding $q = 21$
smallest eigenvalues
~\cite{dwivedi2021generalization}.
We use $\sigma(g_1,g_2)$ to denote the distance between computation graphs $g_1,g_2$ and
define $\alpha_*^{(i)}$ to be the softmax of $\sigma(i,*)$.
We train a CL encoder on
NB-101 and use it to infer embeddings for all test families.
A 2-dimensional representation of the embeddings
is shown in Figure~\ref{fig:tsne}. We note two advantages of the CL encoder.
First,
it effectively separates each test family into distinct clusters with minimal overlap.
By contrast, the CL encoder divides the training family, NB-101, into many smaller clusters. This is an important finding. While NB-101 contains many architectures, it only contains 3 candidate operations, meaning that most of the diversity amongst these architectures comes from topological differences, i.e., Laplacian eigenvalues, which play an important role in training our CL encoder. As such,
each NB-101 cluster may reside closer to a given test family than others.
Next, we exploit these observations to build a predictor ensemble.
\begin{figure}[t]
\centering
\includegraphics[width=3.2in]{fig/tsne.png}
\caption{t-SNE scatterplot of the Contrastive Learning embeddings for all architecture families. Best viewed in color.}
\label{fig:tsne}
\vspace{-1mm}
\end{figure}
\subsection{Soft-Clustering Ensemble}
\label{sec:fcm}
We use MLP Ensembles (MLP-E) in GENNAPE to make predictions. Each head in the MLP-E is is responsible for a region of the embedding space, although these regions can partially overlap with each other. That is because
we use Fuzzy C-Means (FCM)~\cite{bezdek1984fcm}
clustering to divide up the embedding space, and FCM
represents data using continuous \textit{memberships} with respect to all clusters.
The output of the MLP-E is defined as,
\begin{equation*}
\centering
\label{eq:mlp_ensemble}
y'_i = \sum_{j=1}^{C}U_{i,j}f^{j}(h_i),
\end{equation*}
where $h_i$ and $y'_i$ are the graph embedding and target prediction a CG, of which there are $N$ in total, $C$ is the number of heads, $f^j$ is a head and $U_{i, j}$ is the membership for CG $i$ across cluster $j$.
FCM membership values $U \in (0, 1)^{N \times C}$
are positive numbers that sum to 1 for a given sample;
$\forall i \sum_{j=1}^{C} U_{i, j} = 1$.
Like other distance-based clustering algorithms, FCM consists of centroids that are computed alongside membership values by minimizing an
optimization. Let
$d_{i,j}$ be the Euclidean distance between CG embedding $h_i$ and FCM centroid $v_j$. FCM converges by alternating between updating membership values and centroid locations, respectively, according to the following equations,
\begin{equation}
\centering
\label{eq:fcmMembership}
U_{i, k} = (\sum_{j=1}^{C}(\dfrac{d_{i,k}^2}{d_{i,j}^2})^{\dfrac{1}{m-1}})^{-1},
\end{equation}
\begin{equation}
\centering
\label{eq:fcmCentroids}
v_k = \dfrac{\sum_{i=1}^N U_{i,k}^m h_i}{\sum_{i=1}^N U_{i,k}^m},
\end{equation}
where $m > 1$ is known as the \textit{fuzzification coefficient}, and is typically a value of 2 or greater~\cite{pedrycz2012genetic}, which controls the degree of overlap between the clusters.
The FCM algorithm alternates between Equations~\ref{eq:fcmMembership} and \ref{eq:fcmCentroids} until either a pre-specified number of iterations has been reached, or the following stopping criteria is satisfied:
\begin{equation}
\centering
\label{eq:fcmStop}
\max_{i, j} \lvert U_{i, j}(t+1) - U_{i,j}(t) \rvert \leq \epsilon,
\end{equation}
where $t$ is a time parameterization of $U$. Essentially, clustering convergence is reached once the maximum change in membership across all $N$ data samples and $C$ clusters is less than $\epsilon = 1e^{-9}$.
When applying FCM to GENNAPE, we compute
cluster centroids on the training family.
For test families, we infer membership from
existing centroids using Equation~\ref{eq:fcmMembership}.
A simple MLP is not guaranteed to generalize to features of families it has not seen. However, we can aid generalizability by only having the MLP learn a specific region in the feature space and weighing its predictions based on the distance between the unseen features and the learnt region. Moreover, we can divide up the feature space with an MLP-E.
Each head learns to specialize on a subset of the embedding features for the training family, as well an
association with nearby, unseen features, depending on memberships.
\subsection{FLOPs-based Features and Transforms}
\label{sec:FLOPs}
Every network has an associated FLOPs value, or floating point operations required for the forward pass.
GENNAPE uses FLOPs to
transform the regression targets
While the downstream goal of any regressor is to estimate the accuracy of a neural network, GENNAPE
estimates the following,
\begin{equation}
\centering
\label{eq:accTrans}
y_i = \mathcal{Z}(\dfrac{A_i}{\texttt{Log}_{10}(F_i+1)+1}),
\end{equation}
where $y_i$ is the
label, $A_i$ is the accuracy of a network, $F_i$ is the FLOPs, measured in gigaFLOPs and $\mathcal{Z}$ is the Z-Score. The inverse of this transformation can be applied to a prediction to obtain the corresponding accuracy prediction.
We use the standardization statistics from the NB-101 training set for all
test families, and we prune out
NB-101 architectures
whose accuracy is below 80\% when implementing Equation~\ref{eq:accTrans}. This
leaves us with 49k
architectures.
\section{Related Work}
\label{sec:related}
Neural predictors rely on
benchmark datasets,
namely NAS-Bench-101~\cite{ying2019nasbench101}, 201~\cite{dong2020nasbench201} and 301~\cite{zela2022surrogate}, which allow for performance \textit{querying}.
The downside to these methods is that every architecture must be trained
from scratch, possibly multiple times. Arguably, supernet-based methods like OFA~\cite{cai2020once} fall under a unique category of benchmark, where sampled architectures can be immediately evaluated.
However, this is still less resource intensive than training the network from scratch. Therefore, while benchmarks provide a rich repository of architecture statistics,
an upfront resource cost is incurred, motivating the need for generalized predictors that can perform well on unseen families.
One method of low-resource neural prediction
are Zero-Cost Proxies (ZCP); \citet{abdelfattah2021zero} outline many variants.
ZCP schemes involve gradient
calculations as well as parameter salience. As Table~\ref{tab:zcp} shows, while ZCP methods may achieve good results on some architecture families, their performance is inconsistent across families.
In addition, ZCP methods require network instantiation
to perform
forward passes to compute corresponding measures, while neural predictors do not.
Contrastive Learning (CL) is
based on distinguishing pairs of similar and dissimilar objects. This approach has been recently used successfully in image classification
~\cite{chen2020simple}.
Specifically,
CL classifiers improve transferability on unseen data.
Furthermore, fine-tuning on a very small fraction of the labeled data from a new dataset is enough to produce state of the art classifiers.
\citet{khosla2020supervised} further extend this approach to the case when image labels are known during training.
We focus on applying CL
methods for finding vector representations of
graphs.
Some deep learning schemes use Fuzzy C-Means clustering (FCM) to design interpretable models.
\citet{yeganejou2020fuzzy} substitute the last MLP
for an FCM clustering layer and classify images
according to the highest membership value. By contrast, GENNAPE incorporates FCM into an MLP ensemble, using the membership values to perform a weighted sum of MLP heads.
\section{Experimental Results}
\label{sec:exp}
In this Section, we describe our experimental procedure and results in terms of regression and correlation metrics. Finally, we apply GENNAPE to NAS and perform search.
\subsection{NAS-Bench-101 Comparison}
\label{sec:setup}
We use NB-101 as the training family and treat all others as unseen test families.
We split the
NB-101 architectures into a training set with 80\% of the data, and two separate validations sets that contain 10\% each. We apply Equation~\ref{eq:accTrans}
using the mean and standard deviation from the training partition to standardize the validation sets.
The model trains for 40 epochs. We evaluate it on the first validation set at every epoch without applying the inverse of Equation~\ref{eq:accTrans} to track loss statistics on transformed labels.
Once training is complete, we further evaluate the model on the second validation set, this time applying the inverse of Equation~\ref{eq:accTrans}
on
predictions to calculate performance compared to the
ground truth accuracy. For each scheme, we train a model 5 times using different random seeds. The overall best model is the one that achieves the highest rank correlation
on the second NB-101 validation set. We provide hyperparameters and other training details in the supplementary materials.
We consider several types of regressor variants in our experiments. `CL+FCM+T' uses CL graph embeddings as well as the FCM MLP-E to predict performance labels transformed using Equation~\ref{eq:accTrans}. `CL+MLP+T' removes the FCM clustering ensemble and uses a single MLP while `CL+FCM' keeps the keeps the clustering ensemble while removing Equation~\ref{eq:accTrans}. Finally, `CL+MLP' drops both Equation~\ref{eq:accTrans} and the FCM ensemble to predict accuracy directly using the CL embeddings. As baselines, we consider several GNN regressors such as $k$-GNN~\cite{morris2019weisfeiler}, Graph Convolutional Networks (GCN)~\cite{welling2016semi} and Graph Isomorphism Networks (GIN)~\cite{xu2019GIN} and train them end-to-end on CGs. Finally, we also consider several related neural predictors, such as Neural Predictor for NAS (NPN)~\cite{wen2020neural}, BANANAS~\cite{white2019bananas} and TNASP~\cite{lu2021TNASP}. These predictors operate on the NB-101 family, however since they do not represent architectures using CGs, they are not transferable outside of NB-101.
We consider two predictor performance metrics. The first is Mean Absolute Error (MAE), which measures predictor accuracy with respect to ground-truth labels. We report MAE as a percentage where lower is better. The second is Spearman's Rank Correlation (SRCC) which judges a predictor's ability to rank a population of architectures. SRCC ranges from -1 to 1 and in our case higher is better as that represents positive agreement with the ground-truth.
Table~\ref{tab:nb101_compare} enumerates our results for NB-101. We note the effectiveness of Equation~\ref{eq:accTrans},
which allows us to achieve MAE scores below 1\% on average. Moreover, the inclusion of CL and FCM further improve this result to a minimum of 0.59\%. In terms of ranking correlation, CL+FCM+T achieves the second highest SRCC at 0.930. While NPN obtains a slightly higher SRCC, that is the limit of its capabilities, since NPN on NB-101 cannot perform predictions for architectures from other families. Finally, in terms of other GNN CG baselines, the $k$-GNN excels. While it does not obtain the best MAE or SRCC, it is distinctly better than both the GCN and GIN. Therefore, we continue to use it as a generalizability baseline when comparing performance on other families.
\begin{table}[t]
\centering
\caption{NB-101 performance in terms of MAE [\%] and SRCC. We compare our CL-based schemes to various regressor-based neural predictors. Horizontal line separates non-transferable and transferable predictors. Results averaged over 5 runs.}
\label{tab:nb101_compare}
\scalebox{0.8}{
\begin{threeparttable}
\begin{tabular}{l|c|c} \toprule
\textbf{Method} & \textbf{MAE} & \textbf{SRCC} \\ \midrule
NPN\tnote{$\dagger$} & 1.09 $\pm$ 0.01\% & \textbf{0.934 $\pm$ 0.003} \\
BANANAS\tnote{$\dagger$} & 1.40 $\pm$ 0.06\% &0.834 $\pm$ 0.002 \\
TNASP\tnote{$\dagger$} & 1.23 $\pm$ 0.02\% & 0.918 $\pm$ 0.002\\ \midrule
GCN & 1.78 $\pm$ 0.06\% & 0.732 $\pm$ 0.034 \\
GIN & 1.72 $\pm$ 0.04\% & 0.735 $\pm$ 0.035 \\
$k$-GNN & 1.61 $\pm$ 0.08\% & 0.814 $\pm$ 0.020 \\
CL+MLP & 1.51 $\pm$ 0.17\% & 0.874 $\pm$ 0.009 \\
CL+FCM & 1.19 $\pm$ 0.12\% & 0.896 $\pm$ 0.003 \\
CL+MLP+T & \textit{0.65 $\pm$ 0.08\%} & 0.921 $\pm$ 0.003 \\
CL+FCM+T& \textbf{0.59 $\pm$ 0.01\%} & \textit{0.930 $\pm$ 0.002} \\ \bottomrule
\end{tabular}
\begin{tablenotes}\footnotesize
\item{$\dagger$}Obtained by running their model using our 50k NB-101 models, using the same data splits.
\end{tablenotes}
\end{threeparttable}
}
\vspace{-1mm}
\end{table}
\subsection{Transferability Prediction Error}
\label{sec:family_tests}
When evaluating on test families, we consider two cases. The first is zero-shot transfer performance, where we measure a given metric on all architecture CGs in a family without fine-tuning the predictor. In the second case, we sample 50 architectures at random, fine-tune for 100 epochs and then evaluate on the remaining, held-out architectures. We perform fine-tuning 5 separate times on different seeds, ensuring
that we select the same 50 architectures per seed. Evaluating MAE performance on test families is applicable in the fine-tuning setting as that provides the predictor some information on the actual distribution of target labels. When fine-tuning using Equation~\ref{eq:accTrans}, we use the mean and standard deviation information from the NB-101 training partition to standardize labels for the 50 fine-tuning samples, and to recover accuracy
on the remaining samples at inference.
Table~\ref{tab:mae} provides test family MAE results for the $k$-GNN baseline and several CL-based regressors. Once again, we observe how regressors that use Equation~\ref{eq:accTrans} achieve the lowest MAE on 3 of 9 families, including all ImageNet families and Two-Path. The $k$-GNN achieves good performance on NB-201, likely because it has the second largest range after NB-101. On HiAML, Inception and Two-Path, the results generally very close, showing how difficult it can be to predict accuracy for them.
\begin{table}[t]
\centering
\caption{Mean Absolute Error [\%] results across all families and regressors.
Lower is better. Best result in bold. Results averaged across 5 random seeds.}
\label{tab:mae}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c} \toprule
\textbf{Family} & \textbf{\textit{k}-GNN} & \textbf{CL+MLP} & \textbf{CL+MLP+T} & \textbf{CL+FCM+T} \\ \midrule
NB-101 & 1.61 & 1.51 & 0.65 & \textbf{0.59} \\ \midrule
NB-201 & \textbf{1.80} & 2.81 & 1.93 & 2.05 \\
NB-301 & 0.46 & 0.85 & \textbf{0.43} & 0.57 \\ \midrule
PN & 0.56 & 0.40 & 0.35 & \textbf{0.33} \\
OFA-MBv3 & 0.61 & 0.35 & 0.31 & \textbf{0.27} \\
OFA-RN & 0.40 & 0.44 & 0.45 & \textbf{0.37} \\ \midrule
HiAML & \textbf{0.35} & 0.45 & 0.40 & 0.39 \\
Inception & \textbf{0.60} & 0.82 & 0.71 & 0.86 \\
Two-Path & 0.80 & 1.11 & \textbf{0.71} & 0.72 \\ \bottomrule
\end{tabular}
}
\vspace{-1mm}
\end{table}
\subsection{Unseen Architecture Ranking Performance}
\label{sec:srcc_ndcg}
GENNAPE consists of a weighted average of predictions from several models. The first two are the aformentioned `CL+FCM+T' and `CL+MLP+T' regressors. We also include two pairwise classifiers, that, instead of estimating accuracy, predict which CG in a pair has higher accuracy. We label these as `CL+Pairwise+FCM' and `CL+Pairwise', differentiated by whether they have FCM and an MLP ensemble. We also include the $k$-GNN and the FLOPs predictor from Table~\ref{tab:zcp}. For zero-shot performance, GENNAPE weighs the output of all predictors equally. When fine-tuning, we calculate weights by taking the softmax of the Kendall's Tau (KT) result each individual predictor obtains on the fine-tuning samples. The supplementary materials contains details and an ablation study of these components.
Table~\ref{tab:srcc} provides SRCC results across all test families. We observe how GENNAPE achieves SRCC values above 0.85 on all public benchmarks.
In fact, the only public family GENNAPE does not achive zero-shot SRCC above 0.5 on is NB-301, however, at 0.3214 this is still much higher than the $k$-GNN and any of the ZCP from Table~\ref{tab:zcp}. Moreover, fine-tuning greatly improves the performance of GENNAPE on NB-301. Meanwhile, the $k$-GNN does achieve higher zero-shot SRCC on OFA-RN, but the improvement is less than 0.1 SRCC. On all other public benchmarks it fails to achieve over 0.5 SRCC in the zero-shot setting.
GENNAPE achieves the best zero-shot performance on HiAML, Inception and Two-Path. With fine-tuning, it manages to achieve above 0.5 SRCC on Inception and close to 0.5 SRCC on Two-Path. By contrast the $k$-GNN fails to achieve positive correlation on HiAML and Inception in the zero-shot setting, and while it achieves better HiAML SRCC with fine-tuning, once again the performance gap is very small, below 0.015 SRCC and less than the GENNAPE zero-shot SRCC of 0.4331. Finally, GENNAPE does lose some ranking performance when fine-tuning on HiAML, but that is a feature of the family: a narrow accuracy range with many ties that is hard to predict on.
We provide additional results using Kendall's Tau in the supplementary materials.
\begin{table}[t]
\centering
\caption{Spearman Rank Correlation
results across test families
in the zero-shot transfer and fine-tuning (w/ FT) contexts.
Higher is better. Best results in bold. Double horizontal lines demarcate public benchmarks from introduced families.
Fine-tuning results averaged across 5 random seeds.}
\label{tab:srcc}
\scalebox{0.8}{
\begin{tabular}{l|c|c} \toprule
\textbf{Family} & \textbf{\textit{k}-GNN} & \textbf{GENNAPE} \\ \midrule
NB-201 & 0.4930 & \textbf{0.8146} \\
w/ FT & 0.8606 $\pm$ 0.0245 & \textbf{0.9103 $\pm$ 0.0114} \\ \midrule
NB-301 & {0.0642} & \textbf{0.3214} \\
w/ FT & 0.8584 $\pm$ 0.0290 & \textbf{0.8825 $\pm$ 0.0134} \\\midrule
PN & 0.0703 & \textbf{0.8213} \\
w/ FT & 0.7559 $\pm$ 0.0621 & \textbf{0.9506 $\pm$ 0.0039} \\ \midrule
OFA-MBv3 & 0.4345 & \textbf{0.8660} \\
w/ FT & 0.6862 $\pm$ 0.0253 & \textbf{0.9449 $\pm$ 0.0015} \\ \midrule
OFA-RN & \textbf{0.5721} & 0.5115 \\
w/ FT & 0.9102 $\pm$ 0.0146 & \textbf{0.9114 $\pm$ 0.0063} \\\midrule \midrule
HiAML & -0.1211 & \textbf{0.4331} \\
w/ FT & \textbf{0.4300 $\pm$ 0.0507} & 0.4169 $\pm$ 0.0479 \\ \midrule
Inception & -0.2045 & \textbf{0.4249} \\
w/ FT & 0.3340 $\pm$ 0.0793 & \textbf{0.5524 $\pm$ 0.0166} \\ \midrule
Two-Path & 0.1970 & \textbf{0.3413} \\
w/ FT & 0.3694 $\pm$ 0.0406 & \textbf{0.4875 $\pm$ 0.0311} \\ \bottomrule
\end{tabular}
}
\vspace{-1mm}
\end{table}
SRCC measures correlation over all $N$ samples and assigns equal weight to each. However,
the concerns of NAS relate to finding high-performance architectures.
Therefore, for further evaluation
of GENNAPE, we
consider another metric that assigns disproportionate importance.
Following AceNAS~\cite{zhang2021acenas}, we adopt a metric from the field of Information Retrieval (IR),
where queried objects are assigned a relevance score, and
it is more important to properly order objects with higher relevance. This goal is analogous to the concerns of NAS. Accuracy is relevance.
Specifically, we adopt Normalized Discounted Cumulative Gain (NDCG), which
prioritizes the ordering of the top-$k$ architectures by a ground truth ranking.
NDCG is reported in the range $[0, 1]$, where higher is better. We consider the case of $k=10$ in our experiments, which corresponds to ordering the very best architectures. Details of the NDCG calculation are in the supplementary materials.
We list our findings in Table~\ref{tab:ndcg}. GENNAPE clearly outperforms the $k$-GNN baseline in both contexts. The sole exception is OFA-R50, likely due to NB-101 architectures being partially based on ResNets in terms of operation choice. Still, in the zero-shot transfer context GENNAPE achieves over 0.65 NDCG on \textit{all} families, and over 0.9 NDCG on all public families with fine-tuning.
Moreover, GENNAPE now overtakes the $k$-GNN on HiAML in both the zero-shot and fine-tuning contexts. Results are also more favorable on Inception and Two-Path, where GENNAPE achieves over 0.8 NDCG in both the zero-shot and fine-tuning settings. This aligns with our earlier intuition: Although the small accuracy range makes global ranking difficult, there are only a few architectures at the tail of the distribution and GENNAPE is better at determining which ones they are. We report additional NDCG results in the supplementary materials.
In sum,
we show that GENNAPE is a robust neural predictor that can easily generalize to unseen architecture families. The NDCG results we show are of particular relevance to the problem of NAS, where neural predictors fill the role of performance evaluation. This is because, ultimately, the downstream performance of any search algorithm relies upon having a performance estimator capable of identifying high-performance architectures. Next, we apply GENNAPE to the problem of NAS, to demonstrate its applied capability and the flexibility of our CG architecture representation.
\begin{table}[t]
\centering
\caption{Normalized Discounted Cumulative Gain (NDCG@10) across test families
in the zero-shot transfer and fine-tuning (w/ FT) context.
Higher is better. Best results in bold. Double horizontal lines demarcate public benchmarks from introduced families.
Fine-tuning results averaged across 5 random seeds.}
\label{tab:ndcg}
\scalebox{0.8}{
\begin{tabular}{l|c|c} \toprule
\textbf{Family} & \textbf{\textit{k}-GNN} & \textbf{GENNAPE} \\ \midrule
NB-201 & 0.9270 & \textbf{0.9793} \\
w/ FT & 0.9751 $\pm$ 0.0082 & \textbf{0.9855 $\pm$ 0.0030} \\ \midrule
NB-301 & 0.5341 & \textbf{0.7885}\\
w/ FT & 0.9723 $\pm$ 0.0134 & \textbf{0.9765 $\pm$ 0.0081} \\\midrule
PN & 0.4426 & \textbf{0.8736} \\
w/ FT & 0.9287 $\pm$ 0.0271 & \textbf{0.9800 $\pm$ 0.0057} \\ \midrule
OFA-MBv3 & 0.8464 & \textbf{0.9234} \\
w/ FT & 0.8859 $\pm$ 0.0536 & \textbf{0.9838 $\pm$ 0.0030} \\ \midrule
OFA-RN & \textbf{0.9470} & 0.6606 \\
w/ FT & \textbf{0.9717 $\pm$ 0.0090} & 0.9463 $\pm$ 0.0236 \\\midrule \midrule
HiAML & 0.5088 & \textbf{0.6892} \\
w/ FT & 0.7356 $\pm$ 0.0371 & \textbf{0.7804 $\pm$ 0.0211} \\ \midrule
Inception & 0.6064 & \textbf{0.8150} \\
w/ FT & 0.7310 $\pm$ 0.0423 & \textbf{0.8073 $\pm$ 0.0072} \\ \midrule
Two-Path & 0.6339 & \textbf{0.8275} \\
w/ FT & 0.7860 $\pm$ 0.0268 & \textbf{0.8392 $\pm$ 0.0220} \\
\bottomrule
\end{tabular}
}
\vspace{-1mm}
\end{table}
\subsection{Applying GENNAPE to NAS}
\label{sec:search}
We conduct NAS experiments where we directly modify the CGs of existing optimal classification networks.
We aim to reduce FLOPs while improving or maintaining accuracy using a simple location search algorithm and provide details in the supplementary materials.
After
search, we train and evaluate the original optimal architecture and the one and found by search
on classification datasets.
Specifically, we apply this search routine to NB-101 and NB-201 on CIFAR-10. To reduce carbon footprints, we also search on OFA-RN but use a subset of ImageNet, which only contains the first 120 classes; ImageNet120.
We
use the fine-tuning CL+FCM+T predictors in these experiments. Search takes less than 3 hours.
Inference on our predictors is fast. The primary bottleneck stems from the search algorithm determining
whether newly found
CGs are feasible as classification neural networks.
Table~\ref{tab:search} summarizes the results, demonstrating the power of GENNAPE to further improve upon existing, high-performance
architectures, in terms of accuracy and FLOPs, on three public families.
Notably, the OFA-ResNet architecture found by search achieves 22\% FLOPs reduction while improving accuracy by 0.4\%.
Moreover, these results
demonstrate the utility of our CG framework, as the atomic operation mutations result in architectures that are not exact fits to the original search spaces. Using CGs, we can modify sections like the stem or head that are typically fixed, and introduce new operation sequences.
For example, the NB-201 architecture we compare to and outperform was already the best on CIFAR-10. Therefore, a typical neural predictor for NB-201
would not be able to adequately process and predict performance for architectures found by our search algorithm.
\begin{table}[t]
\centering
\caption{Evaluation results for architectures found using CL+FCM+T predictors compared to existing high-performance architectures.}
\label{tab:search}
\scalebox{0.8}{
\begin{tabular}{l|l|c|c}
\toprule
Model & Dataset & FLOPs & Top-1 Acc.(\%) \\
\midrule
NB-101-Best & CIFAR-10 & 11.72G & 94.97 \\
NB-101-Search & CIFAR-10 & \textbf{9.49}G & \textbf{95.05} \\
\midrule
NB-201-Best & CIFAR-10 & 313M & 93.27 \\
NB-201-Search & CIFAR-10 & \textbf{283}M & \textbf{93.62} \\
\midrule
OFA-ResNet-Input & ImageNet120 & 12.13G & 80.62 \\
OFA-ResNet-Search & ImageNet120 & \textbf{9.46}G & \textbf{81.08} \\
\bottomrule
\end{tabular}
}
\vspace{-1mm}
\end{table}
\section{Supplementary Material}
\label{sec:supp}
\subsection{Introduced Neural Network Benchmarks}
\label{sec:customFamilies}
Figure~\ref{fig:families} provides a detailed depiction of the three new benchmark families we propose: HiAML, Inception and Two-Path.
We re-iterate
the key attributes of these new benchmarks.
Specifically, we define an \textit{operator} as a bundle of primitive operations, e.g., Conv3x3-BN-ReLU. A \textit{block} is a set of operators with different connection topologies, a \textit{stage} contains a repetition of the same block type and the \textit{backbone} determines how we connect blocks to form distinct networks.
\subsubsection{The HiAML family}
(Fig.~\ref{fig:families}(a)) first constructs a network backbone with 4 stages
and exactly 2 block repetitions per stage.
Different from other families, the block structures are not randomly sampled.
Instead, we first run GA-NAS~\cite{rezaei2021generative}
on a search space similar to NAS-Bench-101, i.e., we allow up to 4 operators per block with any connection patterns in-between.
After running NAS we find 14 blocks, and to construct the HiAML family we uniformly sample from these 14 blocks for each stage.
Reduction is performed in the stem Conv3x3 and the first block of stages 2 and 4.
We label 4629 networks for this family on CIFAR-10.
\subsubsection{The Inception family}
(Fig.~\ref{fig:families}(b)) mimics the Inception-v4~\cite{szegedy2017inception} classification networks. Our Inception networks all contain 3 stages.
Inside each stage
, we have 2-4 stacked blocks.
Like HiAML,
the blocks inside a stage
have the same internal structure.
Blocks in different stages will likely
can have different internal structures.
When sampling a block, one first chooses the number of branching paths.
We allow up to 4 branching paths and inside each path, there are
up
to 4 operators.
An operator could be a Conv3x3-BN-ReLU combination.
We adopt a wide range of candidate operators, including regular Convolution, Depth-wise Separable Convolution, MBConv, etc.
Figure~\ref{fig:families} (b) shows an example of a 2-path block topology. Additional paths will follow a similar layout.
Note that we also divide the candidate operators into two groups: Conv operators (Conv op) and Supplementary operators (Supp op).
The supplementary operators set includes all 1x1 convolution and pooling operations, whereas the Conv operators set only includes convolution with kernel size $>$1.
A path must have at least one 1 Conv op, and at most one Supp op.
Input channels will be further reduced based on the number of paths, e.g., if there are 2 paths then the channel size of a path will be half of the input channels, achieved via projection by the first operator of the path.
In our Inception networks, we perform reductions on the input image in each stage by halving the height and width of the input and doubling the channels. This is achieved by the first block of each stage.
We label 580 networks for this family on CIFAR-10.
\subsubsection{The Two-Path family}
(Fig.~\ref{fig:families}(c)) constructs a
simpler
structure where an entire network contains only two branching paths.
Inside a path, there are 2-4 blocks.
Each block
has a single-path topology with 1-3 operators.
The definition of an operator is the same as the Inception family. In fact, one may view the Two-path family as the complement of the Inception family. An Inception network has a single-path backbone with branching paths inside blocks. But a Two-Path network has two branching paths of blocks, while each block is a single path of operators.
Reduction on the input image is performed in the second stem Conv3x3
and also by two randomly chosen blocks of each path.
Since we do not allow block repetitions, Two-Path networks are usually lightweight and shallower
than the other families.
We label 6890 networks for this family on CIFAR-10.
\begin{figure*}[t!]
\begin{center}
\includegraphics[width=5.95in]{fig/families.pdf}
\end{center}
\caption{
Illustrations of network and block design spaces for our proposed new families: (a) HiAML, (b) Inception and (c) Two-Path.
For Inception and HiAML networks, each stage
contains the repetitions of one type of block.
Optional operators or blocks have dashed boundary lines.
GP + FF stands for global average pooling and feedforward layers.
}
\label{fig:families}
\end{figure*}
\begin{table*}[t]
\centering
\caption{Spearman's rank correlation (SRCC) results across test families and predictors in the zero-shot transfer and fine-tuning (w/ FT) contexts. Higher is better. Best and second-best entries for each family are in bold and italics, respectively. Fine-tuning results averaged across 5 random seeds.}
\label{tab:srcc_ablate}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c|c|c|c} \toprule
\textbf{Family} & \textbf{\textit{k}-GNN} & \textbf{CL+MLP} & \textbf{CL+MLP+T }& \textbf{CL+FCM+T} & \textbf{CL+Pairwise} & \textbf{CL+FCM+Pairwise} & \textbf{GENNAPE} \\ \midrule
NB-201 & 0.4930 & \textbf{0.8520} & 0.7834 & 0.7647 & 0.8151 & \textit{0.8503} & 0.8146 \\
w/ FT & 0.8606 $\pm$ 0.0245 & 0.7892$\pm$0.0715 & 0.8309$\pm$0.0410 & 0.8281$\pm$0.0181 & \textit{0.8897$\pm$0.0153} & 0.8896$\pm$0.0179 & \textbf{0.9103$\pm$0.0114} \\
NB-301 & {0.0642} & -0.5250 & -0.1689 & \textit{0.1349} & -0.0702 & -0.2462 & \textbf{0.3214} \\
w/ FT & \textit{0.8584$\pm$0.0290} & 0.6354$\pm$0.0929 & 0.7665$\pm$0.0318 & 0.7227$\pm$0.0275 & 0.8301$\pm$0.0335 & 0.8445$\pm$0.0093 & \textbf{0.8825$\pm$0.0134} \\\midrule
PN & 0.0703 & 0.0138 & \textbf{0.8782} & 0.8068 & 0.4424 & 0.3489 & \textit{0.8213} \\
w/ FT & 0.7559$\pm$0.0621 & 0.9209$\pm$0.0009 & 0.9281$\pm$0.0028 & 0.9322$\pm$0.0078 & 0.9429$\pm$0.0010 & \textit{0.9447$\pm$0.0064} & \textbf{0.9506$\pm$0.0039} \\
OFA-MBv3 & 0.4345 & 0.5205 & 0.7122 & \textbf{0.8713} & 0.5350 & 0.5515 & \textit{0.8660} \\
w/ FT & 0.6862$\pm$0.0253 & 0.9182$\pm$0.0070 & 0.9302$\pm$0.0021 & 0.9264$\pm$0.0050 & 0.9356$\pm$0.0062 & \textit{0.9369$\pm$0.0080} & \textbf{0.9449$\pm$0.0015} \\
OFA-RN & \textbf{0.5721} & -0.6963 & -0.6035 & -0.7766 & -0.3541 & -0.5278 & \textit{0.5115} \\
w/ FT & \textit{0.9102$\pm$0.0146} & 0.8588$\pm$0.0133 & 0.8187$\pm$0.0367 & 0.8350$\pm$0.0283 & 0.8785$\pm$0.0207 & 0.8737$\pm$0.0132 & \textbf{0.9114$\pm$0.0063} \\\midrule
HiAML & -0.1211 & \textit{0.4373} & 0.4043 & \textbf{0.4511} & 0.3958 & 0.4167 & 0.4331 \\
w/ FT & \textbf{0.4300$\pm$0.0507} & 0.2259$\pm$0.1753 & 0.2706$\pm$0.0805 & 0.2779$\pm$0.0545 & 0.3062$\pm$0.1187 & 0.3266$\pm$0.0701 & \textit{0.4169$\pm$0.0479} \\
Inception & -0.2045 & 0.1843 & 0.3439 & \textbf{0.4429} & 0.3038 & 0.3487 & \textit{0.4249} \\
w/ FT & 0.3340$\pm$0.0793 & 0.4771$\pm$0.0639 & \textit{0.5144$\pm$0.0448} & 0.4569$\pm$0.0547 & 0.3554$\pm$0.0759 & 0.3654$\pm$0.0825 & \textbf{0.5524$\pm$0.0166} \\
Two-Path & 0.1970 & 0.0106 & \textit{0.3205} & {0.3130} & 0.1843 & 0.2866 & \textbf{0.3413} \\
w/ FT & 0.3694$\pm$0.0406 & 0.3046$\pm$0.0977 & \textit{0.4412$\pm$0.0591} & 0.4331$\pm$0.0584 & 0.3251$\pm$0.1179 & 0.3432$\pm$0.0924 & \textbf{0.4875$\pm$0.0311} \\
\bottomrule
\end{tabular}
}
\end{table*}
\begin{table*}[t]
\centering
\caption{Kendall's Tau (KT) results across test families and predictors in the zero-shot transfer and fine-tuning (w/ FT) contexts. Higher is better. Best and second-best entries for each family are in bold and italics, respectively. Fine-tuning results averaged across 5 random seeds.}
\label{tab:kendall_ablate}
\scalebox{0.8}{
\begin{threeparttable}[hb]
\begin{tabular}{l|c|c|c|c|c|c|c} \toprule
\textbf{Family} & \textbf{\textit{k}-GNN} & \textbf{CL+MLP} & \textbf{CL+MLP+T }& \textbf{CL+FCM+T} & \textbf{CL+Pairwise} & \textbf{CL+FCM+Pairwise} & \textbf{GENNAPE} \\ \midrule
NB-201 & 0.3382 & \textit{0.6554} & 0.5855 & 0.5719 & 0.6253 & \textbf{0.6572} & 0.6202 \\
w/ FT & 0.6772$\pm$0.0100 & 0.6004$\pm$0.0739 & 0.6430$\pm$0.0445 & 0.6376$\pm$0.0205 & \textit{0.7137$\pm$0.0209} & 0.7121$\pm$0.0244 & \textbf{0.7415$\pm$0.0180} \\
NB-301 & 0.0431 & -0.3670 & -0.1122 & \textit{0.0921} & -0.0484 & -0.1673 & \textbf{0.2183}\\
w/ FT & \textbf{0.7125$\pm$0.0143} & 0.4644$\pm$0.0753 & 0.5767$\pm$0.0315 & 0.5340$\pm$0.0257 & 0.6474$\pm$0.0346 & 0.6614$\pm$0.0100 & \textit{0.7075$\pm$0.0171} \\\midrule
PN & 0.0473 & 0.0095 & \textbf{0.6999} & 0.6174 & 0.3057 & 0.2375 & \textit{0.6299} \\
w/ FT & 0.5927$\pm$0.0421 & 0.7593$\pm$0.0137 & 0.7711$\pm$0.0034 & 0.7796$\pm$0.0115 & 0.7978$\pm$0.0176 & \textit{0.8006$\pm$0.0122} & \textbf{0.8135$\pm$0.0074} \\
OFA-MBv3 & 0.2995 & 0.3637 & 0.5221 & \textbf{0.6892} & 0.3737 & 0.3900 & \textit{0.6832} \\
w/ FT & 0.5016$\pm$0.0128 & 0.7564$\pm$0.0114 & 0.7754$\pm$0.0036 & 0.7689$\pm$0.0082 & 0.7843$\pm$0.0112 & \textit{0.7868$\pm$0.0146} & \textbf{0.8024$\pm$0.0027} \\
OFA-RN & \textbf{0.4095} & -0.5054 & -0.4320 & -0.5858 & -0.2565 & -0.3549 & \textit{0.3559} \\
w/ FT & \textit{0.7437$\pm$0.0139} & 0.6760$\pm$0.0155 & 0.6302$\pm$0.0374 & 0.6466$\pm$0.0327 & 0.6997$\pm$0.0247 & 0.6897$\pm$0.0139 & \textbf{0.7457$\pm$0.0092} \\\midrule
HiAML & -0.0813 & 0.3030 & 0.2809 & \textbf{0.3166} & 0.2726 & 0.2880 & \textit{0.3040} \\
w/ FT & \textit{0.2875$\pm$0.0581} & 0.1629$\pm$0.1195 & 0.1940$\pm$0.0539 & 0.1988$\pm$0.0360 & 0.2104$\pm$0.0828 & 0.2240$\pm$0.0488 & \textbf{0.2913$\pm$0.0352} \\
Inception & -0.1383 & 0.1244 & 0.2356 & \textbf{0.3059} & 0.2047 & 0.2400 & \textit{0.2935} \\
w/ FT & 0.2082$\pm$0.0352 & 0.3335$\pm$0.0453 & \textit{0.3627$\pm$0.0337} & 0.3212$\pm$0.0404 & 0.2424$\pm$0.0544 & 0.2516$\pm$0.0572 & \textbf{0.3911$\pm$0.0137} \\
Two-Path & 0.1397 & 0.0753 & \textit{0.2314} & 0.2257 & 0.1306 & 0.2047 & \textbf{0.2323} \\
w/ FT & 0.2232$\pm$0.0432 & 0.2115$\pm$0.0670 & \textit{0.3094$\pm$0.0430} & 0.3033$\pm$0.0420 & 0.2222$\pm$0.0824 & 0.2342$\pm$0.6370 & \textbf{0.3389$\pm$0.0230} \\\bottomrule
\end{tabular}
\end{threeparttable}
}
\end{table*}
\subsection{Model and Hyperparameter Details}
\subsubsection{Baseline GNNs}
\label{sec:gnnDetails}
Our GNNs
(e.g., $k$-GNN, as well as GCN~\cite{welling2016semi} and GIN~\cite{xu2019GIN}) consist of an initial embedding layer that transforms CG node features into continuous vectors of size 32. Graph encoders consist of 6 layers. We derive the graph embedding by averaging all node embeddings. Regressors consist of 4 layers with a hidden size of 32. Baseline GNNs train predictors for 40 epochs with an initial learning rate of $1e^{-4}$ and a batch size of 32.
\subsubsection{Contrastive Learning Graph Encoder}
\label{sec:clDetails}
The CL encoder
consists of a GNN~\cite{morris2019weisfeiler} and Transformer~\cite{vaswani2017attention} whose output is concatenated to produce CG embeddings. The GNN consists of 4 layers, while the Transformer consists of a single layer with two attention heads trained with a dropout rate of 0.1. Both modules produce output vectors of length 64, so the overall embedding size is $m = 128$. We train the CL encoder using a batch size of 128, consider the $q = 21$ smallest eigenvalues and use a temperature $\tau = 0.05$.
For regularization, we add a second projection head that predicts the FLOPs of a CG.
\subsubsection{Details of the Fuzzy C-Means Ensemble}
\label{sec:fcmDetails}
We use a simple grid search to determine the number of clusters $C \in [10, 20]$ and fuzzification coefficient $m \in [2.0, 4.0]$. As $m$ is continuous we consider increments of $0.5$ and select the model that achieves the highest SRCC the second NB-101 validation set. For regressors, these were $[C, m] = [16, 4.0]$ and for classifiers it was $[C, m] = [11, 3.5]$. Prior to clustering, we standardize FLOPs using the mean and standard deviation from the NB-101 training set and concatenate them with the CL graph embeddings. We also use Principle Component Analysis (PCA)~\cite{wold1987principal} to reduce embedding size down to 32. FCM runs for 10k iterations or until the stopping criteria $\epsilon = 1e^{-9}$ is satisifed.
\subsubsection{Details of the CL+MLP and CL+FCM}
\label{sec:mlpDetails}
MLP regressors contain 4 hidden layers with a hidden size of 256 each, while pairwise classifiers contain 128. FCM memberships in the classifier sum to produce a latent vector of size 16 for each CG in a pair. We concatenate these and use an MLP layer to produce a prediction. We use ReLU as an activation function and train all predictors for 40 epochs with an initial learning rate of $1e^{-4}$ and a batch size of 32. We perform fine-tuning for 100 epochs using 50 samples with a batch size of 1. Finally, we obtain the SRCC of pairwise classifiers using mergesort with the model as a comparater to generate a list of rankings.
\subsection{Calculation of NDCG}
\label{sec:ndcg}
We provide a brief explanation on the calculation of Normalized Discounted Cumulative Gain (NDCG) for the top-$k$ best architectures in a population.
Given lists of predictions and ground-truth accuracies, sort into descending order according to the prediction. Each prediction shall be given an index $1, 2, 3,..., N$ while the labels will be assigned a relevance score $rel_1, rel_2, rel_3,..., rel_N$. Following AceNAS~\cite{zhang2021acenas}, we assign relevancy by re-scaling accuracy labels into the range $[0, 20]$. We first compute the Discounted Cumulative Gain (DCG) as
\begin{equation}
\centering
\label{eq:dcg}
DCG = \sum_{i=1}^{k}\dfrac{2^{rel_i}-1}{\texttt{log}_2(i+1)},
\end{equation}
where $k \leq N$ allows one to control how many items we consider. We then compute NDCG as
\begin{equation}
\centering
\label{eq:ndcg}
NDCG = \dfrac{DCG}{IDCG},
\end{equation}
where $IDCG$ is $DCG$ under the ideal ordering, e.g., descending sort according to the ground truth where $rel_i \geq rel_j$ if $i < j$.
\subsection{Search Algorithm Details}
\label{sec:search_details}
We pair our fine-tuned CL+FCM+T predictors with a simple local search algorithm which runs for 6 iterations. In each iteration, we collect the current top-$k$ best CGs based on predicted performance and FLOPs.
For each top-$k$ CG, we perform mutation by randomly replacing a sequence of primitive operations with a sub-graph of new operations, ensuring that previous HWC channel constraints are met.
Finally, we rank the CGs based on the predicted performance and collect the new top-$k$ best CGs for the next iteration.
When searching on NB-101 and NB-201, we select the optimal architectures on CIFAR-10. For OFA-ResNet, we use the best architecture found by \citet{mills2021profiling}.
\begin{table*}[t]
\centering
\caption{Normalized Discounted Cumulative Gain (NDCG) results across test families and predictors in the zero-shot transfer and fine-tuning (w/ FT) contexts. We consider NDCG@$50$ in addition to NDCG@$10$. Higher is better. Best and second-best entries for each family are in bold and italics, respectively. Fine-tuning results averaged across 5 random seeds.
}
\label{tab:ndcg_ablate}
\scalebox{0.8}{
\begin{threeparttable}[hb]
\begin{tabular}{l|c|c|c|c|c|c|c} \toprule
\textbf{Family} & \textbf{\textit{k}-GNN} & \textbf{CL+MLP} & \textbf{CL+MLP+T }& \textbf{CL+FCM+T} & \textbf{CL+Pairwise} & \textbf{CL+FCM+Pairwise} & \textbf{GENNAPE} \\ \midrule
\multicolumn{8}{c}{\textbf{NDCG@50}} \\ \midrule
NB-201 & 0.9495 & 0.9848 & \textit{0.9859} & 0.9847 & 0.9793 & \textbf{0.9872} & 0.9836 \\
w/ FT & 0.9819$\pm$0.0056 & 0.9434$\pm$0.0214 & 0.9822$\pm$0.0063 & 0.9848$\pm$0.0040 & \textbf{0.9916$\pm$0.0022} & \textit{0.9907$\pm$0.0052} & 0.9885$\pm$0.0025 \\
NB-301 & 0.7331 & 0.4175 & 0.6311 & \textit{0.7930} & 0.7235 & 0.5218 & \textbf{0.8184}\\
w/ FT & \textit{0.9725$\pm$0.0043} & 0.8912$\pm$0.0480 & 0.9085$\pm$0.0430 & 0.9179$\pm$0.0357 & 0.9302$\pm$0.0690 & 0.9664$\pm$0.0102 & \textbf{0.9764$\pm$0.0045} \\\midrule
PN & 0.6296 & 0.5264 & \textbf{0.9637} & \textit{0.9343} & 0.8935 & 0.6982 & 0.9099 \\
w/ FT & 0.9225$\pm$0.0063 & 0.9619$\pm$0.0031 & \textit{0.9771$\pm$0.0061} & 0.9755$\pm$0.0097 & 0.9757$\pm$0.0082 & 0.9769$\pm$0.0046 & \textbf{0.9836$\pm$0.0037} \\
OFA-MBv3 & 0.8607 & 0.8893 & 0.9268 & \textit{0.9397} & 0.8422 & 0.9182 & \textbf{0.9433} \\
w/ FT & 0.8854$\pm$0.0203 & 0.9653$\pm$0.0028 & \textit{0.9691$\pm$0.0018} & 0.9660$\pm$0.0053 & 0.9644$\pm$0.0186 & \textit{0.9691$\pm$0.0110} & \textbf{0.9778$\pm$0.0018} \\
OFA-RN & \textbf{0.8789} & 0.3144 & 0.2167 & 0.3494 & 0.3583 & 0.4344 & \textit{0.7007} \\
w/ FT & \textbf{0.9746$\pm$0.0073} & 0.9491$\pm$0.0210 & 0.9245$\pm$0.0252 & 0.9077$\pm$0.0295 & 0.9520$\pm$0.0096 & 0.9222$\pm$0.0422 & \textit{0.9531$\pm$0.0169} \\\midrule
HiAML & 0.5097 & 0.7534 & \textbf{0.7681} & \textit{0.7657} & 0.7567 & 0.7470 & 0.7173 \\
w/ FT & 0.7505$\pm$0.0380 & 0.6847$\pm$0.0893 & 0.6903$\pm$0.0550 & 0.7172$\pm$0.0411 & 0.7562$\pm$0.0369 & \textit{0.7570$\pm$0.0284} & \textbf{0.7938$\pm$0.0144} \\
Inception & 0.6196 & 0.7943 & \textbf{0.8607} & 0.8270 & 0.8240 & 0.8386 & \textit{0.8391} \\
w/ FT & 0.7929$\pm$0.0265 & \textbf{0.8515$\pm$0.0287} & 0.8230$\pm$0.0206 & 0.8201$\pm$0.0133 & 0.7843$\pm$0.0194 & 0.8019$\pm$0.0340 & \textit{0.8452$\pm$0.0089} \\
Two-Path & 0.6930 & 0.6722 & \textit{0.7886} & 0.7654 & 0.7272 & 0.7392 & \textbf{0.8115} \\
w/ FT & 0.7860$\pm$0.0268 & 0.7839$\pm$0.0436 & \textit{0.8334$\pm$0.0304} & 0.8326$\pm$0.0281 & 0.7921$\pm$0.0514 & 0.7888$\pm$0.0435 & \textbf{0.8454$\pm$0.0185} \\\midrule
\multicolumn{8}{c}{\textbf{NDCG@10}} \\ \midrule
NB-201 & 0.9270 & 0.9845 & 0.9856 & \textbf{0.9868} & 0.9755 & \textit{0.9858} & 0.9793 \\
w/ FT & 0.9751$\pm$0.0082 & 0.9362$\pm$0.0298 & 0.9818$\pm$0.0063 & 0.9834$\pm$0.0054 & \textbf{0.9910$\pm$0.0023} & \textit{0.9902$\pm$0.0063} & 0.9855$\pm$0.0030 \\
NB-301 & 0.5341 & 0.3278 & 0.6411 & \textit{0.7737} & 0.7260 & 0.4046 & \textbf{0.7885}\\
w/ FT & \textit{0.9723$\pm$0.0134} & 0.8767$\pm$0.0674 & 0.8979$\pm$0.0518 & 0.8961$\pm$0.0710 & 0.9150$\pm$0.0883 & 0.9666$\pm$0.0102 & \textbf{0.9765$\pm$0.0081} \\\midrule
PN & 0.4426 & 0.4668 & \textbf{0.9564} & 0.9003 & \textit{0.9326} & 0.4849 & 0.8736 \\
w/ FT & 0.9287$\pm$0.0271 & 0.9424$\pm$0.0045 & \textit{0.9759$\pm$0.0075} & 0.9716$\pm$0.0144 & 0.9663$\pm$0.0172 & 0.9752$\pm$0.0073 & \textbf{0.9800$\pm$0.0057} \\
OFA-MBv3 & 0.8464 & 0.9092 & \textit{0.9252} & \textbf{0.9270} & 0.8067 & 0.9079 & 0.9234 \\
w/ FT & 0.8859$\pm$0.0536 & 0.9558$\pm$0.0046 & 0.9636$\pm$0.0070 & 0.9620$\pm$0.0100 & 0.9596$\pm$0.0253 & \textit{0.9697$\pm$0.0132} & \textbf{0.9838$\pm$0.0030} \\
OFA-RN & \textbf{0.9470} & 0.2515 & 0.2018 & 0.3036 & 0.3066 & 0.3859 & \textit{0.6606} \\
w/ FT & \textbf{0.9717$\pm$0.0090} & 0.9416$\pm$0.0213 & 0.9174$\pm$0.0333 & 0.8932$\pm$0.0321 & \textit{0.9465$\pm$0.0140} & 0.9129$\pm$0.0422 & 0.9463$\pm$0.0236 \\\midrule
HiAML & 0.5088 & \textit{0.7745} & \textbf{0.7925} & 0.7197 & 0.7498 & 0.7288 & 0.6892 \\
w/ FT & 0.7356$\pm$0.0371 & 0.6743$\pm$0.0848 & 0.6721$\pm$0.0703 & 0.7150$\pm$0.0519 & 0.7470$\pm$0.0449 & \textit{0.7527$\pm$0.0444} & \textbf{0.7804$\pm$0.0211} \\
Inception & 0.6064 & 0.8241 & \textit{0.8666} & 0.7540 & \textbf{0.8736} & 0.7834 & 0.8150 \\
w/ FT & 0.7310$\pm$0.0423 & \textbf{0.8283$\pm$0.0312} & 0.7808$\pm$0.0369 & 0.7605$\pm$0.0276 & 0.7113$\pm$0.0445 & 0.7510$\pm$0.0550 & \textit{0.8073$\pm$0.0072} \\
Two-Path & 0.6339 & 0.6496 & \textit{0.7993} & 0.7944 & 0.7223 & 0.7278 & \textbf{0.8275} \\
w/ FT & 0.7860$\pm$0.0268 & 0.7839$\pm$0.0436 & \textit{0.8334$\pm$0.0304} & 0.8326$\pm$0.0281 & 0.7921$\pm$0.0514 & 0.7888$\pm$0.0434 & \textbf{0.8392$\pm$0.0220} \\\bottomrule
\end{tabular}
\end{threeparttable}
}
\end{table*}
\subsection{Ablation Studies}
\label{sec:ablate}
We ablate the performance of several GENNAPE components, specifically the CL+MLP, CL+MLP+T and CL+FCM+T regressors as well as the CL+Pairwise and CL+FCM+Pairwise classifiers. We consider the zero-shot transfer and fine-tuning contexts, for all target families across three different metrics.
\subsubsection{Spearman's Rank Correlation}
Table~\ref{tab:srcc_ablate} ablates SRCC results across all families. Overall, our findings demonstrate the generalizablity of GENNAPE as it still attains the best correlation performance on many families. Sometimes CL+FCM+T may outperform the full GENNAPE on a family (e.g., OFA-MBv3, HiAML, Inception) in the zero-shot transfer context, yet reinforcing the efficacy of our FCM and MLP-E scheme.
\subsubsection{Kendall's Tau}
We consider Kendall's Tau (KT), which counts the number of concordant and disconcordant pairs in a set and can handle ties. Table~\ref{tab:kendall_ablate} summarizes our findings. GENNAPE clearly outperforms other configurations on this metric in many scenarios. We note that in comparison to SRCC results in Table~\ref{tab:srcc_ablate}, the best performing predictors for any family and context do not change much. This is because KT is a correlation metric like SRCC that considers all samples equally, yet because it calculates over $N^2$ pairs rather than $N$ samples, performance numbers are generally closer to 0.
\subsubsection{Normalized Discounted Cumulative Gain}
NDCG calculations involve selecting the top-$k$ samples, e.g., NDCG@$k$. Before, we considered NDCG@$10$, but now broaden the scope of our ablation results to include NDCG@$50$. Table~\ref{tab:ndcg_ablate} presents our findings. For both values of $k$, GENNAPE most frequently achieves the highest performance, specifically for NDCG@$50$. However, as we decrease $k$ to $10$, several individual CL-based predictors attain the best performance, specifically the ensemble-driven CL+FCM+T.
\subsection{Hardware and Software Details}
\label{sec:hardware}
We perform our experiments on rack servers that use Intel Xeon Gold 6140 CPUs with 756GB of RAM running Ubuntu 20.04.4 LTS. Each server holds a set of 8 NVIDIA Tesla V100 GPUs with 32GB each.
To create Compute Graphs from models we use \texttt{TensorFlow==1.15.0}, reproducing \texttt{PyTorch} models using \texttt{Keras} components when necessary. To train predictor models we use \texttt{PyTorch==1.8.1} as well as \texttt{Pytorch-Geometric}. Additionally, we use \texttt{PyTorch-Fast-Transformers} to implement the transformer module in the CL graph encoder. | {'timestamp': '2022-12-01T02:21:03', 'yymm': '2211', 'arxiv_id': '2211.17226', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17226'} | arxiv |
\section{Introduction}
\label{sec:introduction}
The low cost and versatility of microcontroller platforms have made them an attractive choice for a wide range of applications: an estimated 29B units shipped in 2021~\cite{mcumarket2021}. This includes numerous embedded, personal and IoT devices, many of which could be enhanced with computational intelligence brought by deep learning.
A microcontroller unit (MCU) is a single chip mainly consisting of a power-efficient CPU, read-only Flash memory and read-write static RAM (SRAM). Table~\ref{tab:devices-comp} compares MCUs along compute, memory and storage capacity axes with GPU server and mobile hardware capable of executing neural networks. The low price and power usage of MCUs come with a marked downgrade in the computational ability: memory capacity lies orders of magnitude behind the next-best hardware, and there is little-to-no memory hierarchy and parallelism to exploit for optimisation. This presents a significant challenge to deep learning inference on the device itself, causing applications to rely on fully remote or hybrid deployments~\cite{almeida2021dyno}, which results in sacrifices in data privacy and autonomy.
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{figures/mobilenetv2-pexec-pmu.pdf}
\caption{Per-layer memory usage of MobileNet-v2. \textsc{Pex} automatically creates partial execution schedules that reduce peak memory usage of inference on microcontroller platforms. Memory is reclaimed at no extra computational cost, and the architecture can be pruned to reduce the memory bottleneck identified by \textsc{Pex}. Here, memory usage is reduced by 4$\times$, or 5.5$\times$ with pruning co-design.}
\label{fig:mobilenetv2-pexec-pmu}
\end{figure}
\begin{table}
\caption{Specifications of a high-end GPU, a smartphone, a micro-PC and Nucleo development boards using Cortex M7 and M4 chips. MCUs have the most favourable power efficiency and price but are significantly resource-constrained.}
\label{tab:devices-comp}
\centering
\footnotesize
\begin{tabular}{rrrrr}
\toprule
\multicolumn{1}{l}{\textbf{CPU}} & \multicolumn{1}{l}{\textbf{RAM}} & \multicolumn{1}{l}{\textbf{Storage}} & \multicolumn{1}{l}{\textbf{Power}} & \multicolumn{1}{l}{\textbf{Price}} \\
\midrule
\multicolumn{5}{l}{\textbf{GPU:} NVIDIA A100 GPU} \\
6912$\[email protected] GHz & 40 GB & --- & 400 W & 12.5K\$ \\
\midrule
\multicolumn{5}{l}{\textbf{Mobile:} Galaxy S22 Smartphone} \\
8$\times$ @ $<$2.8 GHz & 8 GB & 128 GB & $\approx$3.6 W & 750\$ \\
\midrule
\multicolumn{5}{l}{\textbf{Micro-PC:} Raspberry Pi 4B} \\
4$\times$ @1.5 GHz & $<$4 GB & 512 GB & 2.7 W & 35\$ \\
\midrule
\multicolumn{5}{l}{\textbf{MCU:} \href{https://os.mbed.com/platforms/ST-Nucleo-F767ZI/}{NUCLEO-F767ZI}~(M7)~\cite{nucleof767zi}} \\
216 MHz & 512 KB & 2 MB & 0.3 W & 9\$ \\
\midrule
\multicolumn{5}{l}{\textbf{MCU:} \href{https://os.mbed.com/platforms/ST-Nucleo-F446RE/}{NUCLEO-F446RE}~(M4)~\cite{nucleof446re}} \\
180 MHz & 128 KB & 512 KB & 0.1 W & 3\$ \\
\bottomrule
\end{tabular}
\end{table}
\begin{figure*}[ht!]
\centering
\includegraphics[width=\textwidth]{figures/pexec-example-rules.pdf}%
\caption{(\textit{Left:}) MobileNet-v2 IRB example within ordinary and partial execution. (\textit{Middle:}) Sample code for partial execution of the IRB and memory bottlenecks before and after compilation. (\textit{Right:}) Diagrammatic representation of all partial execution rules (Section~\ref{sec:pexec-rules}). Execution transitions between partially- and fully-materialised tensors at loop boundaries; the schedule can contain multiple loops.
}
\label{fig:pexec-example-rules}
\end{figure*}
Enabling on-device neural network inference has been shown to require specialised research into low-footprint deep learning. TinyML~\cite{warden2020tinyml} is an active research direction, which encompasses hardware improvements~\cite{sadiq2022tinyops}; systems-level software research, such as runtimes~\cite{david2020tensorflow}, layer implementations~\cite{lai2018cmsis} and model compilers~\cite{chen2018tvm}; model discovery, incl. compression and neural architecture search (NAS)~\cite{liberis2021differentiable, liberis2021munas, banbury2020micronets, lin2020mcunet}.
\subsection{Memory usage of neural networks on MCUs}
In this work, we focus on the issue of high memory (SRAM) usage of neural network inference, which prevents the deployment of models with large activation tensors.
A neural network is defined as a computational graph of layers, called \emph{operators}, with data dependencies between them. Most MCU deep learning runtimes and kernel implementations~\cite{chen2018tvm, david2020tensorflow, lai2018cmsis}, have adopted a \emph{one-operator-at-a-time} execution regime. For each layer/operator in the network, the runtime:
\begin{enumerate}
\item Allocates the output buffer for the operator in SRAM;
\item Executes the operator, using inputs read from SRAM and parameters read from the separate Flash storage;
\item Marks the operator’s inputs’ buffers as available memory (i.e. deallocates from SRAM, may be implicit), if the buffers are not used later.
\end{enumerate}
Under this execution regime, called \emph{ordinary execution}, the memory bottleneck is the size of the largest operator's working set (input and output buffers) along with any other tensors that must be retained for subsequent operators. This bottleneck must lie within the SRAM capacity constraints.
Some systems-level model-agnostic methods have been developed to reduce SRAM usage of neural networks by optimising buffer layout in memory, such as buffer bin-packing~\cite{david2020tensorflow} and operator reordering~\cite{liberis2019neural}. SRAM usage is also an optimisation objective in MCU-compatible model discovery methods~\cite{fedorov2019sparse, liberis2021differentiable, banbury2020micronets}.
\subsection{\textsc{Pex}: Partial execution for memory efficiency}
A core contribution of this paper is a novel model compiler, called \textsc{Pex}, which realises further gains in memory usage by moving beyond the paradigm of executing one operator at a time and instead executing operators \emph{partially} to produce and/or consume \emph{one feature/channel of data at a time}. The idea of \emph{partial execution} can be applied to arbitrary neural networks. A particular instance of this was first described in MobileNet-v2~\cite{sandler2018mobilenetv2} as a memory-efficient trick to execute the inverted residual block (IRB). Figure~\ref{fig:pexec-example-rules} uses this example to illustrate the concept of partial execution, both diagrammatically and in pseudo-code.
Under ordinary execution, the IRB memory bottleneck resides at the operator \boxlabel{C}: the bottleneck consists of the input and output buffers of \boxlabel{C}, as well as output of \boxlabel{A} retained for operator \boxlabel{E}, amounting to 52.7 KB (at 8-bit precision).
However, operators \boxlabel{B}, \boxlabel{C}, and \boxlabel{D} can be combined along the channel axis. In a partial execution loop, for each of the 144 channels, operator \boxlabel{B} (conv.) produces one output channel, operator \boxlabel{C} (depthwise conv.) transforms it, and operator \boxlabel{D} (conv.) consumes it and writes its contribution to its output buffer. The memory bottleneck is within the loop at operator \boxlabel{C}, amounting to 8.5 KB (at 8-bit precision). It consists of the input to \boxlabel{B}, one channel output of \boxlabel{B} (input to \boxlabel{C}), one channel output of \boxlabel{C}, and the full output buffer of \boxlabel{D}, preallocated before the start of the loop.
Such execution has largely become obsolete on mobile platforms due to the abundance of RAM (Table~\ref{tab:devices-comp}) and an inferior data access pattern. However, on MCUs data access pattern is of little concern due to the lack of data caches. Neural networks inspired by the IRB continue to proliferate~\cite{howard2019searching, cai2018proxylessnas, tan2019efficientnet}, so discovering analogous memory-saving execution schedules for new architectures would greatly benefit deep learning for MCUs by reducing the SRAM footprint of inference.
\textbf{Automatic partial execution with \textsc{Pex}.} We devise abstractions and execution rules required to apply partial execution to \emph{any} network layer layout, and \emph{automate} the scheduling decisions using a dynamic programming-based algorithm. These form the core of \textsc{Pex}, which discovers \emph{computationally-equivalent, yet more memory-efficient network execution schedules for arbitrary neural networks}.
Figure~\ref{fig:mobilenetv2-pexec-pmu} shows the per-layer memory usage profile of the MobileNet-v2 architecture, showing that partial execution enables a \emph{4$\times$ peak memory usage reduction}. However, partial execution alone cannot reduce peak memory usage to arbitrarily low values: a particular layer arrangement at the memory bottleneck may not lend itself to optimisation, or the sizes of buffers allocated at the start of the partial execution loop may cause the memory bottleneck.
\textbf{Compiler+pruning network co-design.} We propose using \emph{structured pruning} to change the network architecture automatically to reduce peak memory usage under partial execution. Structured pruning entirely removes the least important feature maps (e.g. convolutional channels), and we instruct it to target memory bottlenecks identified by the compiler. \textsc{Pex} is repeatedly invoked during pruning, with new memory bottlenecks reported back to the pruning algorithm at each step. Conversely, removing feature maps changes loop sizes and execution instructions produced by the compiler. Therefore, the two work in tandem to co-design the network architecture and the execution schedule.
We discuss the place of our methodology within related microcontroller deep learning work in Section~\ref{sec:related-work}, give the algorithm details in Section~\ref{sec:methodology-pexec}, including integration with pruning and considerations around quantisation, and perform quantitative comparisons in Section~\ref{sec:evaluation}.
Overall, the contributions of this work are as follows:
\begin{itemize}
\item We devise abstractions and execution rules for arbitrary networks, which enable partial execution.
\item We devise a model compiler, \textsc{Pex}, which automatically creates a partial execution schedule while minimising peak memory usage, unlocking significant memory usage reduction compared to ordinary evaluation.
\item We leverage partial peak memory usage as an optimisation goal within structured pruning, reducing the model’s memory footprint further automatically.
\item We reduce memory usage by up to 10.5$\times$ and establish new state-of-the-art models for three classification tasks in the low SRAM usage regime, improving accuracy by up to 2.9\%, compared to prior work.
\end{itemize}
\section{Related work}
\label{sec:related-work}
\subsection{Deep learning on microcontrollers}
Prior work in microcontroller deep learning typically assumes an ordinary execution-based runtime, such as TFLM \cite{david2020tensorflow}. MCU-friendly resource footprints are achieved by: manual architecture design~\cite{zhang2017hello, mocerino2019coopnet}, quantisation~\cite{jacob2018quantization}, network pruning~\cite{liberis2021differentiable} or neural architecture search (NAS)~\cite{lin2020mcunet, banbury2020micronets}. Some methods target inference with sparse matrices~\cite{fedorov2022udc, fedorov2019sparse}, or use pruning as a nested step within NAS~\cite{liberis2021munas}. Prior discovered models can operate within the partial execution regime.
Standardised runtimes are an important common ground for hardware, model compression and network design research. However, prior work shows that performance benefits can be reaped by moving beyond standard assumptions. TVM~\cite{chen2018tvm} is a general model compiler that can perform both computation graph- and inference code-level optimisations and produce binaries for various targets, including microcontroller platforms. MCUNet-v2~\cite{lin2021memory} forgoes layer-by-layer execution in favour of executing memory-intense layers using one input tile (“patch”) at a time; we discuss this execution style further on.
Alternatively, computational constraints can be relaxed by introducing memory hierarchy. \citet{svoboda2022deep} show that a microSD card can be used to offload weights and activations of a neural network, which also significantly increases latency and power usage due to data transfer and the presence of external storage. More promisingly, \citet{sadiq2022tinyops} show that a smaller ($<$ 8 MB) SDRAM and external Flash memory can be introduced to offload selected parameters and activation matrices transparently using DMA. This allows approaching the latency of on-chip memory-only inference, but at the cost of additional power usage.
\subsection{Computation split approaches}
\label{sec:related-work-computation-split}
The computation of neural network layers’ outputs can also be split along their spatial axes instead of (or in addition to) the channel axis, resulting in \emph{patch-based execution}.
Computation split approaches for memory-constrained microcontroller platforms overlap, to some degree, with the techniques developed for model parallelism. Conceptually, the two optimise for different scales: model parallelism maximises utilisation, cache hits, or reduces the multi-gigabyte memory (vRAM) footprint or communication overhead on multi-core GPU/TPU hardware for neural network training; here, we split computation to save 100s KB of SRAM for inference on relatively simplistic single-core hardware, but in the presence of quantisation and greater sensitivity to computation overheads (strict compute budget).
The problems can be approached similarly: both develop frameworks to reason about neural networks, which identify independent computations and optimise their execution schedule. \citet{dryden2019improving} parallelise execution over the sample and spatial dimensions (i.e. patches) and optimise workload assignment to processors under a benchmark-informed cost model using a shortest-path graph algorithm; this methodology is also updated to consider channel and filter dimensions of a CNN~\cite{dryden2019channel}; \citet{xu2022training} combine patch-based execution with gradient checkpointing to reduce vRAM usage for high-resolution inputs; \citet{ivanov2021data} analyse data flow to minimise data movement in Transformer models by identifying data layout and operator fusion improvements. We are optimistic about any future methodology cross-over.
In deep learning for MCUs, patch-based execution has been explored by MCUNet-v2~\cite{lin2021memory}. An analogous idea has been previously explored by \citet{alwani2016fused} for avoiding off-chip memory access. Only a spatial segment (a ``patch'') of a layer's output is computed at a time (thus full output is never materialised in memory), before being consumed by subsequent layers. This can greatly reduce peak memory usage, but comes at the cost of computation overhead due to the re-computing of intermediate values that are required for more than one patch (edge overlap). The amount of extra computation varies per architecture and depends on convolutional kernel size and strides. Extended qualitative discussion of this alternative/orthogonal approach is in Appendix~\ref{apx:qualitative-patch-comparison}. As it is the closest relevant prior work, we perform a quantitative comparison in Section~\ref{sec:evaluation}.
\section{Design of Pex}
\label{sec:methodology-pexec}
\textsc{Pex} is a compiler for arbitrary neural networks which automatically generates execution schedules with partial execution loops (e.g. Figure~\ref{fig:mobilenetv2-pexec-pmu}). This drastically reduces SRAM usage compared to ordinary execution used in prior work.
Conceptually, \textsc{Pex} is built as a progression of the following three components: (1) the partial execution framework: rules, axioms and abstractions, which define how each operator may be executed; (2) execution state and memory model, which allows deriving correct execution schedules for the entire network; (3) a dynamic-programming-based algorithm which finds an execution schedule that minimises the peak memory usage.
In the following, we describe the three components of $\textsc{Pex}$ and discuss the interaction between computational correctness and quantization, as well as using $\textsc{Pex}$ within structured pruning to reduce SRAM usage further. For contextual clarity, we will use convolutional neural network (CNN) terminology and reference the MobileNet-v2 IRB example.
\subsection{Partial execution framework}
\label{sec:pexec-rules}
\textbf{Definition 1.} A neural network is a computation graph of tensors, produced by operators (layers). We consider arbitrary neural networks which process $R$-dimensional tensors ($R \geq 2$) of shape $N \times \ldots \times C$, where $N$ is the batch size, and $C$ is the number of channels/feature maps. A "channel" is a tensor slice in the $C$ dimension. This includes 4-dimensional tensors of shape $N \times H \times W \times C$ seen in 2D CNNs, where $H$, $W$ are the width and height of the image. The dimensions' order is unimportant: for CNNs, NCHW and NHWC are supported; NCHW may be preferred to avoid strided loads/writes.
\textbf{Definition 2.} A tensor $t$ can be present in memory in two forms: fully materialised (denoted $t^F$) or partially materialised (only one channel, denoted $t^P$).
\textbf{Definition 3.} There are only two types of operators: channel-wise operators (borrowing CNN terminology; denoted with `\emph{C}') and aggregating operators (denoted with `\emph{A}'):
\begin{itemize}
\item \textit{Channel-wise operators (C-types)} are depthwise convolutions, pooling layers (both local and global) and any element-wise operators such as addition or ReLU. In principle, these operators consume one input channel to produce one output channel. Output channels are independent, and the implementation of the operator is often a simple loop repeating the computation that maps an input channel to an output channel.
\item \textit{Aggregating operators (A-types)} are dot products: convolutions and fully connected (dense) layers. To compute the output tensor, they map all input channels to one output channel (multiple times, for all output channels), or, equivalently, compute one input channel’s contribution to all output channels (multiple times, for all input channels). That is, A-types can either generate one channel of their output at a time, providing the full input buffer is present in memory, or consume one channel at a time and write its contribution to the fully allocated output buffer. Due to this generating/aggregating property, they will be found either at the start or the end of partial execution loops.
\end{itemize}
\textbf{Remark 4.} We describe partial execution loops as processing one channel of data at a time. However, in a loop with a total of $C$ channels to be iterated over, the number of channels computed at once can be any $K \ll C$. Increasing $K$ increases the memory usage but can have a beneficial effect due to the use of SIMD kernel implementations (when $K$ is a multiple of 4) and lowering overhead associated with operator context switching, if any (implementation-dependent). The highest possible value of $K$ that does not cause a memory constraint violation can be found for each loop independently using binary search.
\textbf{Definition 5.} An operator is a mapping from input tensors $i=\{i_1, \ldots\}$ to an output tensor $o$, denoted $i \opexec o$. The operator's type (A or C) allows for multiple ways of executing it using different materialisation forms of inputs $i$ and output $o$. For operators with multiple inputs (e.g. addition), all inputs always share the same materialisation form, so the set of inputs can be denoted with $i^F$ or $i^P$.
In total, we establish six rules for executing an operator $op$ (also see diagram in Figure~\ref{fig:pexec-example-rules}):
\begin{description}
\item[Full continue] (for both A- and C-types): $i^F \opexec o^F$. Input and output buffers are present in memory fully, and the operator is not in a partial execution loop.
\item[Partial continue] (C-type only): $i^P \opexec o^P$. A channel-wise operator is executed for one input channel to produce one output channel. Example: a depthwise conv. operator computing one output channel.
\item[Generate] (A-type only). $i^F \opexec o^P$. Computes one output channel from fully-materialised input data.
\item[Accumulate] (A-type only). $i^P \opexec o^F$ Consumes one channel of input data and writes its contribution to a fully-materialised output buffer.
\end{description}
The following rules only change the materialisation form of a tensor $t$. For tensors consumed by multiple operators, the rule does not have to be applied to all branches.
\begin{description}
\item[Slice:] $t^F \longrightarrow t^P$. The runtime reads one channel at a time from tensor $t$ to facilitate partial execution of any subsequent operator that requires partially-materialised input. In this case, $t^P$ does not need to be explicitly allocated: it is an offset/view into $t^F$.
\item[Post-concatenate:] $t^P \longrightarrow t^F$. Channels of $t$ are written into a preallocated full buffer. In this case, $t^P$ does not need to be explicitly allocated: the producer of $t^P$ can write into a particular offset of $t^F$.
\end{description}
\textbf{Definition 6.} A \emph{loop context} ($\mathcal{C}$) is a set of tensors that are kept in memory (fully materialised) due to a current loop that will repeatedly read from or write to these tensors. Loop context tensors are allocated in SRAM prior to the first iteration of the loop and deallocated after the last iteration.
In MobileNet-v2 IRB (Figure~\ref{fig:pexec-example-rules}), the context consists of inputs to operator \boxlabel{B} (exec. ‘Generate’) and the output of operator \boxlabel{D} (exec. ‘Accumulate’). At the $i^{th}$ iteration of the loop, \boxlabel{B} reads its entire input from the context to produce its $i^{th}$ channel, and \boxlabel{D} writes the contribution of its $i^{th}$ input channel to its output buffer in the context.
\subsection{Deriving an execution schedule}
\begin{table*}[t]
\caption{Execution state transition rules within \textsc{Pex}. The state is a tuple of tensors yet to be computed (`\texttt{Mem}') within a graph $G$ and loop context tensors (`$\mathcal{C}$'). Rules operate by decomposing `\texttt{Mem}' via pattern matching: a rule can be matched to any tensor of `\texttt{Mem}' via the left-hand side of the rule (providing conditions are satisfied). For example, `$\{i^F \opexec o^F\} \cup R$' matches some element of `\texttt{Mem}' that is a fully-materialised tensor `$o^F$'; then, its producing operator is referred to as (bound to) `$op$' whose fully-materialised inputs are `$i^F$', and remaining tensors ($\texttt{Mem} \setminus o^F$) are `$R$'. The execution instructions (named after the state transition rules) are prepended (`::') to the list `$H$'}
\label{tab:pexec-rules}
\centering
\footnotesize
\begin{tabular}{lr@{\hskip 2pt}c@{\hskip 2pt}ll}
\toprule
\textbf{Rule} & \multicolumn{3}{c}{\textbf{State transition}} & \textbf{Conditions} (Appendix~\ref{apx:derivation-rule-conditions}) \\
\midrule
End & $H \vdash \langle \texttt{Mem}, \varnothing \rangle$ & $\rightarrow$ & \textit{done} & $\langle \texttt{Mem}, \varnothing \rangle$ is $S_*$ (final state) \\
Loop End & $H \vdash \langle \texttt{Mem}, {\mathcal{C}} \rangle$ & $\rightarrow$ & $H \vdash \langle \texttt{Mem}, \varnothing \rangle$ & $\forall t \in \texttt{Mem}.$ $t$ is $t^F$ \\
Full Cont. & $H \vdash \langle \{i^F \opexec o^F\} \cup R, {\mathcal{C}} \rangle$ & $\rightarrow$ & $\texttt{FullCont}(op)::H \vdash \langle i^F \cup R, \varnothing \rangle$ & \boxlabel{Eval.}, \boxlabel{No Loop} \\
Partial Cont. & $H \vdash \langle \{i^P \opexec o^P\} \cup R, {\mathcal{C}} \rangle$ & $\rightarrow$ & $\texttt{PartCont}(op)::H \vdash \langle i^P \cup R, {\mathcal{C}} \rangle$ & \boxlabel{Eval.}, \boxlabel{In Loop}, \boxlabel{C} \\
Generate & $H \vdash \langle \{i^F \opexec o^P\} \cup R, {\mathcal{C}} \rangle$ & $\rightarrow$ & $ \texttt{Generate}(op)::H \vdash \langle i^F \cup R, {\mathcal{C}} \cup i \rangle$ & \boxlabel{Eval.}, \boxlabel{Compat. Loop}, \boxlabel{A}, $o \not\in {\mathcal{C}}$ \\
Aggregate & $H \vdash \langle \{i^P \opexec o^F\} \cup R, {C} \rangle$ & $\rightarrow$ & $\texttt{Aggregate}(op)::H \vdash \langle i^P \cup R, {\mathcal{C}} \cup \{o\} \rangle$ & \boxlabel{Eval.}, \boxlabel{Compat. Loop}, \boxlabel{A}, $o \not\in {\mathcal{C}}$ \\
Slice & $H \vdash \langle \{t^F \longrightarrow t^P\} \cup R, {\mathcal{C}} \rangle$ & $\rightarrow$ & $\texttt{Slice}(t)::H \vdash \langle {t^F} \cup R, {\mathcal{C}} \cup \{t\} \rangle $ & \boxlabel{Compat. Loop}, $t \not\in {\mathcal{C}}$ \\
Post-Concat. & $H \vdash \langle\{t^P \longrightarrow t^F\} \cup R, {\mathcal{C}} \rangle$ & $\rightarrow$ & $\texttt{PostConcat}(t)::H \vdash \langle t^P \cup R, {\mathcal{C}} \cup \{t\} \rangle$ &
\boxlabel{Compat. Loop} \\
\bottomrule
\end{tabular}
\end{table*}
A compiler produces a sequence of \emph{instructions}, which determine which operator should be executed (and how), to obtain the network's outputs from its inputs. Conceptually, an instruction is an action that causes the \emph{execution state} to transition from some current state to the next state. The instructions are applied until the final state is reached in which all neural network layers were executed.
We are interested in modelling memory usage, so the execution state will consist of information about tensors present in the memory, their materialisation form, and information about the current partial execution loop, if any.
\textbf{Definition 7.} The algorithm considers an execution state $S = \langle \texttt{Mem}, \mathcal{C} \rangle$ and builds up an instruction list (history) $H$. ‘\texttt{Mem}’ is the state of memory: a set of tensors currently present in memory, each either fully or partially materialised; ‘$\mathcal{C}$’ is the loop context (see Def. 6); $H$ is a list of instructions required to arrive at state $S$.
\textbf{Remark 8.} The network's parameters (weights) do not reside in SRAM under any execution regime---individual values are loaded from the read-only on-chip Flash memory.
\textbf{Definition 9.} The algorithm works backwards through the network computation graph $G$---tensors in `\texttt{Mem}' are treated as tensors yet to be computed. The initial state $S_0$ is the set of fully-materialised graph output tensors: $S_0 = \langle \{o^F | o \in \textnormal{outputs}(G)\}, \varnothing \rangle$ and, similarly, the final state $S_*$ is the set of fully-materialised inputs. This acts as a reachability analysis: only required operators will be executed.
\textbf{Constraint 10.} No output is computed twice. We do not aim to increase the amount of computation required for a single inference pass of a neural network.
\textbf{Definition 11.} Table~\ref{tab:pexec-rules} lists allowed state transitions, called \emph{derivation rules}. Each rule has a set of conditions which must be satisfied for it to be applied. The transitions closely match the operator evaluation rules described earlier, but also modify the loop context as required.
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{figures/mnetv2-state-complex.pdf}%
\caption{(\textit{Left and middle:}) MobileNet-v2 IRB example as a type-annotated and an execution state graph. (\textit{Right:}) A more complex computation graph with multiple partial execution loops.}
\label{fig:mnetv2-state-complex}
\end{figure}
If derivation rules can be successfully applied to transition from the starting to the final state, we obtain a sequence of instructions (potentially, out of many) to execute a neural network. Figure~\ref{fig:mnetv2-state-complex} shows how the MobileNet-v2 IRB example can be viewed within the devised framework: first, by erasing particular layer information, leaving only A- and C-type annotations; then, by applying the derivation rules to produce a state transition graph. The figure also gives an example of a more complex execution schedule using more execution rules, containing two loops with multiple operators at the start and the end of a loop. The compiler may fall back to ordinary execution by only using ‘Full Continue’.
\subsection{An algorithm to minimise peak memory usage}
Out of numerous valid derivations, we are interested in choosing instructions that minimise SRAM usage. If we knew which sequence of instructions minimises peak memory usage from a particular execution state, we could record and reuse this information to build up a full execution schedule---a hallmark of a dynamic programming algorithm.
Algorithm~\ref{alg:optimise-pmu-func} describes a high-level pseudocode procedure `\texttt{OptimisePMU}' which enumerates all state transitions to find a sequence of instructions that results in the smallest peak memory usage (PMU) for arbitrary neural network computation graphs. Note that calls are memoised: \emph{results for the same input are remembered and not recomputed}. In practice, we are interested in not just accumulating execution history $H$ but also keeping track of the best-seen peak memory usage and the \emph{complete} loop context (denoted $\mathcal{C}^*$, returned from upstream computation) to calculate the PMU of operators within partial execution loops. The algorithm has exponential computational complexity in the number of operators but, due to small input size ($<$ 100 operators) and limited branching in the network architecture, the optimised schedules are obtained within seconds in practice.
\setlength{\textfloatsep}{10pt}
\begin{algorithm}[h]
\caption{\textsc{OptimisePMU} computes a partial execution schedule which minimises peak memory usage.}
\label{alg:optimise-pmu-func}
\small
\algrenewcommand\algorithmicindent{1.0em}%
\begin{algorithmic}[1]
\State \Comment{\textit{Input:} a set of tensors to be computed \texttt{Mem} and loop context $\mathcal{C}$ (empty for the initial call).}
\State \Comment{\textit{Returns:} the instruction list $H$, the computed PMU and the final loop context $\mathcal{C}^*$ (empty iff $\mathcal{C} = \varnothing$).}
\Function{OptimisePMU}{\texttt{Mem}, $\mathcal{C}$}
\If{\texttt{End} (\texttt{Mem}, $\mathcal{C}$) \textit{conditions are satisfied}}
\State \Return $\langle H{=}[], \textnormal{PMU}{=}\sum_{t \in \texttt{Mem}} |t|, \mathcal{C}^*{=}\varnothing \rangle$
\EndIf
\If{\texttt{LoopEnd} (\texttt{Mem}, $\mathcal{C}$) \textit{conditions are satisfied}}
\State $H$, PMU, $\varnothing$ $\gets$ \Call{OptimisePMU}{\texttt{Mem}, $\varnothing$}
\State \Return $\langle H, \textnormal{PMU}, \mathcal{C} \rangle$
\EndIf
\State bestConfig $\gets$ \textit{(unknown)}
\For{$t \in \texttt{Mem}$}
\For{\textit{Rule} $\in \{\texttt{FullContinue}, \texttt{Slice}, \ldots \}$}
\If{\textit{Rule} (\texttt{Mem}, $\mathcal{C}$) \textit{conditions are satisfied}}
\State $\texttt{Mem}'$, $\mathcal{C}'$ $\gets$ \textit{Rule}($t$, \texttt{Mem}, $\mathcal{C}$)
\State $H'$, PMU$'$, $\mathcal{C}^*$ $\gets$ \Call{OptimisePMU}{$\texttt{Mem}'$, $\mathcal{C}'$}
\State PMU$^*$ $\gets$ max(PMU$'$, \textsc{LocalPMU}($t$, $\texttt{Mem}'$, $\mathcal{C}^*$))
\If{$\langle H', \textnormal{PMU}', \mathcal{C}^* \rangle$ \textit{better than} bestConfig}
\State bestConfig $\gets$ $\langle H', \textnormal{PMU}', \mathcal{C}^* \rangle$
\EndIf
\EndIf
\EndFor
\EndFor
\State \Return bestConfig
\EndFunction
\end{algorithmic}
\end{algorithm}
The algorithm relies on four straightforward helper functions: (1) `\textit{rule conditions are satisfied}' checks if \texttt{Mem} and $\mathcal{C}$ satisfy set predicates set out in the definition of rule; (2) \textit{Rule(...)} invocation updates \texttt{Mem} and $\mathcal{C}$ according to the rule definition; (3) \textsc{LocalPMU}($t$, \texttt{Mem}, $\mathcal{C}^*$) computes the memory usage required (working set size) for tensor $t$ to be computed using tensors in \texttt{Mem}; if loop context is present, it will be counted towards the memory usage; (4) `\textit{configuration $x$ is better than $y$}' compares scheduling results: true if $x$ has lower peak memory usage, if $y$ is invalid, or if PMU is equal but $x$ is simpler; the latter can express a preference to avoid partial execution when there is no PMU improvement.
\setlength{\textfloatsep}{20pt}
\subsection{Effects on quantisation}
\label{sec:quant-effects}
Neural network deployment on MCUs requires parameters and activations to be quantised. This both enables the execution and saves space: an MCU may not have floating-point processing units, or they may consume more power; Flash and SRAM usage is reduced when parameters and activations are stored at e.g. 8-bit precision, instead of 32 bits.
Popular runtime and layer implementations use affine quantisation~\cite{jacob2018quantization}, where operators compute a single output element at a time (stored in a CPU register) by accumulating contributions from all input features (multiplied by the learned weight) at 32-bit precision. When all contributions have been added, an activation function is applied, and the output is written to SRAM at 8-bit precision.
This poses a memory usage vs. correctness trade-off for operators executed using the `Accumulate' partial execution rule, which accumulate input contributions at each loop iteration: the accumulation/output buffers must be kept in SRAM at 32-bit precision for computational correctness. This would result in a 4$\times$ memory usage increase for these buffers (changing from 8-bit to 32-bit representation), potentially reducing memory usage gains under partial execution.
To address this issue, we experiment with reducing the precision of the accumulation buffer, thus removing the 4$\times$ memory inflation. The ‘Accumulate’ rule would only apply to a few layers in the network; we expect other layers to learn to compensate for any performance hit caused by the reduced precision of affected convolutions. We experiment with quantization-aware training using 32-bit, 16-bit and 8-bit precision for accumulation buffers and find no performance degradation in the network (see Section~\ref{sec:quant-effects-analysis}).
\subsection{Structured pruning for partial execution}
Most deep learning models are too resource-demanding for MCU hardware, not just due to their memory usage but also size or latency, which can be addressed with model compression. Typically, three dimensions of resource usage are optimised for MCU compatibility: (a) peak memory usage (bounded by SRAM size), (b) model size (bounded by Flash memory) and (c) the number of multiply-accumulate operations (MACs, \citet{liberis2021munas} show that MACs are a highly accurate proxy for latency on an MCU processor).
We integrate \textsc{Pex} with the state-of-the-art MCU-aware model compression, which operates on the basis of differentiable structured pruning~\cite{liberis2021differentiable}, with the aim of (a) producing MCU-compatible models for our evaluation and (b) guiding pruning towards the memory bottleneck identified by our compiler. The method removes entire features/channels by repeatedly querying optimisation objectives during compression: we replace the default peak memory usage metric with an invocation of \textsc{Pex}, which reports the peak memory usage under partial execution and which operators' outputs constitute the bottleneck.
\begin{table*}[t]
\caption{Resource usage of variations of MobileNet-v2 on ImageNet using ordinary, patch-based (4 $H$ and $W$ patches) or partial execution. PMU improvements brought by patch-based or partial execution vary, but partial execution always has zero computational overhead.}
\label{tab:mnetv2-patch-comparison}
\centering
\footnotesize
\begin{tabular}{lrrrrrrrrr}
\toprule
\multirow{2}{*}{\makecell[l]{\textbf{MobileNet-v2} \\ \textbf{variant}}} &
\multicolumn{2}{c}{\textbf{Loop overhead}} &
\multicolumn{2}{c}{\textbf{Total overhead}} &
\multicolumn{3}{c}{\textbf{Peak memory usage (PMU)}} &
\multirow[b]{2}{*}{\makecell[c]{\textbf{Accuracy} \\ \textbf{(8-bit q.)}}} &
\multicolumn{1}{c}{\textbf{MACs}} \\
\cmidrule{2-3} \cmidrule{4-5} \cmidrule{6-8} \cmidrule{10-10}
& \textbf{Patch$^\dagger$} & \textbf{Partial} & \textbf{Patch$^\dagger$} & \textbf{Partial} & \textbf{Ordinary} & \textbf{Patch$^\dagger$} & \textbf{Partial} & & \textbf{Ordinary} \\
\midrule
Original & +30.6\% & \textbf{0\%} & +9.3\% & \textbf{0\%} & 1505 kB & 321 kB & 376 kB & 71.52\% & 301 M \\
RD (MCUNet-v2) & +13.8\% & \textbf{0\%} & +2.9\% & \textbf{0\%} & 1505 kB & 283 kB & 376 kB & 71.16\% & 294 M \\
Our modification & +38.9\% & \textbf{0\%} & +11.2\% & \textbf{0\%} & 978 kB & 278 kB & \textbf{226 kB} & 71.20\% & 295 M \\
\textsc{Pex}-pruning co-design & +36.1\% & \textbf{0\%} & +9.6\% & \textbf{0\%} & 1505 kB & 321 kB & 276 kB & 71.20\% & 288 M \\
Original, 172$\times$172 res. & +45.2\% & \textbf{0\%} & +12.6\% & \textbf{0\%} & 888 kB & \textbf{218 kB} & \textbf{222 kB} & 69.58\% & 193 M \\
\bottomrule
\end{tabular}
\end{table*}
This leads to \emph{co-design} between the model compression and the partial execution compiler. Both structured pruning and the compiler operate on the channel dimension of the neural network operators. Iteratively, the following takes place: (1) pruning adjusts per-layer channel counts based on the current memory bottleneck, and other resource usage objectives; (2) the compiler computes a new execution schedule using the updated operator channel dimensions: this new schedule is likely different due to new channel dimensions; (3) the compiler reports a new peak memory usage result and new memory bottleneck back to the pruning algorithm.
\section{Evaluation}
\label{sec:evaluation}
In this section, we quantitatively evaluate our contributions:
\begin{enumerate}
\item We compare partial execution with patch-based execution (MCUNet-v2), the closest relevant prior work, by considering peak memory usage reduction and overheads of either approach on MobileNet-v2 models.
\item We apply \textsc{Pex} to five classes of architectures, using partial execution alone or the compiler-pruning co-design, to establish new state-of-the-art solutions in the low SRAM usage regime, compared to ten prior low-footprint models on three classification tasks.
\item We test whether storing accumulation buffers at reduced precision affects models' accuracy (Section~\ref{sec:quant-effects}).
\end{enumerate}
\subsection{Comparison with patch-based execution}
\label{sec:patch-comparison}
Patch-based execution is an alternative approach of splitting the computation to reduce memory usage (Section~\ref{sec:related-work-computation-split}), which uses tensor slices along the image width and height axes (``patches''), instead of the channel axis. For MCUs, it is implemented by MCUNet-v2~\cite{lin2021memory}: we compare it to \textsc{Pex} by examining the memory usage reduction and computational overheads for the MobileNet-v2 model, followed by several modifications to it that enable further improvement in SRAM usage.
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{figures/mnetv2-mods.pdf}%
\caption{Modified versions of MobileNet-v2 which, compared to the original architecture, allow greater SRAM usage reduction within patch-based (\textit{left}) or partial (\textit{right}) execution (Table~\ref{tab:mnetv2-patch-comparison}).}
\label{fig:mnetv2-mods}
\end{figure}
\renewcommand*{\thefootnote}{\fnsymbol{footnote}}
Table~\ref{tab:mnetv2-patch-comparison} (row 1) considers variations of MobileNet-v2 architecture, evaluated on ImageNet.\footnote[2]{The resource usage, overheads, and accuracy of MCUNet-v2 models have been adjusted from originally reported data due to differences in evaluation. We explain the rationale in Appendix~\ref{apx:quantitative-mcunet-adjustment}.}
The execution takes $\approx$301 M MACs and has a peak memory usage of 1505 kB. Patch-based and partial execution reduce it to 321 kB ($\downarrow$4.7$\times$) and 372 KB ($\downarrow$4$\times$), respectively, at the cost of additional 9.3\% increase in MAC operation count for patch-based execution yet \emph{zero computational overhead for our approach}.
\renewcommand*{\thefootnote}{\arabic{footnote}}
It is impossible to conclusively argue whether a patch-based or partial approach is generally superior at reducing peak memory usage: the outcome depends on the architecture. To illustrate this, we consider two modifications of MobileNet-v2 in Figure~\ref{fig:mnetv2-mods}: (a) to reduce overheads of patch-based execution, MCUNet-v2 develop an alternative version with a redistributed receptive field (RD): a change to reduce the spatial resolution and kernel size earlier in the network; (b) we present a version that reduces the memory bottleneck via additional spatial downsampling within the first inverted residual block (``MBConv''), in its projection layer, instead of the following block.
Table~\ref{tab:mnetv2-patch-comparison} (rows 2, 3) shows that these minor modifications can drastically affect the models’ resource usage: our variation of MobileNet-v2 significantly increases computation faced by patch-based execution compared to the original model (15.5\% total MAC increase) but, in the partial execution paradigm, yields the lowest peak memory usage seen so far with no computation overhead.
The modifications above are specific to MobileNet-v2 and cannot be straightforwardly applied to other architectures. Therefore, we consider two other generic ways to reduce an architecture's peak memory usage: our compiler-pruning co-design and using lower input resolution. Table~\ref{tab:mnetv2-patch-comparison} (rows 4, 5) show that (a) co-design can reduce PMU under partial execution to match that of patch-based execution while offering comparable accuracy/MACs to the two previously considered modifications; (b) by lowering the input resolution, we observe the lowest peak memory usage achieved so far (218--222 KB) at the cost of a $<$ 2\% accuracy drop.
\textit{Summary of \ref{sec:patch-comparison}.} The network's architecture determines whether patch-based or partial execution will give greater memory reduction, and can be modified to benefit either approach. Partial execution has no computational overhead.
\subsection{Models under partial execution regime}
\label{sec:discovered-models}
In this section, we show the peak memory usage improvements achievable by \textsc{Pex} alone and the compiler-pruning co-design. We limit our scope to CNNs, as the most popular type of low-footprint neural networks, and consider three classification tasks: ImageNet (1000-class image classification)~\cite{deng2009imagenet}, VisualWakeWords (person detection)~\cite{chowdhery2019visual} and SpeechCommands (keyword recognition via spectrogram classification)~\cite{warden2018speech}, and five classes of architectures: MobileNet-v2~\cite{sandler2018mobilenetv2}, EfficientNet~\cite{tan2019efficientnet}, RES-15~\cite{tang2018deep}, MCUNet-v1 networks~\cite{lin2020mcunet} and MicroNets~\cite{banbury2020micronets}. Additional comparison points are provided by the differentiable pruning (DiffPru), DS-CNN~\cite{zhang2017hello}, MCUNet-v2~\cite{lin2021memory}, RES-8~\cite{tang2018deep} and ETinyNet~\cite{xu2022etinynet} architectures, resulting in ten low-footprint baselines. Models have been reevaluated under the same training pipeline and resource usage metrics (except for MCUNet-v2$^\dagger$). We use the peak memory usage (PMU) versus classification accuracy plots for comparison; tabular data with all metrics are available in Appendix~\ref{apx:architecture-tables}.
\begin{figure}[ht!]
\centering
\includegraphics[width=\linewidth]{figures/imagenet-pareto.pdf}\\
\includegraphics[width=\linewidth]{figures/visualwakewords-pareto.pdf}\\
\includegraphics[width=\linewidth]{figures/speechcommands-pareto.pdf}%
\caption{Peak memory usage \emph{vs} accuracy on the considered datasets. The datapoint label, if present, denotes the input resolution (e.g. ‘r160’ for 160x160 colour input) and, for MCU-compatible models, the size (storage requirement).
\label{fig:pareto-fronts}
\end{figure}
\textbf{ImageNet under 128 kB of SRAM.}
Figure~\ref{fig:pareto-fronts} (top) shows the peak memory usage versus accuracy trade-off for ImageNet models. \textsc{Pex} alone improves PMU by 2.2$\times$ and 2.5$\times$ for MCUNet-v1 and EfficientNet-B0 architectures. The compiler-pruning co-design produces \emph{the only set of high-performing models under 128 kB SRAM usage} amongst considered baselines in our evaluation environment. The models achieve 64.5\%--65.4\% accuracy, significantly outperforming a low-resolution MobileNet-v2 model (+13.9\%).
\textbf{VisualWakeWords under 32 kB of SRAM.} Figure~\ref{fig:pareto-fronts} (middle) shows the results for a variety of models for different input resolutions on the Visual Wake Words dataset. On MobileNet-v2, increasing input resolution increases PMU while producing diminishing returns in classification accuracy. At 80$\times$80 input resolution, the compiler-pruning co-design decreases the PMU by 6.8$\times$ compared to the baseline, bringing it within the 32 kB range. This constitutes a +2.9\% accuracy improvement compared to prior work (MicroNets VWW-2 and DiffPru) within this SRAM usage range. Alternatively, recovered SRAM allows using higher resolution inputs to \emph{increase accuracy by +3.9\% while retaining comparable SRAM usage} to the baseline.
\textbf{Keyword spotting under 16 KiB SRAM.} Figure~\ref{fig:pareto-fronts} (bottom) shows results for the SpeechCommands dataset. We apply both the partial execution compiler alone, and the compiler-pruning co-design to the parent architecture of MicroNets-L (i.e. instantiated at full channel counts, abbr. MN-L in the figure), and the RES-15 architecture. The use of compiler alone yields 2.5$\times$ and 1.5$\times$ memory reduction, respectively, and the use of pruning brings the models under the desired SRAM limit, with only up to 1\% accuracy loss compared to their original unpruned versions. This constitutes a +1.9\% accuracy improvement compared to prior work (DS-CNN-S) under the 16 KiB SRAM limit. Applying co-design to the RES-15 architecture yields \emph{up to 10.5$\times$ memory reduction while matching the classification accuracy} compared to the MicroNets-KWS-L baseline (using ordinary execution).
\textit{Summary of \ref{sec:discovered-models}.} \textsc{Pex} and \textsc{Pex}-pruning co-design reduce peak memory usage of high-performing models to establish state-of-the-art results in low SRAM usage regimes.
\subsection{Accumulation buffer precision analysis}
\label{sec:quant-effects-analysis}
Previously, in Section~\ref{sec:quant-effects}, we discussed how the interaction of quantisation and partial execution requires intermediate results of operators executed using the ‘Accumulate’ rule to be stored at 32-bit precision to preserve computational correctness.
To remedy the resulting memory usage increase, we suggest sacrificing computational correctness for affected operators by storing accumulation buffers at reduced precision and allowing other operators to learn to compensate for this imprecision.
We aim to see whether reduced precision results in accuracy loss. We extended TensorFlow's quantisation-aware training (QAT) implementation to learn quantisation parameters for accumulation buffers (pre-activation), which are used during execution to re-quantise the buffers to the desired precision when updated. We experiment with the 32-bit (correct), 16-bit and 8-bit precision. The scheduler is parameterised with the memory cost of increased precision and, therefore, the ‘Accumulate’ rule will be avoided if there is an alternative with a lower PMU and fewer affected layers.
\begin{table}[t]
\caption{The impact of reduced accumulator precision for three diverse models. The data shows no to negligible accuracy loss from sacrificing computational correctness for PMU reduction.}
\label{tab:quant-accum-analysis}
\centering
\footnotesize
\begin{tabular}{lll}
\toprule
\makecell[c]{\textbf{MCUNet-v1-S} \\ \textbf{ImageNet 160x160}} &
\makecell[c]{\textbf{MobileNet-v2} \\ \textbf{VWW 160x160}} &
\makecell[c]{\textbf{MicroNets-KWS-L} \\ \textbf{SpeechCommands}} \\
\midrule
\multicolumn{3}{c}{\underline{\textbf{Mode:} Ordinary execution in \texttt{int8}}} \\[0.5em]
\makecell[l]{
PMU: 333 kB \\
Acc.: 59.89\% \\
0 accum. layers
} &
\makecell[l]{
PMU: 768 kB \\
Acc: 90.14\% \\
0 accum. layers
} &
\makecell[l]{
PMU: 170 kB \\
Acc: 96.77\% \\
0 accum. layers
} \\
\midrule
\multicolumn{3}{c}{\underline{\textbf{Mode:} Partial execution w/ 32-bit accumulators (QAT)}} \\[0.5em]
\makecell[l]{
186 kB ($\downarrow$1.8$\times$) \\
Acc.: 59.91\% \\
1 accum. layer
} &
\makecell[l]{
307 kB ($\downarrow$2.5$\times$) \\
Acc.: 90.14\% \\
0 accum. layers
} &
\makecell[l]{
69.0 kB ($\downarrow$2.5$\times$) \\
Acc.: 96.77\% \\
0 accum. layers
} \\
\midrule
\multicolumn{3}{c}{\underline{\textbf{Mode:} Partial execution w/ 16-bit accumulators (QAT)}} \\[0.5em]
\makecell[l]{
186 kB ($\downarrow$1.8$\times$) \\
Acc: 59.85 \\
1 accum. layer
} &
\makecell[l]{
294 KB ($\downarrow$2.6$\times$) \\
Acc: 90.12\% \\
2 accum. layers
} &
\makecell[l]{
69.0 kB ($\downarrow$2.5$\times$) \\
Acc: 96.71\% \\
1 accum. layer
} \\
\midrule
\multicolumn{3}{c}{\underline{\textbf{Mode:} Partial execution w/ 8-bit accumulators (QAT)}} \\[0.5em]
\makecell[l]{
141 kB ($\downarrow$2.4$\times$) \\
59.66\% (-0.23\%) \\
4 accum. layers
} &
\makecell[l]{
192 kB ($\downarrow$4$\times$) \\
Acc: 90.14\% \\
3 accum. layers
} &
\makecell[l]{
65.8 kB ($\downarrow$2.6$\times$) \\
Acc: 96.99\% \\
2 accum. layers
} \\
\bottomrule
\end{tabular}
\end{table}
Partial execution is mathematically equivalent to ordinary execution: without quantisation, both approaches have tensor values within the noise introduced by a differing order of operations; with quantisation, this noise is amplified, resulting in accuracy differences. We repeat the QAT for different quantisation levels of accumulation buffers; this also introduces noise due to randomness in the training pipeline, and the reduced precision also acts as a regulariser during QAT.
Table~\ref{tab:quant-accum-analysis} shows the classification accuracy of MCUNet-v1-S, MobileNet-v2, and MicroNets-KWS-L models under ordinary and partial execution, which shows no accuracy loss is observed for all tasks for up to 16-bit accumulation precision, resulting in up to 2.6$\times$ PMU reduction. Lowering the precision to 8-bit results in up to 4$\times$ PMU reduction and -0.23\% accuracy loss only in the MCUNet-v1-S experiment.
\textit{Summary of \ref{sec:quant-effects-analysis}.} Operators executed using the `Accumulate' rule can use reduced accumulation precision for lower memory usage: this has no or negligible accuracy loss.
\subsection{Limitations and future work}
\textsc{Pex}'s ability to reduce memory usage is limited by the network's architecture (also applies to patch-based execution, see Appendix~\ref{apx:qualitative-patch-comparison}), which can be adjusted in an informed way to allow further memory improvement. Here, we leveraged pruning as a general way to do so; \textsc{Pex} could be integrated with a neural architecture search system (NAS) that considers different layer connectivity to avoid some unfavourable layer arrangements automatically.
Additionally, data from an on-device MCU deployment could be of interest as auxiliary evaluation; however, because partial evaluation yields deterministic memory usage gains, which we have also verified in simulation, we would expect any on-device deployment to only confirm this.
\section{Conclusions}
A limited amount of SRAM on microcontroller platforms significantly impedes the on-device execution of neural networks on embedded, personal and IoT devices. To address this, we created a partial execution framework for arbitrary neural networks within the \textsc{Pex} model compiler, which automatically finds execution schedules that minimise peak SRAM usage. This is achieved by identifying subgraphs of the network's layers whose execution can be split along the channel axis, resulting in a computationally-equivalent yet more memory-efficient schedule compared to ordinary execution, at no extra computational cost. We enhance \textsc{Pex} with a structured pruning method, resulting in a co-design between the network's architecture and its execution schedule, which reduces SRAM usage even further. We evaluate \textsc{Pex} on five architecture classes and establish state-of-the-art performance in low SRAM usage regimes for ImageNet, VisualWakeWords and SpeechCommands datasets with up to +2.9\% accuracy increase, compared to ten prior low-footprint models. We find that a 4$\times$ memory usage reduction is possible by applying \textsc{Pex} alone, or up to 10.5$\times$ when using the compiler-pruning co-design, while maintaining the same classification accuracy. Alternatively, the recovered SRAM can be used to process higher resolution inputs, boosting accuracy by up to +3.9\% on Visual Wake Words.
| {'timestamp': '2022-12-01T02:21:26', 'yymm': '2211', 'arxiv_id': '2211.17246', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17246'} | arxiv |
\section{Introduction}
The task of multi-camera 3D object detection is fundamental in autonomous driving, which draws great attention in both the research and the industry community recently. Since the scalable paradigm BEVDet \cite{BEVDet} was first introduced to this problem, we have witnessed a mass of progress \cite{BEVDet4D, BEVDepth, BEVStereo, BEVFusionMIT, BEVFusion, UVTR, STS, SOLOFusion, BEVerse} in the past year. With this technical report and the released code, we offer a new codebase version of the BEVDet, dubbed dev2.0. BEVDet-dev2.0 is deployment oriented with an outstanding trade-off between inference speed and accuracy. It inherits the advantages of the BEVDet \cite{BEVDet} while is further developed from several aspects like engineering optimization of some modules and feature integration of some recent progress.
This script is more like a tech report rather than a thesis. Detailed introduction and ablation of some modifications are omitted as they are consistent with the papers they first appear in. We sincerely thanks them for their great contributions to this area. In the following, we'll introduce how we develop branch dev2.0 from the perspective of deployment. Some quantitative results with both accuracy and inference speed are listed to reveal the power of branch dev2.0.
\begin{figure*}[t]
\centering
\includegraphics[width=1.0\linewidth]{view-transformation.pdf}
\caption{Illustration of BEVPool from BEVFusion \cite{BEVFusion} and BEVPoolv2 from BEVDet-dev2.0. The part in low transparency can be pre-computed offline. }
\label{fig:viewtransformation}
\end{figure*}
\section{Modification}
\subsection{BEVPoolv2}
One of the main drawbacks of the Lift-Splat-Shoot view transformer \cite{LSS} is that it has to compute, store, and preprocess the frustum feature with a large size of $(N,D,H,W,C)$, where $N$, $D$, $H$, $W$ and $C$ are the number of views, the class number of depth, the height of the feature size, the width of the feature size, and the channel number of feature respectively. As illustrated in the left of Fig.~\ref{fig:viewtransformation}, it is computed with the depth score in size of $(N,D,H,W)$ and the feature in size of $(N,H,W,C)$. Then it is preprocessed alone with the voxel index, which indicates the voxel that the frustum points belong to and is computed according to the camera's intrinsic and extrinsic. The preprocessing includes filtering the frustum points that are out of the scope of all voxels and sorting the frustum points according to their voxel index. After that, the frustum points within the same voxel are aggregation by cumulative sum \cite{LSS}. Instead of cumulative sum, BEVPool in BEVFusion \cite{BEVFusion} uses multiple processing threads to accelerate this procedure. However, it still needs to compute, store and preprocess the frustum feature, which is both memory-consumptive and calculation consumptive. A similar situation can be observed in BEVDepth \cite{BEVDepth} and BEVStereo \cite{BEVStereo} with VoxelPool. As illustrated in Fig.~\ref{fig:speedresolution} and Fig.\ref{fig:memoryresolution}, when the input resolution is increased, their efficiency degenerates obviously and the memory requirement boosts to an extremely high level. For example with a depth dimension of 118 and an input resolution of $640\times1760$, the previous fastest implementation can only be processed at 81 FPS and occupies cache memory up to 2,964 MB. It is obviously infeasible on edge devices.
We propose BEVPoolv2 in branch dev2.0 with engineering optimization to completely get rid of this drawback. As illustrated in the right of Fig.~\ref{fig:viewtransformation}, the idea is very simple. We just use the index of frustum point as a trace of them to be preprocessed alone with their voxel index. Then we access the value of the frustum point feature in the processing thread according to the frustum index. In this way, we avoid explicitly computing, storing, and preprocessing the frustum feature. Thus, the memory and calculation can be saved and the inference can be further speeded up. Both the voxel index and frustum index can be pre-computed and preprocessed offline. During the inference, they just act as fixed parameters.
As illustrated in Fig.~\ref{fig:speedresolution}, with pre-computation acceleration, the inference speed of the BEVPoolv2 is up to 4,863 PFS in a low input resolution of $256\times704$ and still maintains 1,509 FPS in high resolution of $640\times1760$. It is 3.1 times the previous fastest implementation in a low input resolution of $256\times704$ and 8.2 times in a high resolution of $640\times1760$. BEVPoolv2 is so fast that makes the view transformation no longer to be the bottleneck in the hold pipeline. Last but not least, the memory saved by avoiding storing the frustum feature is also appealing. As illustrated in Fig.~\ref{fig:memoryresolution}, the memory requirement of the ours implementation is far less than that of the previous implementations and can be maintained at an extremely low value when the input solution is increasing. This makes the Lift-Splat-Shoot view transformer feasible to be deployed on edge devices.
\begin{figure*}[t]
\centering
\includegraphics[width=0.85\linewidth]{speed-resolution.pdf}
\caption{Inference speed of different implementation of Lift-Splat-Shoot view transformation. When the number of depth classes is set as $D=59$, the implementation of branch dev2.0, dubbed BEVPoolv2 is 3.1 times the previous fastest implementation in a low input resolution of $256\times704$ and 8.2 times in a high resolution of $640\times1760$. }
\label{fig:speedresolution}
\end{figure*}
\begin{figure*}[t]
\centering
\includegraphics[width=0.85\linewidth]{memory-resolution.pdf}
\caption{Memory requirement of different implementation of Lift-Splat-Shoot view transformation. When the number of depth classes is set as $D=59$, the implementation of branch dev2.0, dubbed BEVPoolv2 need just 5.7\% memory requirement of the previous fastest implementation in a low input resolution of $256\times704$ and 2.0\% in a high resolution of $640\times1760$. }
\label{fig:memoryresolution}
\end{figure*}
\subsection{TensorRT}
We support the conversion of the BEVDet paradigm from PyTorch to TensorRT in our codebase. We list the inference latency of some configurations in Tab.~\ref{tab:trt} for reference. With the TensorRT-FP16 backend, BEVDet-R50 \cite{BEVDet} configuration with $256\times704$ input resolution can be processed at 138.9 FPS on an NVIDIA GeForce RTX 3090 GPU.
\begin{table}[h]
\centering
\caption{Inference speed of different backends with BEVDet-R50 \cite{BEVDet} configuration on an NVIDIA GeForce RTX 3090 GPU. We omit the postprocessing, which runs about 14.3 ms with the PyTorch backend.}
\resizebox{1.0\linewidth}{!}{
\begin{tabular}{c|ccccccccccccccc}
\hline
\hline
Backend & $256\times704$ & $384\times1056$ & $512\times1408$ & $640\times1760$ \\
\hline
PyTorch & 37.9 & 64.7 & 105.7 & 154.2 \\
TensorRT & 18.4 & 25.9 & 40.0 & 58.3 \\
TensorRT-FP16 & 7.2 & 10.6 & 15.3 & 21.2 \\
\hline
\end{tabular}%
}
\label{tab:trt}%
\end{table}%
\subsection{Receptive Field}
In the previous version of BEVDet \cite{BEVDet}, we inherit the receptive field from CenterPoint \cite{CenterPoint3D} without modification. The receptive field in CenterPoint takes the origin of the Lidar coordinate system as the center. However, it is inconsistent with the receptive field in evaluation, which takes the ego (IMU) coordinate system as the center. The inconsistency will lead to performance degeneration. We follow BEVDepth \cite{BEVDepth} to set the origin of the ego coordinate system as the center of the receptive field.
\subsection{Other Modifications}
\paragraph{BEVDepth} We support all techniques in BEVDepth \cite{BEVDepth} including the depth supervision from Lidar, depth correction, and camera-aware depth prediction.
\paragraph{Temporal Fusion} We introduce the long-term fusion in SOLOFusion \cite{SOLOFusion} to upgrade the temporal fusion paradigm in BEVDet4D \cite{BEVDet4D}.
\paragraph{Stereo Depth Estimation} So far, we haven't integrated any technique for stereo depth prediction like BEVStereo \cite{BEVStereo}, STS \cite{STS}, or SOLOFusion \cite{SOLOFusion}. We consider that they trade too much inference time for small accuracy improvement when compared with other factors like increasing the input resolution or increasing the backbone size. Besides, all the paradigms relied on cost volume are too complicated to be deployed to other platforms. More effort is needed in this promising direction.
\subsection{BEVDet4D-R50-Depth-CBGS}
We construct the BEVDet4D-R50-Depth-CBGS configuration as an example, which integrates all the aforementioned features. It scores 52.3 NDS and can be processed at 16.4 FPS with the PyTorch backend on an NVIDIA GeForce RTX 3090 GPU.
{\small
\bibliographystyle{ieee_fullname}
| {'timestamp': '2022-12-01T02:18:11', 'yymm': '2211', 'arxiv_id': '2211.17111', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17111'} | arxiv |
\section{Introduction}
Coarse-grained reconfigurable arrays (CGRAs) have been studied heavily in recent years as a promising configurable accelerator architecture~\cite{adres, dyser, plasticine, artem}. The end of Moore's law necessitates the creation of specialized hardware accelerators to enable running increasingly complex image processing and machine learning applications. While a variety of hardware accelerator architectures exist, CGRAs have emerged as an interesting midpoint between the flexibility of an FPGA and the performance of an application-specific accelerator. A CGRA can achieve high energy efficiency and performance due to word-level arithmetic operations and interconnect, while maintaining enough flexibility to run a variety of applications that evolve over time \cite{ambervlsi}.
\begin{figure}
\centering
\includegraphics[width=0.33\textwidth]{figs/cgra_diagram.pdf}
\caption{Architecture of a CGRA with PE tiles, memory tiles, connection boxes, and switch boxes.}
\label{fig:cgra-diagram}
\end{figure}
CGRAs, as well as other spatial accelerator architectures, often have hundreds of compute cores and memory cores. These compute cores (called processing elements or PEs) and memory (MEM) cores are laid out spatially in a grid of tiles and are connected through a configurable interconnect. An example is shown in Fig.~\ref{fig:cgra-diagram}. The reconfigurable interconnect contains switch boxes (SBs), which connect the PE/MEM outputs to the tracks in the interconnect, and connection boxes (CBs), which connect the interconnect tracks to the inputs of the cores. While having a large number of compute cores enables very high performance, the reconfigurable interconnect connecting these cores can constitute over 50\% of the CGRA area and 25\% of the CGRA energy \cite{artem}. Design space exploration of the interconnect is necessary to achieve high performance with lower energy and area costs.
There are many interconnect design choices that directly impact the power, performance, and area of the resulting accelerator, including the number and bitwidth of tracks in the interconnect, how the processing elements and memories are arranged in the array, how those elements are connected, and how the interconnect is configured. An agile approach for specifying and generating the interconnect is needed for efficient design space exploration.
In this paper, we present Canal, a Python-embedded domain-specific language (eDSL) and compiler for specifying and generating reconfigurable interconnects for CGRAs using a graph-based intermediate representation. The major contributions of our paper are:
\begin{enumerate}
\item We describe a graph-based intermediate representation (IR) for CGRA interconnects that is capable of representing and generating a variety of topologies.
\item We propose an embedded domain-specific language (eDSL) called Canal that can compile an interconnect architecture specification into the graph-based IR.
\item We propose an interconnect generator system that can take the IR and automatically produce hardware, place and route collateral, and a bitstream generator.
\item We explore various design space choices using Canal and demonstrate its effectiveness in generating an efficient CGRA design.
\end{enumerate}
\section{Related Work}
Previous attempts have been made to create an interconnect generator for CGRAs, but new demands in CGRA design necessitate a more flexible and powerful system. VPR is one of the most established FPGA architecture research tools~\cite{vpr}. It allows users to adjust various design aspects of the FPGA and observe the effects on final application performance, such as timing and area usage. However, VPR does not offer an RTL generator and users have to design their FPGA independently and hand-write the VPR architecture file accordingly.
CGRA-ME~\cite{cgra-me} is a CGRA architecture research tool similar to Canal in that it also offers integrated RTL generation and place and route tools. One of the major differences is the architecture specification. CGRA-ME opts for a more rigid XML-based input whereas Canal takes in a Python eDSL program, which is more flexible and readable.
FastCGRA~\cite{fastcgra} is a similar CGRA architecture exploration tool that uses an eDSL to construct the hardware. However, with FastCGRA, users explicitly construct multiplexers and switches, from which RTL is generated. Canal abstracts away the notion of hardware primitives and lets the compiler backend choose how to generate the hardware. In summary, Canal supports more tools, allows for more flexibility, and enables easier design space exploration than previous attempts at an interconnect generator.
\section{System Design}
In this section, we introduce the design of the Canal system, including the graph-based IR for representing interconnects, the Canal eDSL, the static interconnect generation used to translate the IR into hardware, and finally how that IR interfaces with the application place and route (PnR) algorithms. Fig.~\ref{fig:system-diagram} summarizes how the Canal interconnect generator interfaces with the PE and memory core designs, application PnR, RTL generation, and bitstream generation.
\begin{figure}
\centering
\includegraphics[width=0.48\textwidth]{figs/system_diagram.pdf}
\caption{The Canal interconnect generator system. It takes an interconnect specification written as a program in the Canal eDSL and produces the interconnect RTL implementation. Canal also takes an application and places and routes it on a CGRA with the specified interconnect and generates a configuration bitstream.}
\label{fig:system-diagram}
\vspace{-1em}
\end{figure}
\subsection{Graph-Based Intermediate Representation}
The primitives in Canal's intermediate representation (IR) are nodes, which represent anything that can be connected in the underlying hardware, and edges, which are wires connecting the nodes together. An example of the IR for a switch box is shown in Fig.~\ref{fig:graph-representation}.
All edges are unidirectional so the IR represents a directed graph. Nodes in the graph can have multiple incoming edges which, when translated into hardware, transform into multiplexers. Each node also has attributes that provide additional information for type checking and hardware generation.
This intermediate representation is flexible enough to represent a wide variety of interconnect topologies and handle an arbitrarily complex set of CGRA cores. We will discuss a few design space exploration experiments that exploit this flexibility in Section~\ref{sec:results}.
\begin{figure}
\centering
\captionsetup{justification=centering}
\begin{subfigure}[b]{.2\textwidth}
\centering
\includegraphics[width=0.8\textwidth]{figs/switchbox.pdf}
\caption{Hardware representation of a PE with four SBs}
\end{subfigure}
\hfill
\begin{subfigure}[b]{.2\textwidth}
\centering
\includegraphics[width=0.8\textwidth]{figs/graph_sb.pdf}
\caption{Digraph representation of a PE with four SBs}
\end{subfigure}
\captionsetup{justification=justified}
\caption{Hardware and directed graph based intermediate representation of the configurable interconnect. Not all connections between the PE and SBs are shown for simplicity.}
\label{fig:graph-representation}
\vspace{-0.5em}
\end{figure}
\subsection{The Canal Language}
\begin{figure}[t]
\centering
\begin{minted}{python}
node = Node(x=1, y=1, side="south", track=1)
for port_node in tile.pe.inputs():
node.add_edge(port_node)
create_uniform_interconnect(width=32,
height=32, sb_type="wilton", num_tracks=5,
track_width=16, reg_density=1)
\end{minted}
\vspace{-1em}
\caption{Example Canal low level node creation and high level interconnection creation. Canal includes many useful high level interconnect construction functions to enable the creation of common interconnects.}
\label{fig:canal_example}
\vspace{-1em}
\end{figure}
The Canal language is a Python-embedded domain-specific language (eDSL) that constructs the interconnect intermediate representation described in the previous section. The Canal language translates the Python description of an interconnect into this IR, so at the lowest level, a designer could instantiate nodes in the Canal language and wire them together.
As Canal is embedded in Python, we have also built a layer on top of the basic primitives of Canal, which simplifies the IR construction. For instance, for creating a uniform interconnect (all switch boxes have the same topology) with no diagonal connections, we provide a simple helper function that produces different interconnect topologies by varying function parameters such as height and width of the array, switch box topology, number of tracks, bit width of tracks, and density of pipeline registers. An example of creating a low level Canal node and using a higher level Canal helper function is shown in Fig.~\ref{fig:canal_example}.
The Canal eDSL allows designers to easily conduct design space exploration by varying the parameters in the helper functions, or by generating an entirely new interconnect. Canal can easily be integrated with other DSLs. For example, one could use a DSL for specifying individual CGRA tiles and then integrate them together using Canal to generate the interconnect.
\subsection{Generating Interconnect Hardware}
\label{sec:compile-hardware}
Because Canal's IR only describes the connectivity among the different nodes, it is up to the hardware compiler backend to decide how to lower the IR. We implemented two different hardware compiler backends that lower the IR into \begin{enumerate*}[label=(\arabic*)] \item a static mesh interconnect and \item a statically configured network-on-chip (NoC) \end{enumerate*}. This NoC has data channels along with a ready-valid interface and routing is configured statically before the application runs. We use magma~\cite{magma} as our hardware circuit implementation, but this could be extended to any hardware generator framework.
To generate a static mesh interconnect, we adopt the following principles to generate hardware:
\begin{enumerate}
\item Nodes with hardware attributes (e.g. a processing element core) generate the specified hardware.
\item Directed edges are translated into wires.
\item Nodes with multiple incoming edges generate multiplexers.
\end{enumerate}
\begin{figure}
\centering
\includegraphics[width=0.43\textwidth]{figs/ready_join.pdf}
\caption{Joining logic for the ready signals on the configurable interconnect. In this example, the data signal coming in from the east is being routed to both the north and west. The ready signals corresponding to the data signals flow in the opposite direction through the same switch boxes. The two ready signals need to be joined together to form the final ready signal, and we can reuse the one-hot switch box mux select signals to compute this.}
\label{fig:ready-valid-join}
\vspace{-1em}
\end{figure}
\begin{figure}
\centering
\includegraphics[width=0.25\textwidth]{figs/split-fifo.pdf}
\caption{Split FIFO optimization where two registers in adjacent switch boxes can function as a FIFO.}
\label{fig:split-fifo}
\vspace{-1em}
\end{figure}
We also use attributes associated with each node to lower the node to different hardware components. For instance, a register node will be lowered into a physical register. A port node will be lowered to a CB (with an internal multiplexer) where the output of the CB connects to the port of the core. These translations are mechanical and can be accomplished through a compiler pass.
Reusing the same IR to generate a statically configured NoC has several challenges.
First, the application graph may have fanouts, that is, one output port of a node is connected to multiple input ports. While this is simple to handle in a static interconnect, we now need an area-efficient way to handle control signals.
Since valid signals flow in the same direction as the data, generating hardware for valid channels follows the same strategy as that used for the data channels. However, since ready signals flow in a direction opposite to that of the data channels, we need a way to merge ready signals at the fan-in point. A naive solution is to implement a lookup table (LUT) that encodes the fan-in information, as shown in Fig.~\ref{fig:ready-valid-join}. During configuration, we statically encode the ready signal joining logic into the LUT. However, building a LUT for each multiplexer is expensive and it also bloats the configuration space. To optimize this logic, we leverage the fact that the data multiplexers in the switch box are AOI multiplexers, which internally use a decoder to convert the mux selection bits into a one-hot vector, which represents the active routing information. The ready signal joining logic needs this routing information to properly join multiple ready signals. We can reuse these one-hot decoder signals to compute the joining logic without introducing expensive LUT based solutions, as shown at the bottom of Fig.~\ref{fig:ready-valid-join}. In this figure, the one-hot selection signals are $n\_sel\_oh$, $w\_sel\_oh$, and $s\_sel\_oh$. We know that if bit 2 of $n\_sel\_oh$ is high, than the $data\_in$ is routed to the north. We OR the inversion of $n\_sel\_oh[2]$ with the $n\_ready$ signal, giving us a signal that is high when $n\_ready$ is high or when that route is not used. We can repeat this logic for the remaining two directions and AND them all together to form the final $ready$ output.
Another challenge when generating a statically configured NoC is that a ready-valid NoC needs FIFOs present in the interconnect to buffer data when a downstream tile is not yet ready. While we can easily generate a fixed-size FIFO for a register IR node, the area cost of those FIFOs can be quite high, as shown in Fig~\ref{fig:sb-fifo-area}. Therefore, we also need a way to reduce FIFO size.
To reduce the area overhead introduced by FIFOs while maintaining backward compatibility with a static interconnect, we realize that we can combine two registers from adjacent tiles into a single size-two FIFO. We call this a split FIFO. The first register's FIFO control signals are passed from the first tile into the second tile and its register, as shown in Figure~\ref{fig:split-fifo}.
We can also chain more registers together into a deeper FIFO using the same logic. Since each register's FIFO logic is slightly different depending on its location inside the FIFO pipeline, we need to configure them differently during place and route. The drawback, however, is that these control signals cannot be registered at the tile boundary; the longer the FIFO is chained, the longer the combinational delay on the path. However, if most of the target applications do not require a deep FIFO between different nodes, using this scheme can significantly reduce the silicon area. The area impact of this optimization is evaluated in Fig.~\ref{fig:sb-fifo-area}.
\begin{figure}
\centering
\captionsetup{justification=centering}
\begin{subfigure}[b]{.22\textwidth}
\includegraphics[width=1\textwidth]{figs/sb_no_timing.pdf}
\caption{Digraph representation with no edge weights}
\end{subfigure}%
\begin{subfigure}[b]{.26\textwidth}
\includegraphics[width=0.8\textwidth]{figs/sb_timing.pdf}
\caption{Digraph representation with timing information as weights}
\end{subfigure}
\captionsetup{justification=justified}
\caption{The edge weights of the directed graph representation of the interconnect allow the PnR algorithm to be run on the graph directly.}
\label{fig:pnr}
\vspace{-2em}
\end{figure}
After the graph is translated into RTL, Canal verifies structural correctness by comparing the connectivity of the hardware with that of the IR by parsing the generated RTL. In addition, Canal also has a built in configuration sweep test suite that exhaustively tests every possible connection in IR on the CGRA. This ensures correctness of the design.
The methodology described here also applies to generating dynamic NoCs. Instead of lowering a node into a configurable multiplexer to select among incoming data tracks, we can generate a router whose routing table is computed based on the same connectivity information.
\subsection{Place and Route using Canal Interconnect}
This section describes how the Canal system integrates with a PnR algorithm backend (see Fig.~\ref{fig:system-diagram}) to enable running applications on a given interconnect. During the translation from a Canal program into the directed graph representation, information regarding important hardware characteristics, like core or wire delays, can be embedded into the graph as shown in Fig.~\ref{fig:pnr}. The Canal system then executes PnR in three stages: packing, placement, and routing. The remainder of this section describes the PnR backend we use in our results.
During the packing stage, both the interconnect graph and the application graph (represented as a dataflow graph) are loaded into the PnR tool. Constants and registers in the application are analyzed to identify any packing opportunities. For example, a pipeline register that feeds directly into a PE can be packed within that PE, eliminating the need to place that register on the configurable interconnect.
After packing, the placement tool places the tiles in the application onto the interconnect in two stages: global placement and detailed placement.
Global placement uses an analytical algorithm that leverages the standard conjugate gradient method on the summation of the cost of each net (Equation~\ref{eqn:globalplacement-function})~\cite{kahng2005aplace}. The cost of a net is the combination of its half-perimeter wire length (HPWL) and a legalization term for memory tiles. In global placement, we use L2 distance to approximate the HPWL to speed up the algorithm. CGRAs typically have fewer rows or columns of memory tiles (compared to PE tiles), so the legalization term is needed to ensure that memory tiles are only placed in those rows/columns.
\vspace{-0.2em}
\begin{equation}
\label{eqn:globalplacement-function}
\text{Cost}_{net} = \text{HPWL}_{net, estimate} + \text{MEM}_{potential}
\end{equation}
After global placement, we perform detailed placement based on simulated annealing~\cite{van1987simulated}. The cost function for simulated annealing (see Equation~\ref{eqn:detailedplacement-function}) is the total wirelength of the application, calculated by summing the HPWL cost for each net, and an additional term for penalizing pass-through tiles. Pass-through tiles are those that are only used for routing, which need to be powered on despite not computing anything for the application. $\gamma$ and $\alpha$ are hyperparameters. Some CGRAs have tile-level power gating that enables the ability to turn off tiles that are used for neither the application's computation nor as pass-through tiles. A higher value of $\gamma$ penalizes pass-through tiles more, which encourages the placement algorithm to use already-used tiles for routing, rather than powering on otherwise unused tiles. A higher value for $\alpha$ will penalize longer potential routes, thereby encouraging shorter critical paths after routing. We find that sweeping $\alpha$ from 1 to 20 and choosing the best result post-routing results in short application critical paths.
\vspace{-0.2em}
\begin{equation}
\label{eqn:detailedplacement-function}
\text{Cost}_{net} = (\text{HPWL}_{net} - \gamma \times (\text{Area}_{net} \cap \text{Area}_{existing}))^\alpha
\end{equation}
After global and detailed placement, we route using an iteration-based routing algorithm~\cite{swartz1998fast}. During each iteration, we compute the slack on a net and determine how critical it is given global timing information. Then we route using the A* algorithm on the weighted graph. The weights for each edge are based on historical usage, net slack, and current congestion. This allows us to balance both routing congestion and timing criticality. Similarly to detailed placement, we also adjust the wire cost functions to discourage the use of unused tiles in favor of tracks within already-used tiles. We finish routing when a legal routing result is produced.
\section{Evaluation}
\label{sec:results}
We evaluate the Canal system by first exploring the optimizations of interconnect FIFOs described in Section~\ref{sec:compile-hardware} and then by using the Canal system to conduct design space exploration of a CGRA interconnect.
\subsection{Interconnect FIFO Optimizations}
\label{sec:results-fifo}
We evaluate the effect of introducing FIFOs in the interconnect on switch box area. As described in Section~\ref{sec:compile-hardware}, we need to include FIFOs in the configurable routing when running applications with ready-valid signaling.
As a baseline, we compare against a fully static interconnect with five 16-bit routing tracks containing PEs with two outputs and four inputs, synthesized in Global Foundries 12 nm technology.
As shown in Fig.~\ref{fig:sb-fifo-area}, adding these depth two FIFOs to the baseline design introduces a 54\% area overhead. Splitting the FIFO between multiple switch boxes results in only a 32\% area overhead over the baseline. This optimization allows for much more efficient implementation of an interconnect that supports ready-valid signaling.
\subsection{Interconnect Design Space Exploration}
We use Canal to explore three important design space axes of a configurable interconnect: switch box topology, number of routing tracks, and number of switch box and connection box port connections.
We find that Canal's automation greatly simplifies the procedure to explore each option in the following subsections.
\begin{figure}
\centering
\includegraphics[width=0.23\textwidth]{figs/sb_tracks_area.pdf}
\includegraphics[width=0.23\textwidth]{figs/cb_tracks_area.pdf}
\vspace{-1em}
\caption{Left: Area of a switch box as the number of tracks increases. Right: Area of a connection box as the number of tracks increases.}
\label{fig:sb-topo-tracks-area}
\vspace{-1em}
\end{figure}
\subsubsection{Exploring Switch Box Topologies and Number of Routing Tracks}
The switch box topology defines how each track on each side of the switch box connects to the tracks on the remaining sides of the switch box. The choice of topology affects how easily nets can be routed on the interconnect. High routability generally corresponds to shorter routes and shorter critical paths in applications. This allows the CGRA to be run at higher frequencies, which decreases application run time. For these experiments we investigate two different switch box topologies illustrated in Fig.~\ref{fig:sb-topos}: Wilton~\cite{wilton} and Disjoint~\cite{disjoint}. These switch box topologies have the same area, as they both connect each input to each of the other sides once.
\begin{figure}
\centering
\vspace{-1em}
\includegraphics[width=0.45\textwidth]{figs/tracks_runtime.pdf}
\vspace{-1em}
\caption{Application run time comparison on CGRAs with switch boxes that have different number of tracks.}
\label{fig:sb-topo-tracks-runtime}
\vspace{-1em}
\end{figure}
We found that the Wilton topology performs much better than the Disjoint topology, which failed to route in all of our test cases. The Disjoint topology is worse for routability because every incoming connection on track $i$ has a connection only to track $i$ on the three other sides of the SB. This imposes a restriction that if you want to route a wire from any point on the array to any other point on the array starting from a certain track number, you must only use that track number. In comparison, the Wilton topology does not have this restriction resulting in many more choices for the routing algorithm, and therefore much higher routability~\cite{imran}.
We also vary the number of routing tracks in the interconnect. This directly affects the size of both the connection box and switch box and the amount of routing congestion. For these experiments we measure the area of the connection box and switch box as well as the run time of applications running on the CGRA.
In this experiment we use an interconnect with five 16-bit tracks and PE tiles that have 4 inputs and 2 outputs. As shown in Fig.~\ref{fig:sb-topo-tracks-area}, the area of both the switch box and connection box scale with the number of tracks. From Fig.~\ref{fig:sb-topo-tracks-runtime}, we can see that the run time of the applications generally decreases as the number of tracks increases, although the benefits are less than 25\%.
\subsubsection{Exploring Switch Box and Connection Box Port Connections}
Finally, we explore how varying the number of switch box and connection box port connections affects the area of the interconnect and the run time of applications executing on the CGRA. In Canal, we have the ability to specify how many of the incoming tracks from each side of the tile are connected to the inputs/outputs of the PE/MEM cores. Decreasing these connections should reduce the area of the interconnect, but may decrease the number of options that the routing algorithm has. For these experiments, we vary the number of connections from the incoming routing tracks through the connection box to the inputs of the PE/MEM core, and vary the number of connections from the outputs of the core to the outgoing ports of the switch box. At maximum, we can have 4 SB sides, with connections from the core output to the four sides of the switch box. We then decrease this by removing the connections facing east for a total of three sides with connections, and finally we also remove the connections facing south for a total of two sides with connections. This is shown in Fig.~\ref{fig:sb-conns}. We do the same for the connection box.
\begin{figure}
\centering
\vspace{-0.5em}
\includegraphics[width=0.35\textwidth]{figs/sb_conns.pdf}
\vspace{-0.5em}
\caption{Reducing the number of connections from the outputs of the PE to the outgoing ports of the switch box.}
\label{fig:sb-conns}
\vspace{-1em}
\end{figure}
\begin{figure}
\centering
\vspace{-0.2em}
\captionsetup{justification=centering}
\begin{subfigure}[b]{.22\textwidth}
\includegraphics[width=1\textwidth]{figs/port_conns_sb_area.pdf}
\end{subfigure} \hspace{1em}
\begin{subfigure}[b]{.22\textwidth}
\includegraphics[width=0.97\textwidth]{figs/port_conns_cb_area.pdf}
\end{subfigure}
\vspace{-1em}
\captionsetup{justification=justified}
\caption{Area comparison of a switch box and a connection box that have varying number of connections with the four sides of the tile.}
\label{fig:port-conn-area}
\vspace{-1em}
\end{figure}
As shown in Fig.~\ref{fig:port-conn-area}, as the number of connections from the core to the switch box decreases, we see a decrease in switch box area. From Fig.~\ref{fig:port-conn-sb-runtime}, we can see that this generally has a small negative effect on the run time of the applications. In this case, a designer could choose to trade some performance for a decrease in switch box area.
As shown in Fig.~\ref{fig:port-conn-area}, as the number of connections from the connection box to the tile inputs decreases, we see a larger decrease in connection box area. From Fig.~\ref{fig:port-conn-cb-runtime}, we can see that this has a larger negative effect on the run time of the applications. Again, a designer could choose to trade some performance for a decrease in connection box area.
\section{Conclusion}
We have developed Canal, a domain-specific language and interconnect generator for coarse-grained reconfigurable arrays. The Canal language allows a designer to easily specify a complex configurable interconnect, while maintaining control over the low-level connections. The hardware generator, placer and router, and bitstream generator help to facilitate design space exploration of CGRA interconnects. We demonstrate the flexibility of Canal by creating a hybrid ready-valid interconnect and demonstrate the design space exploration capabilities of Canal by evaluating different switch box topologies, number of interconnect routing tracks, and number of SB and CB port connections. The power and flexibility that Canal provides will enable more designers to create and explore diverse and interesting CGRA architectures.
\begin{figure}
\centering
\vspace{-1em}
\includegraphics[width=0.4\textwidth]{figs/port_conns_sb_runtime.pdf}
\vspace{-1em}
\caption{Run time comparison of a switch box that has varying number of connections from the four sides of the tile.}
\label{fig:port-conn-sb-runtime}
\vspace{-0.5em}
\end{figure}
\begin{figure}
\centering
\vspace{-0.7em}
\includegraphics[width=0.4\textwidth]{figs/port_conns_cb_runtime.pdf}
\vspace{-1em}
\caption{Run time comparison of a connection box that has varying number of connections from the four sides of the tile.}
\label{fig:port-conn-cb-runtime}
\vspace{-1.5em}
\end{figure}
\section{Introduction}
\vspace{-0.4cm}
Coarse-grained reconfigurable arrays (CGRAs) have been studied heavily in recent years as a promising configurable accelerator architecture~\cite{adres, dyser, plasticine, artem}. The end of Moore's law necessitates the creation of specialized hardware accelerators to enable running increasingly complex image processing and machine learning applications. While a variety of hardware accelerator architectures exist, CGRAs have emerged as an interesting midpoint between the flexibility of an FPGA and the performance of an application-specific accelerator. A CGRA can achieve high energy efficiency and performance due to word-level arithmetic operations and interconnect, while maintaining enough flexibility to run a variety of applications that evolve over time \cite{ambervlsi}.
\begin{figure}
\centering
\includegraphics[width=0.33\textwidth]{figs/cgra_diagram.pdf}
\caption{Architecture of a CGRA with PE tiles, memory tiles, connection boxes, and switch boxes.}
\label{fig:cgra-diagram}
\end{figure}
CGRAs, as well as other spatial accelerator architectures, often have hundreds of compute cores and memory cores. These compute cores (called processing elements or PEs) and memory (MEM) cores are laid out spatially in a grid of tiles and are connected through a configurable interconnect. An example is shown in Fig.~\ref{fig:cgra-diagram}. The reconfigurable interconnect contains switch boxes (SBs), which connect the PE/MEM outputs to the tracks in the interconnect, and connection boxes (CBs), which connect the interconnect tracks to the inputs of the cores. While having a large number of compute cores enables very high performance, the reconfigurable interconnect connecting these cores can constitute over 50\% of the CGRA area and 25\% of the CGRA energy \cite{artem}. Design space exploration of the interconnect is necessary to achieve high performance with lower energy and area costs.
There are many interconnect design choices that directly impact the power, performance, and area of the resulting accelerator, including the number and bitwidth of tracks in the interconnect, how the processing elements and memories are arranged in the array, how those elements are connected, and how the interconnect is configured. An agile approach for specifying and generating the interconnect is needed for efficient design space exploration.
In this paper, we present Canal, a Python-embedded domain-specific language (eDSL) and compiler for specifying and generating reconfigurable interconnects for CGRAs using a graph-based intermediate representation. The major contributions of our paper are:
\begin{enumerate}
\item We describe a graph-based intermediate representation (IR) for CGRA interconnects that is capable of representing and generating a variety of topologies.
\item We propose an embedded domain-specific language (eDSL) called Canal that can compile an interconnect architecture specification into the graph-based IR.
\item We propose an interconnect generator system that can take the IR and automatically produce hardware, place and route collateral, and a bitstream generator.
\item We explore various design space choices using Canal and demonstrate its effectiveness in generating an efficient CGRA design.
\end{enumerate}
\section{Related Work}
\vspace{-0.4cm}
Previous attempts have been made to create an interconnect generator for CGRAs, but new demands in CGRA design necessitate a more flexible and powerful system. VPR is one of the most established FPGA architecture research tools~\cite{vpr}. It allows users to adjust various design aspects of the FPGA and observe the effects on final application performance, such as timing and area usage. However, VPR does not offer an RTL generator and users have to design their FPGA independently and hand-write the VPR architecture file accordingly.
CGRA-ME~\cite{cgra-me} is a CGRA architecture research tool similar to Canal in that it also offers integrated RTL generation and place and route tools. One of the major differences is the architecture specification. CGRA-ME opts for a more rigid XML-based input whereas Canal takes in a Python eDSL program, which is more flexible and readable.
FastCGRA~\cite{fastcgra} is a similar CGRA architecture exploration tool that uses an eDSL to construct the hardware. However, with FastCGRA, users explicitly construct multiplexers and switches, from which RTL is generated. Canal abstracts away the notion of hardware primitives and lets the compiler backend choose how to generate the hardware. In summary, Canal supports more tools, allows for more flexibility, and enables easier design space exploration than previous attempts at an interconnect generator.
\section{System Design}
\vspace{-0.4cm}
In this section, we introduce the design of the Canal system, including the graph-based IR for representing interconnects, the Canal eDSL, the static interconnect generation used to translate the IR into hardware, and finally how that IR interfaces with the application place and route (PnR) algorithms. Fig.~\ref{fig:system-diagram} summarizes how the Canal interconnect generator interfaces with the PE and memory core designs, application PnR, RTL generation, and bitstream generation.
\begin{figure}
\centering
\includegraphics[width=0.48\textwidth]{figs/system_diagram.pdf}
\caption{The Canal interconnect generator system. It takes an interconnect specification written as a program in the Canal eDSL and produces the interconnect RTL implementation. Canal also takes an application and places and routes it on a CGRA with the specified interconnect and generates a configuration bitstream.}
\label{fig:system-diagram}
\vspace{-1.4em}
\end{figure}
\subsection{Graph-Based Intermediate Representation}
\vspace{-0.4cm}
The primitives in Canal's intermediate representation (IR) are nodes, which represent anything that can be connected in the underlying hardware, and edges, which are wires connecting the nodes together. An example of the IR for a switch box is shown in Fig.~\ref{fig:graph-representation}.
All edges are unidirectional so the IR represents a directed graph. Nodes in the graph can have multiple incoming edges which, when translated into hardware, transform into multiplexers. Each node also has attributes that provide additional information for type checking and hardware generation.
This intermediate representation is flexible enough to represent a wide variety of interconnect topologies and handle an arbitrarily complex set of CGRA cores. We will discuss a few design space exploration experiments that exploit this flexibility in Section~\ref{sec:results}.
\begin{figure}
\centering
\captionsetup{justification=centering}
\begin{subfigure}[b]{.2\textwidth}
\centering
\includegraphics[width=0.8\textwidth]{figs/switchbox.pdf}
\caption{Hardware representation of a PE with four SBs}
\end{subfigure}
\hfill
\begin{subfigure}[b]{.2\textwidth}
\centering
\includegraphics[width=0.8\textwidth]{figs/graph_sb.pdf}
\caption{Digraph representation of a PE with four SBs}
\end{subfigure}
\captionsetup{justification=justified}
\caption{Hardware and directed graph based intermediate representation of the configurable interconnect. Not all connections between the PE and SBs are shown for simplicity.}
\label{fig:graph-representation}
\vspace{-0.5em}
\end{figure}
\subsection{The Canal Language}
\vspace{-0.4cm}
\begin{figure}[t]
\centering
\begin{minted}{python}
node = Node(x=1, y=1, side="south", track=1)
for port_node in tile.pe.inputs():
node.add_edge(port_node)
create_uniform_interconnect(width=32,
height=32, sb_type="wilton", num_tracks=5,
track_width=16, reg_density=1)
\end{minted}
\vspace{-1em}
\caption{Example Canal low level node creation and high level interconnection creation. Canal includes many useful high level interconnect construction functions to enable the creation of common interconnects.}
\label{fig:canal_example}
\vspace{-1.3em}
\end{figure}
The Canal language is a Python-embedded domain-specific language (eDSL) that constructs the interconnect intermediate representation described in the previous section. The Canal language translates the Python description of an interconnect into this IR, so at the lowest level, a designer could instantiate nodes in the Canal language and wire them together.
As Canal is embedded in Python, we have also built a layer on top of the basic primitives of Canal, which simplifies the IR construction. For instance, for creating a uniform interconnect (all switch boxes have the same topology) with no diagonal connections, we provide a simple helper function that produces different interconnect topologies by varying function parameters such as height and width of the array, switch box topology, number of tracks, bit width of tracks, and density of pipeline registers. An example of creating a low level Canal node and using a higher level Canal helper function is shown in Fig.~\ref{fig:canal_example}.
The Canal eDSL allows designers to easily conduct design space exploration by varying the parameters in the helper functions, or by generating an entirely new interconnect. Canal can easily be integrated with other DSLs. For example, one could use a DSL for specifying individual CGRA tiles and then integrate them together using Canal to generate the interconnect.
\subsection{Generating Interconnect Hardware}
\label{sec:compile-hardware}
\vspace{-0.4cm}
Because Canal's IR only describes the connectivity among the different nodes, it is up to the hardware compiler backend to decide how to lower the IR. We implemented two different hardware compiler backends that lower the IR into \begin{enumerate*}[label=(\arabic*)] \item a static mesh interconnect and \item a statically configured network-on-chip (NoC) \end{enumerate*}. This NoC has data channels along with a ready-valid interface and routing is configured statically before the application runs. We use magma~\cite{magma} as our hardware circuit implementation, but this could be extended to any hardware generator framework.
To generate a static mesh interconnect, we adopt the following principles to generate hardware:
\begin{enumerate}
\item Nodes with hardware attributes (e.g. a processing element core) generate the specified hardware.
\item Directed edges are translated into wires.
\item Nodes with multiple incoming edges generate multiplexers.
\end{enumerate}
\begin{figure}
\centering
\includegraphics[width=0.43\textwidth]{figs/ready_join.pdf}
\caption{Joining logic for the ready signals on the configurable interconnect. In this example, the data signal coming in from the east is being routed to both the north and west. The ready signals corresponding to the data signals flow in the opposite direction through the same switch boxes. The two ready signals need to be joined together to form the final ready signal, and we can reuse the one-hot switch box mux select signals to compute this.}
\label{fig:ready-valid-join}
\vspace{-1em}
\end{figure}
\begin{figure}
\centering
\includegraphics[width=0.25\textwidth]{figs/split-fifo.pdf}
\caption{Split FIFO optimization where two registers in adjacent switch boxes can function as a FIFO.}
\label{fig:split-fifo}
\vspace{-2em}
\end{figure}
We also use attributes associated with each node to lower the node to different hardware components. For instance, a register node will be lowered into a physical register. A port node will be lowered to a CB (with an internal multiplexer) where the output of the CB connects to the port of the core. These translations are mechanical and can be accomplished through a compiler pass.
Reusing the same IR to generate a statically configured NoC has several challenges.
First, the application graph may have fanouts, that is, one output port of a node is connected to multiple input ports. While this is simple to handle in a static interconnect, we now need an area-efficient way to handle control signals.
Since valid signals flow in the same direction as the data, generating hardware for valid channels follows the same strategy as that used for the data channels. However, since ready signals flow in a direction opposite to that of the data channels, we need a way to merge ready signals at the fan-in point. A naive solution is to implement a lookup table (LUT) that encodes the fan-in information, as shown in Fig.~\ref{fig:ready-valid-join}. During configuration, we statically encode the ready signal joining logic into the LUT. However, building a LUT for each multiplexer is expensive and it also bloats the configuration space. To optimize this logic, we leverage the fact that the data multiplexers in the switch box are AOI multiplexers, which internally use a decoder to convert the mux selection bits into a one-hot vector, which represents the active routing information. The ready signal joining logic needs this routing information to properly join multiple ready signals. We can reuse these one-hot decoder signals to compute the joining logic without introducing expensive LUT based solutions, as shown at the bottom of Fig.~\ref{fig:ready-valid-join}. In this figure, the one-hot selection signals are $n\_sel\_oh$, $w\_sel\_oh$, and $s\_sel\_oh$. We know that if bit 2 of $n\_sel\_oh$ is high, than the $data\_in$ is routed to the north. We OR the inversion of $n\_sel\_oh[2]$ with the $n\_ready$ signal, giving us a signal that is high when $n\_ready$ is high or when that route is not used. We can repeat this logic for the remaining two directions and AND them all together to form the final $ready$ output.
Another challenge when generating a statically configured NoC is that a ready-valid NoC needs FIFOs present in the interconnect to buffer data when a downstream tile is not yet ready. While we can easily generate a fixed-size FIFO for a register IR node, the area cost of those FIFOs can be quite high, as shown in Fig~\ref{fig:sb-fifo-area}. Therefore, we also need a way to reduce FIFO size.
To reduce the area overhead introduced by FIFOs while maintaining backward compatibility with a static interconnect, we realize that we can combine two registers from adjacent tiles into a single size-two FIFO. We call this a split FIFO. The first register's FIFO control signals are passed from the first tile into the second tile and its register, as shown in Figure~\ref{fig:split-fifo}.
We can also chain more registers together into a deeper FIFO using the same logic. Since each register's FIFO logic is slightly different depending on its location inside the FIFO pipeline, we need to configure them differently during place and route. The drawback, however, is that these control signals cannot be registered at the tile boundary; the longer the FIFO is chained, the longer the combinational delay on the path. However, if most of the target applications do not require a deep FIFO between different nodes, using this scheme can significantly reduce the silicon area. The area impact of this optimization is evaluated in Fig.~\ref{fig:sb-fifo-area}.
\begin{figure}
\centering
\captionsetup{justification=centering}
\begin{subfigure}[b]{.22\textwidth}
\includegraphics[width=1\textwidth]{figs/sb_no_timing.pdf}
\caption{Digraph representation with no edge weights}
\end{subfigure}%
\begin{subfigure}[b]{.26\textwidth}
\includegraphics[width=0.8\textwidth]{figs/sb_timing.pdf}
\caption{Digraph representation with timing information as weights}
\end{subfigure}
\captionsetup{justification=justified}
\caption{The edge weights of the directed graph representation of the interconnect allow the PnR algorithm to be run on the graph directly.}
\label{fig:pnr}
\end{figure}
After the graph is translated into RTL, Canal verifies structural correctness by comparing the connectivity of the hardware with that of the IR by parsing the generated RTL. In addition, Canal also has a built in configuration sweep test suite that exhaustively tests every possible connection in IR on the CGRA. This ensures correctness of the design.
The methodology described here also applies to generating dynamic NoCs. Instead of lowering a node into a configurable multiplexer to select among incoming data tracks, we can generate a router whose routing table is computed based on the same connectivity information.
\subsection{Place and Route using Canal Interconnect}
\vspace{-0.4cm}
This section describes how the Canal system integrates with a PnR algorithm backend (see Fig.~\ref{fig:system-diagram}) to enable running applications on a given interconnect. During the translation from a Canal program into the directed graph representation, information regarding important hardware characteristics, like core or wire delays, can be embedded into the graph as shown in Fig.~\ref{fig:pnr}. The Canal system then executes PnR in three stages: packing, placement, and routing. The remainder of this section describes the PnR backend we use in our results.
During the packing stage, both the interconnect graph and the application graph (represented as a dataflow graph) are loaded into the PnR tool. Constants and registers in the application are analyzed to identify any packing opportunities. For example, a pipeline register that feeds directly into a PE can be packed within that PE, eliminating the need to place that register on the configurable interconnect.
After packing, the placement tool places the tiles in the application onto the interconnect in two stages: global placement and detailed placement.
Global placement uses an analytical algorithm that leverages the standard conjugate gradient method on the summation of the cost of each net (Equation~\ref{eqn:globalplacement-function})~\cite{kahng2005aplace}. The cost of a net is the combination of its half-perimeter wire length (HPWL) and a legalization term for memory tiles. In global placement, we use L2 distance to approximate the HPWL to speed up the algorithm. CGRAs typically have fewer rows or columns of memory tiles (compared to PE tiles), so the legalization term is needed to ensure that memory tiles are only placed in those rows/columns.
\vspace{-0.2em}
\begin{equation}
\label{eqn:globalplacement-function}
\text{Cost}_{net} = \text{HPWL}_{net, estimate} + \text{MEM}_{potential}
\end{equation}
After global placement, we perform detailed placement based on simulated annealing~\cite{van1987simulated}. The cost function for simulated annealing (see Equation~\ref{eqn:detailedplacement-function}) is the total wirelength of the application, calculated by summing the HPWL cost for each net, and an additional term for penalizing pass-through tiles. Pass-through tiles are those that are only used for routing, which need to be powered on despite not computing anything for the application. $\gamma$ and $\alpha$ are hyperparameters. Some CGRAs have tile-level power gating that enables the ability to turn off tiles that are used for neither the application's computation nor as pass-through tiles. A higher value of $\gamma$ penalizes pass-through tiles more, which encourages the placement algorithm to use already-used tiles for routing, rather than powering on otherwise unused tiles. A higher value for $\alpha$ will penalize longer potential routes, thereby encouraging shorter critical paths after routing. We find that sweeping $\alpha$ from 1 to 20 and choosing the best result post-routing results in short application critical paths.
\vspace{-0.2em}
\begin{equation}
\label{eqn:detailedplacement-function}
\text{Cost}_{net} = (\text{HPWL}_{net} - \gamma \times (\text{Area}_{net} \cap \text{Area}_{existing}))^\alpha
\end{equation}
After global and detailed placement, we route using an iteration-based routing algorithm~\cite{swartz1998fast}. During each iteration, we compute the slack on a net and determine how critical it is given global timing information. Then we route using the A* algorithm on the weighted graph. The weights for each edge are based on historical usage, net slack, and current congestion. This allows us to balance both routing congestion and timing criticality. Similarly to detailed placement, we also adjust the wire cost functions to discourage the use of unused tiles in favor of tracks within already-used tiles. We finish routing when a legal routing result is produced.
\section{Evaluation}
\label{sec:results}
\vspace{-0.4cm}
We evaluate the Canal system by first exploring the optimizations of interconnect FIFOs described in Section~\ref{sec:compile-hardware} and then by using the Canal system to conduct design space exploration of a CGRA interconnect.
\subsection{Interconnect FIFO Optimizations}
\label{sec:results-fifo}
\vspace{-0.4cm}
We evaluate the effect of introducing FIFOs in the interconnect on switch box area. As described in Section~\ref{sec:compile-hardware}, we need to include FIFOs in the configurable routing when running applications with ready-valid signaling.
As a baseline, we compare against a fully static interconnect with five 16-bit routing tracks containing PEs with two outputs and four inputs, synthesized in Global Foundries 12 nm technology.
As shown in Fig.~\ref{fig:sb-fifo-area}, adding these depth two FIFOs to the baseline design introduces a 54\% area overhead. Splitting the FIFO between multiple switch boxes results in only a 32\% area overhead over the baseline. This optimization allows for much more efficient implementation of an interconnect that supports ready-valid signaling.
\subsection{Interconnect Design Space Exploration}
\vspace{-0.4cm}
We use Canal to explore three important design space axes of a configurable interconnect: switch box topology, number of routing tracks, and number of switch box and connection box port connections.
We find that Canal's automation greatly simplifies the procedure to explore each option in the following subsections.
\begin{figure}
\centering
\includegraphics[width=0.23\textwidth]{figs/sb_tracks_area.pdf}
\includegraphics[width=0.23\textwidth]{figs/cb_tracks_area.pdf}
\vspace{-1em}
\caption{Left: Area of a switch box as the number of tracks increases. Right: Area of a connection box as the number of tracks increases.}
\label{fig:sb-topo-tracks-area}
\vspace{-1em}
\end{figure}
\subsubsection{Exploring Switch Box Topologies and Number of Routing Tracks}
\vspace{-0.4cm}
The switch box topology defines how each track on each side of the switch box connects to the tracks on the remaining sides of the switch box. The choice of topology affects how easily nets can be routed on the interconnect. High routability generally corresponds to shorter routes and shorter critical paths in applications. This allows the CGRA to be run at higher frequencies, which decreases application run time. For these experiments we investigate two different switch box topologies illustrated in Fig.~\ref{fig:sb-topos}: Wilton~\cite{wilton} and Disjoint~\cite{disjoint}. These switch box topologies have the same area, as they both connect each input to each of the other sides once.
\begin{figure}
\centering
\vspace{-1em}
\includegraphics[width=0.45\textwidth]{figs/tracks_runtime.pdf}
\vspace{-1em}
\caption{Application run time comparison on CGRAs with switch boxes that have different number of tracks.}
\label{fig:sb-topo-tracks-runtime}
\vspace{-1em}
\end{figure}
We found that the Wilton topology performs much better than the Disjoint topology, which failed to route in all of our test cases. The Disjoint topology is worse for routability because every incoming connection on track $i$ has a connection only to track $i$ on the three other sides of the SB. This imposes a restriction that if you want to route a wire from any point on the array to any other point on the array starting from a certain track number, you must only use that track number. In comparison, the Wilton topology does not have this restriction resulting in many more choices for the routing algorithm, and therefore much higher routability~\cite{imran}.
We also vary the number of routing tracks in the interconnect. This directly affects the size of both the connection box and switch box and the amount of routing congestion. For these experiments we measure the area of the connection box and switch box as well as the run time of applications running on the CGRA.
In this experiment we use an interconnect with five 16-bit tracks and PE tiles that have 4 inputs and 2 outputs. As shown in Fig.~\ref{fig:sb-topo-tracks-area}, the area of both the switch box and connection box scale with the number of tracks. From Fig.~\ref{fig:sb-topo-tracks-runtime}, we can see that the run time of the applications generally decreases as the number of tracks increases, although the benefits are less than 25\%.
\subsubsection{Exploring Switch Box and Connection Box Port Connections}
\vspace{-0.4cm}
Finally, we explore how varying the number of switch box and connection box port connections affects the area of the interconnect and the run time of applications executing on the CGRA. In Canal, we have the ability to specify how many of the incoming tracks from each side of the tile are connected to the inputs/outputs of the PE/MEM cores. Decreasing these connections should reduce the area of the interconnect, but may decrease the number of options that the routing algorithm has. For these experiments, we vary the number of connections from the incoming routing tracks through the connection box to the inputs of the PE/MEM core, and vary the number of connections from the outputs of the core to the outgoing ports of the switch box. At maximum, we can have 4 SB sides, with connections from the core output to the four sides of the switch box. We then decrease this by removing the connections facing east for a total of three sides with connections, and finally we also remove the connections facing south for a total of two sides with connections. This is shown in Fig.~\ref{fig:sb-conns}. We do the same for the connection box.
\begin{figure}
\centering
\vspace{-0.5em}
\includegraphics[width=0.35\textwidth]{figs/sb_conns.pdf}
\vspace{-0.5em}
\caption{Reducing the number of connections from the outputs of the PE to the outgoing ports of the switch box.}
\label{fig:sb-conns}
\vspace{-1em}
\end{figure}
\begin{figure}
\centering
\vspace{-0.2em}
\captionsetup{justification=centering}
\begin{subfigure}[b]{.22\textwidth}
\includegraphics[width=1\textwidth]{figs/port_conns_sb_area.pdf}
\end{subfigure} \hspace{1em}
\begin{subfigure}[b]{.22\textwidth}
\includegraphics[width=0.97\textwidth]{figs/port_conns_cb_area.pdf}
\end{subfigure}
\vspace{-1em}
\captionsetup{justification=justified}
\caption{Area comparison of a switch box and a connection box that have varying number of connections with the four sides of the tile.}
\label{fig:port-conn-area}
\vspace{-1em}
\end{figure}
As shown in Fig.~\ref{fig:port-conn-area}, as the number of connections from the core to the switch box decreases, we see a decrease in switch box area. From Fig.~\ref{fig:port-conn-sb-runtime}, we can see that this generally has a small negative effect on the run time of the applications. In this case, a designer could choose to trade some performance for a decrease in switch box area.
As shown in Fig.~\ref{fig:port-conn-area}, as the number of connections from the connection box to the tile inputs decreases, we see a larger decrease in connection box area. From Fig.~\ref{fig:port-conn-cb-runtime}, we can see that this has a larger negative effect on the run time of the applications. Again, a designer could choose to trade some performance for a decrease in connection box area.
\section{Conclusion}
\vspace{-0.4cm}
We have developed Canal, a domain-specific language and interconnect generator for coarse-grained reconfigurable arrays. The Canal language allows a designer to easily specify a complex configurable interconnect, while maintaining control over the low-level connections. The hardware generator, placer and router, and bitstream generator help to facilitate design space exploration of CGRA interconnects. We demonstrate the flexibility of Canal by creating a hybrid ready-valid interconnect and demonstrate the design space exploration capabilities of Canal by evaluating different switch box topologies, number of interconnect routing tracks, and number of SB and CB port connections. The power and flexibility that Canal provides will enable more designers to create and explore diverse and interesting CGRA architectures.
\begin{figure}
\centering
\vspace{-1em}
\includegraphics[width=0.4\textwidth]{figs/port_conns_sb_runtime.pdf}
\vspace{-1em}
\caption{Run time comparison of a switch box that has varying number of connections from the four sides of the tile.}
\label{fig:port-conn-sb-runtime}
\vspace{-0.5em}
\end{figure}
\begin{figure}
\centering
\vspace{-0.7em}
\includegraphics[width=0.4\textwidth]{figs/port_conns_cb_runtime.pdf}
\vspace{-1em}
\caption{Run time comparison of a connection box that has varying number of connections from the four sides of the tile.}
\label{fig:port-conn-cb-runtime}
\end{figure} | {'timestamp': '2022-12-01T02:20:26', 'yymm': '2211', 'arxiv_id': '2211.17207', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17207'} | arxiv |
\section{Introduction}
\label{sec:intro}
In recent years, \gls*{ml} has been increasingly applied for high-stakes decision making with a huge impact on human lives, such as medical applications~\cite{shahid_predictions_2020, brinker_deep_2019}, credit scoring~\cite{wang2011comparative}, criminal justice~\cite{zavrvsnik2020criminal} and hiring processes~\cite{bogen2018help}.
Therefore, awareness has been raised for the need of neural networks and their predictions to be transparent and explainable~\cite{goodman_european_2017}, which makes \gls*{xai} a key component of modern \gls*{ml} systems.
Rule-based and modified backpropagation-based \gls*{xai} methods, such as DeepLift~\cite{shrikumar2017learning}, \gls*{lrp}~\cite{bach_pixel-wise_2015} or Excitation Backprop~\cite{zhang_top-down_2018}, which are among the most prominent algorithms to explain neural network predictions, however, struggle when being applied to modern model architectures with innovative building blocks.
This is caused by two problems:
Firstly, rule-based \gls*{xai} methods provide large flexibility thanks to configurable rules which can be tailored to the model architecture at hand.
This comes at the cost of a large number of potential \gls*{xai} method parameterizations, particularly for complex model architectures.
However, finding optimal parameters is barely researched and often neglected, which can cause these methods to yield suboptimal explanations.
Secondly, earlier works~\cite{montavon2019gradient} have shown that many \gls*{xai} methods break implementation invariance, which has been defined as an axiom for explanations~\cite{sundararajan_axiomatic_2017}.
This is caused by certain layer types for which no explanation rules have been defined yet, e.g., \gls*{bn} layers.
To address that issue, \emph{model canonization} has been suggested, a method that fuses \gls*{bn} layers into neighboring linear layers without changing the underlying function of the neural network~\cite{hui_batchnorm_2019, guillemot_breaking_2020}, arguably leading to improved explanations for simple model architectures (VGG, ResNet)~\cite{motzkus_measurably_2022}.
However, what constitutes a ``good'' explanation is only vaguely defined and many, partly contradicting, metrics for the quality of explanations have been proposed.
Therefore, tuning hyperparameters of \gls*{xai} methods and measuring the benefits of model canonization for \gls*{xai} are non-trivial tasks.
To that end, we propose an evaluation framework, in which we evaluate \gls*{xai} methods w.r.t their faithfulness, complexity, robustness, localization capabilities and behavior with regard to randomized logits, following the authors of~\cite{hedstrom_quantus_2022}.
We apply our framework to (1) measure the impact of canonization and (2) demonstrate how hyperparameter search can improve the quality of explanations.
Therefore, we first extend the model canonization approach to modern model architectures with high interconnectivity, e.g., DenseNet variants.
We apply our evaluation framework to measure the benefits of model canonization for various image classification model architectures (VGG, ResNet, EfficientNet, DenseNet) using the ILSVRC2017 and Pascal VOC 2012
datasets, as well as for \gls*{vqa} with Relation Networks using the CLEVR-XAI dataset~\cite{arras_clevr-xai_2022}.
We show that generally model canonization is beneficial for all tested architectures, but depending on which aspect of explanation quality is measured, the impact of model canonization differs.
Moreover, we demonstrate how our \gls*{xai} evaluation framework can be leveraged for hyperparameter search to optimize the explanation quality from different points of view.
\section{Related Work}
\label{sec:related_work}
\subsection{XAI Methods}
\label{sec:rw_xai_methods}
XAI methods can broadly be categorized into local and global explanations.
While local explainers focus on explaining the model decisions on specific inputs, global explanation methods aim to explain the model behavior in general, e.g., by visualizing learned representations.
For image classification tasks, local XAI methods assign relevance scores to each input unit, expressing how influential that unit (e.g., an input pixel) has been for the inference process.
Many XAI methods are (modified) backpropagation approaches.
To compute the importance of features in the detection of a certain class
, they start from the output of the network, backpropagating importance values layer by layer, depending on the parameters and/or hidden activations of each layer.
Saliency maps~\cite{simonyan2013deep,baehrens_saliency_2010,morch_saliency_1995}
are generated by computing the gradient $\frac{\partial f(\textbf{x}) }{\partial \textbf{x}}$, where $f(\textbf{x})$ is the model's prediction for an input sample $\textbf{x}$. This yields a feature map where each value indicates the model's sensitivity towards the corresponding feature.
Guided Backpropagation~\cite{springenberg_guided-bp_2014} also uses the gradients, but applies the ReLU function to computed gradients in ReLU activation layers in the backpropagation pass.
This filters out the flow of negative information, allowing to focus on the parts of the image where the desired class is detected.
Integrated Gradients~\cite{sundararajan_axiomatic_2017} accumulates the activation gradients on a straight path in the input space, starting from a baseline image $\textbf{x}^\prime$ selected beforehand, to the datapoint of interest. Formally, the attribution to the $i^\text{th}$ feature is given by $(x_i-x^\prime_i)\int_{\rho=0}^1 \frac{\partial f(\textbf{x}+\rho(\textbf{x}^\prime -\textbf{x}))}{\partial x_i}d\rho$.
SmoothGrad~\cite{smilkov_smooth_2017} aims to reduce the noise in saliency maps by sampling datapoints in the neighborhood of the original datapoint, and taking the average saliency map.
Since these XAI methods only on the gradients of the total function computed by the network, they are implementation invariant, meaning they produce the same explanations for different implementations of the same function.
\gls*{lrp}~\cite{bach_pixel-wise_2015} operates by redistributing the relevance scores of neurons backwards up to the input features.
More precisely, LRP distributes the activation of the output neuron of interest to the previous layers in a way that preserves relevance across layers.
Several rules have been defined (e.g., LRP-$\varepsilon$, LRP-$\gamma$, LRP-$\alpha\beta$), which can be combined in meaningful configurations according to the types and positions of layers in the neural network.
Excitation Backprop~\cite{zhang_top-down_2018} is a backpropagation method that is equivalent to LRP-$\alpha1\beta0$~\cite{montavon_methods-for-interpreting-dnns_2018}, which has a probabilistic interpretation.
DeepLIFT~\cite{shrikumar_deeplift_2017} is another rule-based method, where a reference image (e.g., the mean over the training population) is selected in addition. Using the associated rules, the differences in the activations of neurons on the reference image and the target image are backpropagated to the input.
In addition to backpropagation-based XAI methods there are also other approaches.
Prominent examples are SHAP~\cite{lundberg_shap_2017}, which uses the game theoretic concept of Shapley values to find the contribution of each input feature to the model output, and LIME~\cite{ribeiro_lime_2016}, which fits an interpretable model to the original model output around the given input.
Both methods treat the model as a black box, only using outputs for certain inputs. As such, they are also implementation independent.
\subsection{Evaluation of XAI Methods}
While various XAI methods have been developed, the quantitative evaluation thereof is often neglected and explanations of XAI methods are often only compared by visually inspecting heatmaps.
To address this issue, many XAI metrics have been introduced in recent years~\cite{hedstrom_quantus_2022,agarwal2022openxai}.
However, there is no consensus on which metric to use and moreover, each metric evaluates explanations from different viewpoints, partly with contradictory objectives.
Broadly speaking, XAI metrics can be categorized into five classes: \textbf{Faithfulness} metrics measure whether an explanations truly represents features used by the model. For instance, Pixel Flipping~\cite{bach_pixel-wise_2015} measures the difference in output scores of the correct class, when replacing pixels in descending order of their relevance scores with a baseline value (e.g., black pixel or mean pixel). If the score decreases quickly, i.e., after replacing only a few highly relevant pixels, the explanation is considered as highly faithful. Faithfulness correlation~\cite{bhatt_evaluating_2020} replaces a random subset of attribution with a baseline value and measures the correlation between the sum of attributions in the subset and the difference in model output.
\textbf{Robustness} metrics measure the robustness of explanations towards small changes in the input. Prominent examples are Max-Sensitivity and Avg-Sensitivity~\cite{yeh__2019}, which use Monte Carlo sampling to measure the maximum and average sensitivity of an explanation for a given XAI method.
\textbf{Localization} metrics measure how well an explanation localizes the object of interest for the underlying task.
Consequently, in addition to the input sample and an explanation function, ground-truth localization annotations are required. Examples for localization metrics are \gls*{rra} and \gls*{rma}~\cite{arras_clevr-xai_2022}.
\gls*{rra} measures the fraction of high-intensity relevances within the (binary) ground truth mask as $\text{RRA}=\frac{|P_{\text{top-K}} \cap GT|}{|GT|}$, where $GT$ is the ground truth, $K$ is the size of the ground truth mask and $P_{\text{top-K}}$ is the set of pixels sorted by relevance in decreasing order.
Similarly, \gls*{rma} measures the fraction of the total relevance mass within the ground truth mask and can be computed as $\text{RMA}=\frac{R_\text{within}}{R_\text{total}}$ where $R_\text{within}$ is the sum of relevance scores for pixels within the ground truth mask and $R_\text{total}$ is the sum of all relevance scores.
\textbf{Complexity} metrics measure how concise explanations are. For example, the authors of~\cite{chalasani_concise_2020} use the Gini Index of the total attribution vector to measure it's sparseness, while~\cite{bhatt_evaluating_2020} propose an entropy-derived measure.
\textbf{Randomization} metrics measure by how much explanations change when randomizing model components.
For instance, the random logit test~\cite{sixt_when_2020} measures the distance between the original explanation and the explanation with respect to a random other class.
\subsection{Challenges of Rule-Based/Modified Backpropagation Methods}
\label{sec:xai_problems}
\paragraph{No Implementation Invariance:} From a functional perspective, it is desirable for an XAI method to be implementation invariant, i.e., the explanations for predictions of two different neural networks implementing the same mathematical function should always be identical~\cite{sundararajan_axiomatic_2017}.
However rule-based and modified backpropagation approaches explain predictions from a message-passing point of view, which, by design, is affected by the structure of the predictor.
Therefore, these methods violate the implementation invariance axiom, for example because of concatenations of linear operations such as \gls*{bn} and Convolutional layers.
However, this problem can be overcome with model canonization, i.e., re-structuring the network into a canonical form implementing exactly the same mathematical function.
\paragraph{Parameterization:}
\label{sec:gamma_rule}
Rule-based backpropagation approaches are highly flexible and allow to tailor the XAI method to the underlying model and the task at hand. However, this flexibility comes at the cost of numerous different possible parameterizations.
For instance, the $\gamma$-rule in \gls*{lrp} computes relevances $R_j$ of layer $j$ given relevances $R_k$ from the succeeding layer $k$ as
\begin{equation}
R_j=\sum_k\frac{a_j \cdot (w_{jk} + \gamma w_{jk}^{+})}{\sum_{0,j}a_j \cdot (w_{jk} + \gamma w_{jk}^{+})} \cdot R_k~~,
\end{equation}
where $a_j$ are the lower-layer activations, $w_{jk}$ are the weights between layers $j$ and $k$, $w_{jk}^{+}$ is the positive part of $w_{jk}$ and $\gamma$ is a parameter allowing to regulate the impact of positive and negative contributions.
Therefore, $\gamma$ is a hyperparameter that has to be defined for each layer.
Note that the $\gamma$-rule becomes equivalent to the $\alpha1\beta0$-rule as $\gamma \rightarrow \infty$, where negative contributions are disregarded.
Similarly, for $\gamma=0$, it is equivalent to the $\varepsilon$-rule, where negative and positive contributions are treated equally.
The choice of $\gamma$ for each layer can highly impact various measurable aspects of explanation quality.
\section{Model Canonization}
\label{sec:canonization_general}
We assume there is a model $f$, which, given input data $\textbf{x}$, implements the function $f(\textbf{x})$.
We further assume that $f$ contains model components which pose challenges for the implementation of certain \gls*{xai} methods.
Model canonization aims to replace $f$ by a model $g$ where $g(\textbf{x})=f(\textbf{x})$, but $g$ does not contain the problematic components.
We call $g$ the canonical form of all models implementing the function $g(\textbf{x})$.
In practice, model canonization can be achieved by restructuring the model and combining several model components, as outlined in the following sections.
\subsection{BatchNorm Layer Canonization}
\label{sec:canonization_theory}
\gls*{bn} layers~\cite{ioffe_batch_2015} were introduced to increase
the stability of model training by normalizing the gradient flows in neural networks.
Specifically, \gls*{bn} adjusts the mean and standard deviation as follows:
\begin{equation}
\text{BN}(\textbf{x})=w_{BN}^\top \Big(\frac{\textbf{x} - \mu}{\sqrt{\sigma + \varepsilon}}\Big) + b_{BN}~~,
\end{equation}
where $w_{BN}$ and $b_{BN}$ are learnable weights and a bias term of the \gls*{bn} layer, $\mu$ and $\sigma$ are the running mean and running variance and $\varepsilon$ is a stabilizer.
\newline
However, as discussed in Section \ref{sec:xai_problems}, \gls*{bn} layers have shown to pose challenges for modified backpropagation \gls*{xai} methods, such as \gls*{lrp}~\cite{hui_batchnorm_2019}.
To address that problem, model canonization can be applied to remove \gls*{bn} layers without changing the output of the function.
We make use of the fact that during test time the \gls*{bn} operation can be viewed as a fixed affine transformation.
Specifically, we follow previous works~\cite{ guillemot_breaking_2020}, which have shown that \gls*{bn} layers can be fused with neighboring linear layers, including fully connected layers and Convolutional layers, of form $w_L^\top \textbf{x} + b_L$, where $w_L$ is the weight matrix and $b_L$ is the bias term.
This results in a single linear layer, combining the affine transformations from the original linear layer and the \gls*{bn}.
The exact computation of the new parameters of the linear transformation depends on the order of model components:
\paragraph{Linear $\rightarrow$ BN:} Many popular architectures (including VGG~\cite{szegedy_going_2015} and ResNets \cite{he_deep_2016}) apply batch normalization directly after Convolutional layers. Hence, this model component implements the following function:
\begin{align}
f(\textbf{x}) &= \text{BN}(\text{Linear}(\textbf{x})) \\
&= (\underbrace{\frac{w_{BN}}{\sqrt{\sigma + \varepsilon}} w_L}_{w_\text{new}})^\top \textbf{x} + \underbrace{\frac{w_{BN}}{\sqrt{\sigma + \varepsilon}} (b_L - \mu) + b_{BN}}_{b_\text{new}}
\label{eq:lin_bn}
\end{align}
which can be merged into a single linear layer with weight $w_{\text{new}}=\frac{w_{BN}}{\sqrt{\sigma + \varepsilon}} w_L$ and bias $b_\text{new}=\frac{w_{BN}}{\sqrt{\sigma + \varepsilon}} (b_L - \mu) + b_{BN}$. See Section~\ref{app:canonization_details} in the appendices for details.
\paragraph{BN $\rightarrow$ Linear:} Other implementations apply \gls*{bn} right before linear layers (i.e., \emph{after} the activation function of the previous layer), which impacts the computation of parameters of the merged linear transformation:
\begin{align}
f(\textbf{x}) &= \text{Linear}(\text{BN}(\textbf{x})) \\
&= \underbrace{\frac{w_L^\top w_{BN}}{\sqrt{\sigma + \varepsilon}}}_{w_\text{new}} \textbf{x} \underbrace{- \frac{w_L^\top w_{BN} \mu}{\sqrt{\sigma + \varepsilon}} + w_L^\top b_{BN} + b_L}_{b_\text{new}}
\label{eq:bn_lin}
\end{align}
Again, this component can be fused into a single linear transformation with weight $w_{\text{new}}=\frac{w_L^\top w_{BN}}{\sqrt{\sigma + \varepsilon}}$ and bias $b_\text{new}=w_L^\top b_{BN} - \frac{w_L^\top w_{BN} \mu}{\sqrt{\sigma + \varepsilon}} + b_L$.
Note that there are practical challenges when padding is applied, for instance in a Convolutional layer.
In this case, the bias becomes a spatially varying term, which cannot be implemented with standard Convolutional layers.
See Appendix~\ref{app:canonization_details} for details.
\paragraph{BN $\rightarrow$ ReLU $\rightarrow$ Linear:} In some architectures, \gls*{bn} layers have to be merged with linear layers with an activation function (e.g., ReLU) in between. For instance, in DenseNets model components occur in that order.
In that case, model canonization goes beyond merging two affine transformations, because of the non-linear activation function in between.
Therefore, we propose to swap the BN layer and the activation function, which can be achieved by defining a new activation function, named $\textit{ReLU}_{\textit{thresh}}$ which depends on the parameters of the \textbf{BN} layer, such that
\begin{align}
\text{ReLU}(\text{BN}(\textbf{x})) &= \text{BN}(\text{ReLU}_{\text{thresh}}(\textbf{x}))~~,
\label{eq:bn_thresh}
\end{align}
where
\begin{align}
\text{ReLU}_{\text{thresh}}(\textbf{x})
= \begin{cases}
\textbf{x} & \text{if } (w_{\text{BN}}>0 \text{ and } \textbf{x}>z)\\\textbf{x}&\text{if }(w_{\text{BN}}<0\text{ and } \textbf{x}<-z)\\
z & \text{otherwise}
\end{cases}
\label{eq:def_thresh}
\end{align}
with $z=\mu-\frac{b_{\text{BN}}}{w_{\text{BN}} / \sqrt{\sigma+\varepsilon}}$.
Hence, \textbf{BN}$\rightarrow$\textbf{ReLU}$\rightarrow$ \textbf{Linear} is first transformed into \textbf{ThreshReLU}$\rightarrow$\textbf{BN}$\rightarrow$ \textbf{Linear}, then the \gls*{bn} layer and the linear layer can be merged with Eq.~\ref{eq:bn_lin}.
\begin{figure*}[ht]
\centering
\includegraphics[width=.75\linewidth]{figures/densenet_canon.png}
\caption{Due to the high interconnectivity of model components in DenseNets, it is not straightforward to fuse \gls*{bn} layers with Convolutional layers from neighboring blocks. Therefore, we suggest to first swap \gls*{bn} layers and ReLU activation functions using Eq.~\ref{eq:bn_thresh} (see step b)) and then merge the \gls*{bn} parameters into the following Convolutional layer using Eq.~\ref{eq:bn_lin} (see step c)).
\label{fig:canon_densenet}}
\end{figure*}
\subsection{Canonization of Popular Architectures}
\label{sec:canonization_examples}
We now demonstrate the canonization of popular neural network architectures.
We picked 4 image classification models (VGG, ResNet, EfficientNet and DenseNet) and one \gls*{vqa} model (Relation Network~\cite{santoro_simple_2017}).
\paragraph{Image Classification Models:} Many popular image classification model architectures, such as VGG~\cite{szegedy_going_2015}, ResNet~\cite{he_deep_2016} and EfficientNet~\cite{tan_efficientnet_2019}, apply \gls*{bn} directly after linear layers. Therefore, these networks can easily be canonized using Eq.~\ref{eq:lin_bn}.
It gets more complicated, however, if model architectures are more complex with highly interconnected building blocks.
DenseNets, for example, use skip connections to pass activations from each dense block to all subsequent blocks, as shown in Fig.~\ref{fig:canon_densenet}.
Each block applies \gls*{bn} on the concatenated inputs coming from multiple blocks, followed by ReLU activation and a Convolutional layer (BN $\rightarrow$ ReLU $\rightarrow$ Conv).
Note that due to the high interconnectivity, \gls*{bn} layers cannot easily be merged into linear layers from neighboring blocks, because most linear layers pass their activations to multiple blocks, and vice versa, most blocks receive activations from multiple blocks.
Consequently, the linear transformation implementing the \gls*{bn} function has to be merged with the linear layer following the ReLU activation within the same block.
Therefore, we propose to perform model canonization by first applying Eq.~\ref{eq:bn_thresh} and then Eq.~\ref{eq:bn_lin} to join \gls*{bn} layers with following linear layers within the same block, over the ReLU function between them.
This process is visualized in Fig.~\ref{fig:canon_densenet}.
In addition, we apply Eq.~\ref{eq:lin_bn} to merge the first \gls*{bn} layer in the initial layers of the DenseNet architecture, before the dense blocks.
Moreover, there is a BN$\rightarrow$ReLU$\rightarrow$AvgPool2d$\rightarrow$Conv chain in the end of the network, which can also be merged using Eq.~\ref{eq:bn_thresh} and Eq.~\ref{eq:bn_lin}.
\paragraph{VQA Model:} In contrast to image classification models, VQA models, e.g., Relation Network~\cite{santoro_simple_2017}, require two paths to encode both, the input image and the input question. Relation Networks use a simple Convolutional neural network as image encoder. The implementation by the authors of CLEVR-XAI~\cite{arras_clevr-xai_2022} applies \gls*{bn} \emph{after} the activation function (Conv $\rightarrow$ ReLU $\rightarrow$ BN). Therefore, we merge \gls*{bn} layers with the Convolutional layer from the following block using Eq.~\ref{eq:bn_lin}.
The \gls*{bn} layer of the last block of the image encoder has to be merged with the fully connected layer of the following module, which, however, receives a concatenation of image encoding and text encoding from the input question.
Therefore, it has to be assured that \gls*{bn} parameters are merged only with the weights operating on inputs coming from the image encoder (see Appendix~\ref{sec:relation_network_details} and Fig.~\ref{fig:rn_canonization} in the appendices for details).
\section{Experiments: XAI Evaluation Framework}
\label{sec:experiments}
\subsection{Datasets}
\label{sec:exp_datasets}
\paragraph{ILSVRC2017~\cite{russakovsky_imagenet_2015}} is a popular benchmark dataset for object recognition tasks with 1.2 million samples categorized into 1,000 classes, out of which we randomly picked 10 classes for our experiments.\footnote{We use the following classes: ``Toucan'', ``Tibetan terrier'', ``Siamese cat'', ``Tiger shark'', ``Ostrich'', ``Jellyfish'', ``Red fox'', ``Zebra'', ``Chimpanzee'', ``African elephant''.
} Bounding box annotations are provided for a subset of ILSVRC2017, which we use for localization metrics. Per class, we use 400 random samples in our experiments. Note that ILSVRC2017 faces a center-bias, i.e., most of the objects to be classified are located in the center of the image. Therefore, naive explainers can assume that models base their decisions on center pixels.
To that end, we include additional experiments using the Pascal VOC 2012 dataset~\cite{everingham_pascal_2010} in Appendix~\ref{sec:experiments_pascal}.
\paragraph{CLEVR-XAI~\cite{arras_clevr-xai_2022}}
builds upon the CLEVR dataset~\cite{johnson_clevr_2017}, which is an artificial \gls*{vqa} dataset. It contains 10,000 images showing objects with varying characteristics regarding shape, size, color and material.
Moreover, there are simple and complex questions that need to be answered.
The task is framed as a classification task, in which, given an image and a question, the model has to predict the correct response out of 28 possible answers.
In total, there are approx.\ 40,000 simple questions, asking for certain characteristics of single objects.
In addition, there are 100,000 complex questions, which require the understanding of relationships between multiple objects.
CLEVR-XAI further comes with ground-truth explanations, encoded as binary masks locating the objects that are required in order to answer the question.
Simple questions come with two binary masks, which are \textit{GT Single Object}, localizing the object affected by the question, and \textit{GT All Objects}, localizing all objects in the image.
For complex questions there are four binary masks, including \textit{GT Union} localizing all objects that are required to answer the question (we refer to~\cite{arras_clevr-xai_2022} for details on the other masks).
\subsection{Models}
\label{sec:exp_models}
For our experiments with ILSVRC2017, we analyze VGG-16~\cite{szegedy_going_2015}, ResNet-18~\cite{he_deep_2016}, EfficientNet-B0~\cite{tan_efficientnet_2019} and DenseNet-121~\cite{huang_densely_2017}. We use pre-trained models provided in the PyTorch model zoo~\cite{paszke_pytorch_2019}.
We use a Relation Network~\cite{santoro_simple_2017} for our experiments with CLEVR-XAI.
\subsection{XAI Methods and Implementation Details}
\label{sec:exp_explainers}
We analyze rule-based and modified backpropagation based XAI methods
, namely \gls*{eb} and \gls*{lrp}.
Note that other backpropagation-based methods, such as Saliency, Smoothgrad, Integrated Gradients and Guided Backprop are not impacted by model canonization~\cite{motzkus_measurably_2022} and are therefore not analyzed in this experiment.
For each method, we compute explanations for both, the original and the canonized model.
We use \textit{zennit}\footnote{\url{https://github.com/chr5tphr/zennit}}~\cite{anders_software_2021} as toolbox to compute explanations.
For \gls*{lrp}, we analyze two pre-defined \emph{composites}, i.e., mappings from layer type to \gls*{lrp} rule which have been established in literature~\cite{montavon_layer-wise_2019}, namely \gls*{ep} and \gls*{a2b1}, see Tab.~\ref{tab:composites} in the appendices for details.
For Relation Networks, we use an additional composite (\emph{LRP-Custom}) following~\cite{arras_clevr-xai_2022}, in which we apply the $\alpha1\beta0$ rule to all linear layers and the box-rule~\cite{montavon_layer-wise_2019} to the input layer.
Note that ResNets, EfficientNets and DenseNets leverage skip connections, which require the application of an additional canonizer in \textit{zennit} to explicitly make them visible to the XAI method.
Furthermore, we apply the signal-takes-it-all rule~\cite{arras__2017} to address the gate functions in the Squeeze-and-Excitation modules~\cite{hu_squeeze-and-excitation_2018} in EfficientNets.
In order to convert 3-dimensional relevance scores per voxel (channel $\times$ height $\times$ width) into 2-dimensional scores per pixel (height $\times$ width), we simply sum the relevances on the channel axis for ILSVRC2017
experiments.
For CLEVR-XAI experiments we follow the authors from~\cite{arras_clevr-xai_2022} and use
\textit{pos-l2-norm-sq} ($R_\text{pool}=\sum_{i=1}^C max(0, R_i)^2$) as pooling function, where $C=3$ is the number of channels.
Results for other pooling functions, including \textit{max-norm} ($R_\text{pool}=max(|R_1|, R_2, ..., R_C)$) and the channel-wise sum, are provided in the appendices.
Moreover, before computing the metrics, we normalize the relevances
by dividing all values by the square root of the second moment to bound their variance for numerical stability when comparing heatmaps.
\subsection{XAI Metrics}
\label{sec:exp_metrics}
In our experiments, we quantitatively measure the impact of canonization of the selected model architectures with various metrics, probing the quality of explanations from different viewpoints.
We use the \emph{quantus} toolbox\footnote{\url{https://github.com/understandable-machine-intelligence-lab/quantus}}~\cite{hedstrom_quantus_2022} to compute the following metrics:
We measure \textbf{Faithfulness} using Pixel Flipping. As baseline value we use the mean pixel value in the training set. We compute the \gls*{aopc}~\cite{samek_evaluating_2016} to measure the faithfulness in a single number as $\text{AoPC}=\frac{1}{L+1}\Big(\sum_{k=0}^L f(\textbf{x}^{(0)}) - f(\textbf{x}^{(k)})\Big)$, where $\textbf{x}$ is the input sample, $k$ is the perturbation step and $L$ is the total number of perturbations. The \gls*{aopc} is averaged over all input samples.
\textbf{Localization} quality is measured using \gls*{rra} and \gls*{rma}. As ground truth location we use bounding box annotations provided for ILSVRC2017, and binary segmentation masks for CLEVR-XAI. For the latter, we use \textit{GT Unique} for simple questions and \textit{GT Union} for complex questions. Moreover, we use the average sensitivity to measure \textbf{Robustness}, sparseness for \textbf{Complexity} and run the logit test as \textbf{Randomization} metric. While for robustness and randomization low scores are desirable, for the other metrics higher scores are better.
\begin{table*}[t]
\centering
\include{results/results_all}
\caption{\label{tab:results_imagenet} \gls*{xai} evaluation results with and without model canonization for VGG-16, ResNet-18, EfficientNet-B0 and DenseNet-121 using the ILSVRC2017 dataset. We measure the quality of explanations using the metrics Sparseness (\emph{Complexity}), Pixel Flipping (\emph{Faithfulness}), \gls*{rra} and \gls*{rma} (\emph{Localization}), Avg. Sensitivity (\emph{Robustness}) and Random Logit Test (\emph{Randomization}). For the latter two low values are better, while for the other metrics high values are better. Best results are shown in bold.}
\end{table*}
\begin{table*}[ht]
\centering
\include{results/clevr_main.tex}
\caption{\label{tab:results_clevr_xai} \gls*{xai} evaluation results for Relation Network with and without model canonization using the CLEVR-XAI dataset for both, simple and complex questions. Attribution scores are pooled using the \textit{pos-l2-norm-sq}-pooling function. Best results are shown in bold.}
\end{table*}
\subsection{Canonization Results}
\label{sec:exp_canon}
The \gls*{xai} evaluation results for the ILSVRC2017 dataset comparing models with and without canonization using the metrics described above are shown in Tab.~\ref{tab:results_imagenet}.
It can be seen that for most models and metrics the \gls*{xai} methods yield better explanations for canonized models.
However, there are some exceptions.
While all other models yield less complex explanations when using model canonization, DenseNet explanations appear to show the opposite behavior.
The localization metrics tend to be better for canonized model, except for EfficientNet-B0 with the $\alpha2\beta1$-composite for \gls*{lrp}, which, however, also yields a poor performance in terms of faithfulness.
Hence, the $\alpha2\beta1$-composite itself appears to be a suboptimal parameterization for EfficientNets, which demonstrates the importance of the choice of hyperparameters for rule-based XAI methods.
Note that randomization scores tend to increase for canonized models, i.e., the canonized model leads to explanations that are less dependent on the target class.
This is due to the fact that the explanations are more focused on the object to classify (see improvements for localization) and therefore are more similar when computed for different target classes.
Results for additional models and XAI evaluation metrics are shown in the appendices in Tables~\ref{tab:vgg16}-\ref{tab:densenet161}.
In Tab.~\ref{tab:results_clevr_xai} we show results for our XAI evaluation using the CLEVR-XAI dataset.
In general, pre-defined LRP-composites developed for feed-forward models in image classification settings~\cite{montavon_layer-wise_2019,kohlbrenner_towards_2020} yield poor results for most metrics compared to the customized LRP configuration.
However, for the LRP-Custom configuration, model canonization yields explanations that are either better than those of the original model or approx.\ on par with them for both simple and complex questions.
Results with other pooling techniques are shown in the appendices in Tables~\ref{tab:clevr_max_norm}~and~\ref{tab:clevr_sum}.
\label{sec:exp_results}
\begin{figure*}[ht]
\centering
\includegraphics[width=.8\linewidth]{figures/figure_facet_grid.png}
\caption{Results Grid Search for VGG-13: We group the layers into low-level (\emph{Conv 1-3}), mid-level (\emph{Conv 4-7}) and high-level (\emph{Conv 8-10}) Convolutions, as well as fully connected layers in the classification head (\emph{Classifier}). We evaluate different parameterizations for the $\gamma$-rule, where we define different values for $\gamma$ per group and measure the quality of explanations both with and without model canonization w.r.t localization, faithfulness, complexity, randomization and robustness metrics.}
\label{fig:results_grid_search}
\end{figure*}
\begin{figure*}[ht]
\centering
\includegraphics[width=.9\linewidth]{figures/attributions_grid_search_canon1.png}
\caption{Attribution heatmaps (with canonization) for best and worst $\gamma$-parameters according to the grid search. $\gamma_1$ is for low-level features (Conv 1-4), $\gamma_2$ is for mid-level features (Conv 5-10), $\gamma_3$ is for high-level features (Conv 10-13), $\gamma_4$ is for layers in the classification head. }
\label{fig:attributions_grid_search}
\end{figure*}
\subsection{XAI Hyperparameter Tuning}
For our experiments in Section~\ref{sec:exp_canon} we used pre-defined composites for the LRP parameterization established in literature~\cite{montavon_layer-wise_2019,kohlbrenner_towards_2020}.
However, as the different results for the evaluated composites suggest, the parameters required to run LRP differently impact the quality of explanations w.r.t the chosen metric.
To that end, we run another experiment in which we use our XAI evaluation framework for hyperparameter tuning.
Specifically, we focus on the LRP-$\gamma$-rule, which uses the parameter $\gamma$ to regulate the effect of positive and negative contributions (see Sec.~\ref{sec:gamma_rule}).
It ranges from treating both equally ($\gamma=0$) to neglecting negative contributions ($\gamma \rightarrow \infty$).
Further, the flexibility of the \gls*{lrp} framework allows us to define \gls*{xai} methods with varying focus on positive and negative contributions depending on the position of the layer in the network.
In our experiment, we use a \mbox{VGG-13} model with \gls*{bn} and define 4 groups of network layers, which are low-level Convolutional layers (Conv 1-3), mid-level Convolutional layers (Conv 4-7), high-level Convolutional layers (Conv 8-10) and fully-connected layers in the classification head.
We define one $\gamma$-parameter per group with $\gamma \in [0, 0.1, 0.25, 0.5, 1, 10]$, and run a grid search for all possible combinations for both with and without model canonization, i.e., $2 \cdot 6^4=2592$ $\gamma$-configurations. Note that in theory, we could also evaluate different sub-canonizations, where we only canonize certain parts of the model.
This, however, further increases the degrees of freedom.
We evaluate the resulting explanations with the metrics described in section~\ref{sec:exp_metrics} and show the results in Fig.~\ref{fig:results_grid_search}.
Specifically, each line represents the score per metric with $\gamma$ for a certain group of layers kept constant, averaged over all $\gamma$-parameterizations for other layer groups.
It can be seen that the impact of the choice of $\gamma$ depends on the position of the layer in the network and, in addition, differs by the metric of choice.
For instance, the robustness of the explanations is mainly impacted by the $\gamma$-value in low-level Convolutional layers (Conv 1-3), while it has no impact for the other layers.
In contrast, randomization is mostly impacted by the choice of $\gamma$ for fully connected layers in the classification head.
Interestingly, canonization has a large impact on the optimal choice of $\gamma$ for low-level Convolutional layers when measuring the faithfulness of the resulting explanations.
In Fig.~\ref{fig:attributions_grid_search} we show attribution heatmaps for three samples using different $\gamma$-configurations, where we apply model canonization and use the best and worst parameterization according to the metrics faithfulness, localization and complexity.
It can be seen that each metric favors another parametrization, which leads to different attribution heatmaps.
High $\gamma$-values in low-level layers ($\gamma_1$) appear to be favorable for all metrics, i.e., more focus on positive contributions on those layers.
This leads to attribution heatmaps with less noise, which is beneficial w.r.t faithfulness, localization and complexity.
\section{Conclusions}
\label{sec:exp_conclusions}
In this work, we proposed an evaluation framework for XAI methods which can be leveraged to optimize the quality of explanations based on a variety of XAI metrics.
Specifically, we demonstrated the application of our framework to measure the impact of model canonization towards various aspects of explanation quality.
Therefore, we extended the model canonization approach to state-of-the-art model architectures, including EfficientNets and DenseNets.
Moreover, we applied our evaluation framework for hyperparameter optimization for XAI methods and demonstrated the impact of parameters w.r.t different XAI metrics.
While we have evaluated our methods for LRP, it is also applicable to other configurable XAI methods, such as DeepLift.
Future work can focus on optimized hyperparameter search, e.g., with random search, evolutionary algorithms, or other approaches to reduce the search space.
Moreover, the framework can be applied with other optimization objectives, e.g., to find LRP configurations that mimic other, more expensive XAI methods, e.g., SHAP.
\section*{Acknowledgements}
This work was supported by
the European Union's Horizon 2020 research and innovation programme (EU Horizon 2020) as grant [iToBoS (965221)];
the state of Berlin within the innovation support program ProFIT (IBB) as grant [BerDiBa (10174498)];
the Federal Ministry of Education and Research (BMBF) as grant [BIFOLD (01IS18025A, 01IS18037I)];
the Research Council of Norway, via the SFI Visual Intelligence grant [project grant number 309439].
{\small
\bibliographystyle{ieee_fullname}
| {'timestamp': '2022-12-01T02:19:44', 'yymm': '2211', 'arxiv_id': '2211.17174', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17174'} | arxiv |
\section{#1}\label{sec:#2}\vspace{-.1cm}}
\newcommand{\mysubsection}[2]{\subsection{#1}\label{sec:#2}\vspace{-.1cm}}
\newcommand{\mysubsubsection}[2]{\subsubsection{#1}\label{sec:#2}\vspace{-.1cm}}
\definecollection{mymaths}
\newcommand{\mymath}[2]{
\newcommand{#1}{\TextOrMath{$#2$\xspace}{#2}}
\begin{collect}{mymaths}{}{}{}{}
#1
\end{collect}
}
\definecolor{colorA}{HTML}{4285f4}
\definecolor{colorB}{HTML}{ea4335}
\definecolor{colorC}{HTML}{fbbc04}
\definecolor{colorD}{HTML}{34a853}
\definecolor{colorE}{HTML}{ff6d01}
\definecolor{colorF}{HTML}{46bdc6}
\definecolor{colorG}{HTML}{000000}
\definecolor{colorH}{HTML}{777777}
\definecolor{colorI}{HTML}{bdd6ff}
\definecolor{colorJ}{HTML}{6a9e6f}
\usepackage{pifont}
\newcommand{\cmark}{\checkmark}%
\newcommand{\xmark}{\scalebox{0.85}{\ding{53}}}%
\newcommand{\expnum}[2]{$#1\!\!\times\!\!10^{#2}$}
\newcommand{\bexpnum}[2]{\boldsymbol{\expnum{#1}{#2}}}
\newcommand\blfootnote[1]{%
\begingroup
\renewcommand\thefootnote{}\footnote{#1}%
\addtocounter{footnote}{-1}%
\endgroup
} | {'timestamp': '2022-12-01T02:21:43', 'yymm': '2211', 'arxiv_id': '2211.17263', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17263'} | arxiv |
\section{Introduction}
Modern software systems are expected to deal with changing operating conditions. Examples are dynamic workloads, fluctuating availability of services, and changes in the environment of the system. For designers, these changes create uncertainties that may be difficult to anticipate before deployment~\cite{Ramirez2012,Esfahani2013,icpe14,Mahdavi2017,Calinescu2020}. Yet, without mitigation, such uncertainties may jeopardise the concerns of the stakeholders of the system. One approach to mitigate uncertainties is self-adaptation~\cite{cheng2009software,Weyns2019}. Self-adaptation extends a system with a feedback loop that tracks the system and its environment to resolve the uncertainties and adapt the system to deal with the changing conditions, or gracefully degraded if necessary.
Over the past two decades, researchers and engineers have extensively studied the problem of how to realise self-adaptation using feedback loops~\cite{Weyns2019}.
A common approach is to equip the feedback loop with a decision-making mechanism that evaluates the relevant options for adaptation (i.e., the possible configurations of the system that are considered to adapt the system) and selects the option with the best expected outcome in terms of achieving the system goals. We refer to this as the \textit{estimated benefit} that can be achieved by self-adaptation when a particular adaptation option is selected for execution.
Consider for instance
an e-health system that remotely monitors vital parameters of elderly people and takes action when needed; for instance, change drugs, visit and support the elderly, or send an emergency team. To perform the analysis of vital parameters or dispatch health carers when needed, the system uses third-party services. The load of the system (i.e., service requests) may dynamically change in ways that may be difficult to predict; for instance, the health conditions of elderly may be affected by changing weather. To deal with such changes, the system may dynamically adapt the allocation of service requests to third-party services such that the response time of the service remains below a given threshold, while the reliability of the system is maximised. To that end, the system will estimate the benefit in terms of the values of the required quality attributes (i.e., response time and reliability in our example) for different compositions of services provided by the service providers, and then adapts the system such that it selects the best composition of services~\cite{7194661}.
A few approaches also take into account the \textit{estimated cost} for adapting the system when evaluating the options for adaptation, see for instance~\cite{5541703,VanDerDonckt2018}. In this context, we use `cost' to refer to the one-off cost to perform an adaptation of the running system.\footnote{Note that the one-off cost for adaptation contrasts with other aspects such as the financial cost for the owner to run the application, or the price that may need to be payed by users when using the service. If deemed relevant for the stakeholders, these aspects need to be considered when determining the expected benefits of adapting the system.} As an example, switching services in the e-health system may require the system to test the reliability of newly selected services before using them. Such tests require extra resources and time. The level of testing that is required may depend on the service-level agreement of the service providers of the services under test. When assessing a composition of services provided by third-parties, the system will calculate the estimated cost for testing the different newly integrated services of the composition. Hence, when making adaptation decisions, the system should not only consider the estimated benefit of the each of the adaptation options, but should also take into account the estimated cost of the different service compositions that can be selected.
Besides estimated benefit and cost, we argue that adaptation decisions should also take into account the \textit{estimated risk} the system would be exposed to if an adaption option were selected and used to adapt the running system. Considering that risk is particularly important in domains where decision-making may affect the safety and/or privacy of users, have an impact on the environment, or jeopardise ethical or legal concerns~\cite{Fischhoff2015}.
With the advancing digitisation of society and industry, these aspects apply to a wide variety of computing systems that are becoming vital for our society.
Compared to other areas where risks are taken into account in decision-making, see for instance~\cite{62930,Alali2012,6606612,holstein2018ethical}, the decision-making of self-adaptive systems is lagging behind. Yet, compared to other areas, where risk analysis is done by humans supported by tools, risk analysis in self-adaptive systems needs to be done automatically by the self-adaptive system itself within the time window that is available to take adaptation decisions. Clearly, this calls for solid preparation during system design, such that adaptation decisions that take risk into account can be made efficiently by the system during operation.
This paper aims at making a step forward towards dealing with risk in self-adaptive systems.
We illustrate the importance of considering estimated risk in the e-health system, which is an example of a valuable computing system for society. Selecting a new composition of services from different service providers may affect the privacy of the elderly people that use the services. In particular, different service providers may apply different rules regarding the collection and treatment of data from the e-health system. Hence, the selection of a particular set of services
implies a particular data privacy risk for the system users. When selecting services, the system should estimate this risk, e.g., based on the trustworthiness of the service providers.
Hence, decision-making in self-adaptation should in general take into account the estimated benefit, cost, and risk of the different options considered for adaptation.
This paper presents an architectural viewpoint for
decision-making in self-adaptive systems that takes into account estimated benefit, cost, and risk as first-class citizens.
The primary users that will benefit from the viewpoint are the software architects of self-adaptive systems. The viewpoint is structured using the template recommended by the ISO/IEC/IEEE 42010 standard~\cite{ISO2011}.
This standard defines an architecture viewpoint as ``a work product establishing the conventions for the construction, interpretation and use of architecture views to frame specific system concerns.'' An architectural viewpoint gives an architect the means to express a coherent set of concerns, the stakeholders interested in these concerns, and \emph{model kinds} (i.e., meta-models) that frame the concerns, each defining notations, modelling templates, analytical methods and possibly other operations useful on models of the model kind. A viewpoint can be instantiated for a domain at hand, resulting in a view that comprises architecture models that address the concerns framed by its governing viewpoint. As such, the viewpoint presented in this document establishes the conventions for defining and using architecture views to deal with the concerns of stakeholders for decision-making in self-adaptation by taking into account the estimated benefit, cost, and risk of adaptation options.
The viewpoint is grounded in a study of the literature and supported with extensive experiences in engineering self-adaptive systems across a wide range of domains.
\section{Scope of the Viewpoint}
\label{sec:scope}
Given the wide range of approaches used to realise self-adaptation in general, and decision-making in self-adaptive systems in particular, it is essential that we clarify the definition of the viewpoint before we present its specification.
In this work, we adopt the widely accepted conceptual definitions of architectural viewpoints and models from the IEEE 1471 and ISO/IEC 42010 standards~\cite{4278472}.
The viewpoint is centred on \emph{architecture-based adaptation}~\cite{Oreizy1999,Garlan2004,Kramer2007,Weyns2012}, which is an established approach to engineering self-adaptive systems. Architecture-based adaptation has a dual focus~\cite{weyns2020book}: on the one hand the use of software architecture as an abstraction to \emph{define} a self-adaptive system at design time, and on the other hand the use of architectural models to \emph{reason} about change and make adaptation decisions at runtime. The viewpoint presented in this paper focusses on the second aspect.
Architecture-based adaptation makes a distinction between domain concerns that are handled by the \textit{managed system}, i.e., what the system should provide to the user in terms of functions or services, and adaptation concerns that are handled by the \textit{managing system}, i.e., how the domain concerns are achieved in terms of benefits, cost, and risk. A reference approach to realise the managing system is by means of a so-called MAPE feedback loop~\cite{Kephart2003,6595487}. MAPE refers to the basic functions realised by the feedback loop: Monitor the system and its environment, Analyse the situation and the options for adaptation, Plan the adaptation of the managed system for the best option, and Execute the actions of the plan to adapt the managed system. The MAPE functions share a repository with Knowledge that typically comprises different types of runtime models~\cite{Weyns2012} (MAPE is therefore sometimes also referred to as MAPE-K). It is important to note that MAPE provides a reference model that describes the essential functions of a managing system and the interactions between them. A concrete architecture maps the functions to corresponding components, which can be a one-to-one mapping or any other mapping, such as a mapping of the analysis and planning functions to one integrated decision-making component.
The focus of the viewpoint is on the adaptation concerns, in particular the decision-making process to select a configuration from the possible configurations to adapt the system.
We refer to the set of possible configurations to select from as the \textit{adaptation options} and refer to the complete set as the \textit{adaptation space}. With \textit{relevant adaptation options} we refer to the adaptation options that are deemed to be relevant and are actually analysed, which can be the complete adaptation space or a subset of it, determined using some heuristic or selection mechanism.
The viewpoint is concerned with uncertainties related to \textit{anticipated change}, i.e., the architect has knowledge of the types of changes that may occur, but not when these changes occur and in what way they may occur~\cite{10.1145/3487921} (for instance the frequency of changes or their intensity). Decision-making in the viewpoint is defined based on abstract functions associated with the estimated benefit, cost, and risk of adaptation options. This allows to support different types of decision-making mechanisms,
for instance based on rules,
utilities, or softgoals.
The approaches used for estimating benefit, cost, and risk build on the Cost Benefit Analysis Method (CBAM)~\cite{CBAMWebsite} and the IEC 31010:2019 standard on
risk management and risk assessment techniques~\cite{RiskWebsite}.
CBAM is an established method for analysing the benefits and costs of architectural designs of software-intensive systems. CBAM takes into account the uncertainty factors regarding benefits and costs, providing a basis for informed decision-making about architectural design or upgrade. In contrast to CBAM, we require an automated approach that makes adaptation decisions for the system at runtime to deal with uncertainties.
On the other hand, the IEC 31010:2019 standard on risk management and risk assessment provides guidance on the selection and application of various techniques that take into account risk in the decision-making process when mitigating uncertainty. Whereas the standard focuses on techniques that are used to aid decision-making under uncertainty in general, in this viewpoint we require techniques that can be applied automatically by a system at runtime to make adaptation decisions under uncertainty.
\section{Running Example}
\label{sec:example}
We illustrate the different parts of the architectural viewpoint using a classic example from the literature~\cite{7194661}: the e-health system that we already used in the introduction. Consider a simple service-based system as shown in Figure~\ref{fig:example}. This system offers a remote health-assistance service to patients, and relies on data collected via wearable devices. The health-assistance service is realised by a set of specific services that are executed in a workflow as shown in the figure. The core of the application exploits resources of a cloud infrastructure. Each request of a patient instantiates a new instance of the health-assistance service workflow. This workflow then interacts with the services, following the invocation pattern defined by the workflow. A \textit{Medical Service} receives messages with values of vital parameters from the patient's health device. The service analyses the data, and depending on the analysis results nothing needs to be done or action is required. In the latter case, the medical service instructs a \textit{Drug Service} to notify a local pharmacy to deliver new medication to the patient or change the dose of medication, or it instructs an \textit{Alarm Service} in case of an emergency to request medical staff to visit the patient. The alarm service can also directly be invoked by a user via a panic button. The numbers associated with arrows in the workflow express probabilities that actions are invoked. These numbers represent uncertainties that may change over time. Each service can be implemented by a number of service providers that offer concrete services according to a service-level agreement that specifies the reliability and accuracy of the service, among other aspects. Some of the properties of services may change at runtime. For example, due to the changing workloads on the provider side or to unexpected network failures, the reliability of a service may deviate from the one specified in its service-level agreement. Each service provider also offers a privacy policy that specifies how patient data is managed.
At runtime, it is possible to pick any combination of the available services offered by the service providers. The adaptation goals that express the benefits of adaptation are to keep the average failure low, while minimising the resources required to run the e-health service. Switching services in the system may imply a cost associated with the extra resources that are required to test newly selected services before they can be used.
Given that service providers may use different privacy policies on how patient data is managed, selecting a service from a service provider implies a risk on the confidentially of the data of patients within legal constraints; e.g., kept strictly local, stored with partners, shared with partners, non-specified.
Finally, medical analysis services perform their analysis based on the measurements of a limited period using bounded computational resources, there is a risk that the diagnoses derived from the analysis results may not not be 100\% accurate. This may indirectly affect the health conditions of the patients.
\begin{figure}[h!]
\centering
\includegraphics[width=0.75\textwidth]{figures/ehealth-case.pdf}
\caption{Service-based system: system architecture and workflow instance}
\label{fig:example}
\end{figure}
\section{Specification of the Viewpoint}
\label{sec:vp}
Based on a thorough analysis of the literature~\cite{icpe14,Mahdavi2017}, a number of surveys of the community~\cite{Calinescu2020,hezavehi2021uncertainty,10.1145/3487921}, and our own experiences with developing self-adaptive systems in a variety of domains, e.g.,~\cite{8008800,WeynsI0M18,VanDerDonckt2018,Weyns2022}, we defined the architecture viewpoint for benefit-cost-risk-aware decision-making in self-adaptive systems. The viewpoint frames the essential concerns of stakeholders with an interest in the runtime decision-making of self-adaptive systems that are subject to uncertainties. In particular, the viewpoint defines a set of model kinds for identifying, designing, and realising a decision-making module for self-adaptation taking into account the estimated benefit, cost, and risk of the relevant adaptation options.
It is important to put the viewpoint in a broader context of the design of the feedback loop of a self-adaptive system. The focus of the viewpoint is on the decision-making of self-adaptation, which maps to the analysis function and the first part of the planning function (in the MAPE workflow)~\cite{weyns2020book}. The analysis function evaluates the relevant adaptation options and the first part of planning selects the best option based on the estimated values for benefit, cost, and risk of all analysed adaptation options. The planner function then determines the best option to adapt the running system. As such, architects can combine the viewpoint with additional architectural approaches, such as complementary viewpoints or patterns, to deal with other concerns of realising a self-adaptive system, such as monitoring the system and its environment, keeping runtime models up to date, generating adaptation plans, and executing the adaptation actions of a plan.
\subsection{Stakeholders and Concerns}
Table~\ref{tab:vp_overview} shows an overview of the viewpoint with the stakeholders and their concerns.
\begin{table}[!h!]
\renewcommand{\arraystretch}{1.2}
\caption{Viewpoint -- Overview, Stakeholders, and Concerns.
\label{tab:vp_overview}
\centering
\begin{tabular}{p{13.4cm} }
\toprule
\textbf{Overview:} \\The architecture viewpoint deals with the main stakeholder concerns related to the decision-making of self-adaptive systems that need to handle uncertain but anticipated changes in the environmemt, the system, and its goals. The viewpoint takes into account the estimated benefit, cost, and risk as first-class citizens when selecting adaptation options. The viewpoint offers model kinds that can be instantiated for a problem at hand. The model kinds show the relevant architectural information that is essential to guide a successful design of benefit-cost-risk-aware decision-making modules of self-adaptive systems.\\
\midrule
\textbf{Stakeholders:}\\
\emph{Architect(s)} who design the decision-making module of a self-adaptive system. \\
\emph{Owner(s)} who operate the system and offer its service to users.\\
\emph{User(s)} who use (and pay) for the service of the system. \\
\emph{Other(s)} who may be exposed to potential risks implied by the system.
\\
\midrule
\textbf{Concerns:}\\
\emph{C1 - Benefit:} What are the adaptation goals of the self-adaptive system? What are the estimated values of the quality attributes, i.e., benefit attributes, for an adaptation option that correspond with the adaptation goals? How can the adaptation goals be combined to determine the overall estimated benefit of an adaptation option?\\
\emph{C2 - Cost:} What are the different types of cost associated with performing adaptation? How can the cost for each type be quantified? How can the cost for each type be estimated for an adaptation option? How can the cost for different types be combined to determine the overall estimated cost of an adaptation option?\\
\emph{C3 - Desirability:}
How to balance benefit against cost of an adaption option in order to express its desirability? How to compare and rank desirability results? \\
\emph{C4 - Risk:} What are the relevant types of risk for the system? How can the risk for each type be quantified? How can the risk for each type be estimated for an adaptation option? How can the estimates of different types of risk be combined to determine the overall estimated risk of an adaptation option?\\
\emph{C5 - Decision-Making:} What options are available for adapting the system from the current configuration? What elements need to be considered when selecting an adaptation option to adapt the current configuration? How to balance desirability of adaptation options with estimated risk when making adaptation decisions?\\
\bottomrule
\end{tabular}
\end{table}
Stakeholders of the viewpoint are \emph{architect(s)}, \emph{owner(s)}, \emph{user(s)}, and \emph{other(s)}. Architects are primarily interested in technical aspects, in particular the design and behaviour of the decision-making module of the self-adaptive system taking into account the estimated benefit, cost, and risk. Owners have a primary interest in the benefits of the self-adaptive system, the costs that may be induced by adaptation, and the risks that may be implied by adaptations of the system.\footnote{In this viewpoint, we use the term \textit{benefit attribute} to refer to different dimensions of estimated benefit; similarly we use the terms \textit{cost attribute} and \textit{risk attribute} to refer to different dimensions of estimated cost and risk respectively.}
Architects and owners have also an interest in the desirability of system configurations; a configuration with a high desirability has a high benefit and a low cost. Users are primarily interested in the benefits provided by the self-adaptive system as well as the risks they may be exposed to.
Others are those people that may be exposed to potential risks implied by the system, directly or in the environment.
In summary, the viewpoint addresses the following adaptation concerns of the stakeholders: \emph{benefits} of adaptation (architects, owners, and users), \emph{costs} of adaptation (architects and owners), \emph{desirability} of adaptation (architects, owners), \emph{risks} implied by adaptation (architects, owners, users, and others), and \emph{decision-making} for adaptation (architects).
\vspace{5pt}\noindent
\textit{\textbf{Example.}} The architects of the health assistance system are the persons who design and oversee the realisation of the decision-making module of the feedback loop that selects adaptation options to adapt the services used by the workflow. The architects' main concern is to ensure that the system makes proper adaptation decisions, i.e., select adaptation options balancing their estimated benefit, cost, and risk. The system owners are the persons who operate the health-assistance service. The main concerns of the system owners are to provide a good service to the users, optimise the resources to operate the system, keeping the cost required for adaptation low, and minimising the exposed risks. The users are the patients that use the service via a wearable device either to analyse vital parameters or to direct alarm a medical team in case of an emergency. Their main concerns are the reliability of the service and risks in terms of data privacy and health risks of the application. Finally others are people who may be exposed to risks implied by the system directly or indirectly, in particular risks with respect to the data privacy and decisions made by the system. Others can be relatives and friends of patients, care professionals, among other people.
\subsection{Viewpoint Model Kinds}
The viewpoint comprises five model kinds. Table~\ref{tab:vp_mk} presents the first three model kinds: \emph{benefit estimation} (MK1), \emph{cost estimation} (MK2), and \emph{benefit-cost analysis} (MK3). Table~\ref{tab:vp_mk2} presents the last two model kinds: \emph{risk estimation} (MK4) and \emph{decision-making} (MK5).
Figure~\ref{fig:process} gives a high-level overview of the process to use the model kinds. The process starts with the design of the benefit estimation model using the benefit estimation model kind. This model deals with concern C1 (benefit of adaptation options). Next (or in parallel), the cost estimation model can be designed using cost estimation model kind. This model deals with concern C2 (cost of adaptation options). The next step in the process is the design of the benefit-cost estimation model. This model takes as input the benefit-cost estimation model kind, the benefit estimation model and the cost estimation model. The benefit-cost estimation model deals with concern C3 (desirability of adaptation options). Then (or in parallel), the risk estimation model is designed using the risk estimation model kind. This model deals with concern C4 (risk of adaptation options). In the last step, the decision-making model is designed. This step takes as input the decision-making model kind, the cost-benefit estimation model and the risk estimation model. The decision-making model deals with concern C5 (decision-making, i.e., selecting the best adaptation option).
\begin{figure}[h!]
\centering
\includegraphics[width=0.88\textwidth]{figures/process-ad.pdf}
\caption{Process to use model kinds.}
\label{fig:process}
\end{figure}
\begin{table}[h!t!]
\renewcommand{\arraystretch}{1.2}
\caption{Viewpoint -- Model Kinds MK1, MK2, and MK3}
\label{tab:vp_mk}
\centering
\begin{tabular}{ p{13.4cm} }
\toprule
\textbf{Model Kinds (description):}\\
\emph{MK1 - Benefit Estimation (deals with concern C1):}
describes per adaptation option how
each quality attribute is estimated based on the associated adaptation goal and what the overall estimated benefit is based on the combined adaptation goals. \\
\emph{MK2 - Cost Estimation (deals with concern C2):}
describes per adaptation option how
each cost attribute is estimated based on the associated cost metric and what the overall estimated cost is based on the combined costs metrics. \\
\emph{MK3 - Benefit-Cost Estimation (deals with concern C3):}
describes per adaptation option how
the desirability is determined based a benefit-cost analysis using the estimated benefit and estimated cost of that adaptation option.
\\
\midrule
\textbf{Model Kinds (meta-models):}
\begin{center}
\includegraphics[width=0.46\textwidth]{figures/benefit_model_kind2.pdf}
\hspace{5pt}
\includegraphics[width=0.46\textwidth]{figures/cost_model_kind2.pdf}
\end{center}
\begin{center}
\includegraphics[width=0.46\textwidth]{figures/cost_benefit_analysis_model_kind.pdf}
\end{center}
\\
\vspace{-12pt}
\emph{Key:} UML (gray boxes represent model elements shared among model kinds)\\
\bottomrule
\end{tabular}
\end{table}
\begin{table}[ht!]
\renewcommand{\arraystretch}{1.2}
\caption{Viewpoint -- Model Kinds MK4 and MK5}
\label{tab:vp_mk2}
\centering
\begin{tabular}{ p{13.4cm} }
\toprule
\textbf{Model Kinds (description):}\\
\emph{MK4 - Risk Estimation (deals with concern C4):}
describes per adaptation option how
each risk attribute is estimated based on the associated risk metric and what the overall estimated risk is based on the combined risk metrics. \\
\emph{MK5 - Decision-Making (deals with concern C5):} describes how an adaptation option is selected from the set of adaptation options to adapt the system from its current configuration based on the desirability and estimated risk of the adaptation options.\vspace{5pt}\\
\midrule
\textbf{Model Kinds (meta-models):}
\begin{center}
\includegraphics[width=0.46\textwidth]{figures/risk_model_kind.pdf}
\hspace{5pt}
\includegraphics[width=0.46\textwidth]{figures/decision-making_model_kind4.pdf}
\end{center}
\\
\vspace{-12pt}
\emph{Key:} UML (gray boxes represent model elements shared among model kinds)\\
\bottomrule
\end{tabular}
\end{table}
We explain now each model kind in detail and illustrate it with an example of the health-assistance service system. More elaborated descriptions of the core elements used on the model kinds are provided in the Appendix. \\
\noindent\textbf{Benefit Estimation Model Kind (MK1).} This model kind describes how the benefit of each relevant adaption option is estimated (see Table~\ref{tab:vp_mk} top left). The \textit{current configuration} is a representation of the aspects of the managed system and the environment that are relevant to adaptation at that time. These aspects include the current component configuration of the managed system, the settings of relevant system parameters, the values of the quality properties of interest, and the values of uncertainties that are relevant to adaptation. An \textit{adaptation option} is a possible configuration that can be reached from the current configuration by adapting the system.
An \textit{adaptation goal} represents a requirement that needs to be achieved by the managing system. Adaptation goals usually refer to quality requirements. A \textit{benefit attribute} of an adaptation option represents the estimated value for a system property of the managed system that corresponds with an adaptation goal. Benefit attributes are usually quality properties. With each benefit attribute there is one corresponding adaption goal.
A \textit{benefit estimator} is a mechanism that enables estimating the benefit attributes of the adaptation options. The \textit{estimated benefit} represents the overall estimated benefit of an adaptation option based on the estimated benefit attributes and combined adaptation goals.
\vspace{5pt}\noindent
\textit{Example.} Figure~\ref{fig:example_MK1} shows an instance of the benefit estimation model kind for the health assistance system. The current configuration consists of the workflow with a set of services currently in use, a set of properties referring to uncertainties including the actual values associated with the different paths exercised in the workflow, the current values of the failure rate and resource usage of the system, and service-level agreements. An adaptation option corresponds to a particular selection of concrete services provided by service providers to be executed by the workflow. The service-based system has two benefit attributes: failure rate and resource usage. The corresponding adaptation goals are represented at utility responses.
Figure~\ref{fig:example_urc} shows the utility response curves for both goals.
\begin{figure}[h!]
\centering
\includegraphics[height=0.35\textwidth]{figures/utility-function-example.pdf}
\caption{Example utility response curves}
\label{fig:example_urc}
\end{figure}
As shown in the left part, the utility preference for configurations with failure rates below 1\% is 100\%. For configurations with failure rates between 1 and 2\% the utility preference gradually decreases to 30\%. The utility preference of configurations with failure rates above 2\% is zero. The right part of the figure shows the utility preference for resource usage, defined in a similar way.
As an example, configuration $C_1$ has a 100\% utility preference for a failure rate of 0.5\% and 50\% for a resource usage of 18 units. Adaptation option $C_2$ has a utility preference of 85\% for a failure rate of 1.3\% and 100\% for a resource usage of 3 units. Current configuration $C_c$ on the other hand has a utility preference of 65\% for a failure rate of 1.5\% and 50\% for a resource usage of 15 units.
The utility estimator determines the estimated utilities for each relevant adaptation option. To that end, the estimator configures a runtime model of the workflow for each combination of concrete services (adaptation options) together with the actual probabilities that paths are selected. This model is then analysed by a statistical model checker that runs a number of simulations for each adaptation option. The result of the analysis is an estimate for failure rate and resource usage for each adaptation option with a required accuracy and confidence. The estimated benefit is then determined using a utility function that computes the sum of the weighted values of the estimated quality attributes for each adaptation option. Weights express the relative importance of the benefit attributes for the stakeholders.
In particular, to determine the estimated benefit for an adaptation option we take the sum of the difference between the estimated utility for that adaptation option and the utility of the current configuration for each benefit property taking into account the respective weights. As an example, the estimated benefit of adaptation options can be computed as follows:
\begin{equation}\label{eq5}
EB_{C_i}= (U_{C_i}^{F} - U_{C_c}^{F}) * W^{F} + (U_{C_i}^{R} - U_{C_c}^{R}) * W^{R}
\end{equation}
with $U_{C_i}^{F}$ the utility of adaptation option $C_i$ for failure rate $F$, $U_{C_c}^{F}$ the utility of the current configuration $C_c$ for the failure rate, and $W^F$ the weight for failure rate (in the example 0.7); the second term with a similar structure refers to resource usage $R$ (with weight 0.3). Applied to adaptation option $C_1$ in Figure~\ref{fig:example_urc} the estimated benefit is:
\begin{equation}\label{eq5}
EB_{C_1}= (100 - 65) * 0.7 + (50 - 50) * 0.3 = 24.5
\end{equation}
Similarly, the benefit of adaptation option $C_2$ in Figure~\ref{fig:example_urc} is:
\begin{equation}\label{eq5}
EB_{C_2}= (85 - 65) * 0.7 + (100 - 50) * 0.3 = 29.0
\end{equation}
In this particular case, adaptation option $C_2$ has a higher estimated benefit as adaptation option $C_1$. Hence, if an adaptation decision would be made based on estimated benefit only, adaptation option $C_2$ would be selected for adaptation.
\begin{figure}[h!]
\centering
\includegraphics[height=0.45\textwidth]{figures/benefit_model_kind_example.pdf}
\caption{Example instance of Benefit Estimation Model Kind}
\label{fig:example_MK1}
\end{figure}
\vspace{5pt}
\noindent\textbf{Cost Estimation Model Kind (MK2).}
This model kind describes how the estimated cost of applying each adaption option is determined (see Table~\ref{tab:vp_mk} top right). A \textit{cost attribute} represents a particular type of cost that is implied by adaptation of the managed system. Different cost attributes can be associated with an adaptation option, such as communication overhead implied by adaptation, extra resources required to perform adaptation, and temporal restrictions in the availability of the system functionality as a consequence of adaptation. \textit{Cost metrics} define measures to quantify cost attributes. A \textit{cost estimator} is a mechanism that enables estimating the cost attributes of the adaptation options. The \textit{estimated cost} represents the overall estimated cost of an adaptation option based on the estimated cost attributes and the combined cost metrics.
To support architects with identifying cost attributes for a problem at hand, we devised a list of cost attributes with associate cost metrics, see Table~\ref{tab:cost_dim_cost_met}. This table is based on examples extracted from the literature and our own experiences, see for instance~\cite{5541703,VanDerDonckt2018,SEAMS.2019.00023}.
We distinguish three groups of adaptation costs. The first group refers to resources that are required to realise adaptation, such as bandwidth, processor time, memory, and power. The second group relates to overhead of the system in terms of quality properties that are affected by adaptation, which can be reduced availability, a performance penalty, or costs to deal additional security vulnerabilities implied by adaptation. The third group refers to a monetary price that is implied by the realisation of adaptation. Table~\ref{tab:cost_dim_cost_met} is not meant to be exhaustive and can be easily refined or extended.
\begin{table}[htbp]
\centering
\caption{Cost attributes with cost metrics.}
\label{tab:cost_dim_cost_met}
\begin{tabular}{|c|c|c|}
\hline
\textbf{Cost type} &
\textbf{Cost attribute} & \textbf{Cost metric} \\ \hline
Resources & Communication & Required bandwidth \\ \hline
Resources & Computation & Required processing resources \\ \hline
Resources & Storage & Required memory \\ \hline
Resources & Power & Required energy \\ \hline
Overhead & Availability & Degree of reduced service \\ \hline
Overhead & Performance & Degree of degraded user experience \\ \hline
Overhead & Security & Cost to manage exposed vulnerability \\ \hline
Economic & Financial & Monetary price \\ \hline
\end{tabular}
\vspace{5pt}
\end{table}
\vspace{5pt}\noindent
\textit{Example.} Figure~\ref{fig:example_MK2} shows an instance of the cost estimation model kind
for the health assistance system. We consider one cost attribute: the tests of new services that are considered by the adaptation options~\cite{CalinescuSubmitted}. Testing overhead requires extra resources, which corresponds to computation overhead in Table~\ref{tab:cost_dim_cost_met}. The amount of testing that is needed may depend on trustworthiness of service providers. Table~\ref{tab:cost_dim_cost_met} illustrates a possible cost model.
\begin{table}[htbp]
\centering
\caption{Example cost model for e-health system with required resources for services.}
\label{tab:cost_dim_cost_met}
\begin{tabular}{|c|c|c|c|c|}
\hline
\textbf{Provider} & \textbf{SLA} & \textbf{Medical Analysis Service} & \textbf{Drug Service} & \textbf{Alarm Service} \\ \hline
SP1 & Silver & 5 & 6 & 2 \\ \hline
SP2 & Gold & 3 & 2 & 2 \\
\hline
SP3 & Bronze & 8 & 8 & 4 \\
\hline
\end{tabular}
\vspace{5pt}
\end{table}
Assume that the current configuration comprises the following set of services:
\begin{equation}\label{eq5}
C_c = \{S_{SP1}^{MAS}, S_{SP3}^{DS}, S_{SP1}^{AS}\}
\end{equation}
$MAS$ is a medical analysis service provided by service provider $SP1$, $DS$ is a drug service provided by $SP3$, and $AS$ is an alarm service provided by $SP1$. Consider now two adaptation options $C_1$ and $C_2$ composed as follows:
\begin{equation}\label{eq5}
C_1 = \{S_{SP1}^{MAS}, S_{SP2}^{DS}, S_{SP2}^{AS}\};\mbox{\ \ } C_2 = \{S_{SP1}^{MAS}, S_{SP1}^{DS}, S_{SP1}^{AS}\}
\end{equation
The estimated cost to test the adaptation option of configuration $C_1$ is: \vspace{-5pt}
\begin{equation}\label{eq6}
EC_{C_1} = cost(C_c, C_1) =
cost_{adapt}(S_{SP3}^{DS},S_{SP2}^{DS}) + cost_{adapt}(S_{SP1}^{AS},S_{SP2}^{AS}) = 2 + 2 = 4
\end{equation}
The cost only applies to $DS$ and $AS$, i.e., the services that need to be tested before they can be adapted. The cost for testing the different services can be found in Table\,\ref{tab:cost_dim_cost_met}. Similarly, t]he estimated cost to test the adaptation option of configuration $C_2$ is:
\begin{equation}\label{eq7}
EC_{C_2} = cost(C_c, C_2) = cost_{adapt}(S_{SP3}^{DS}, S_{SP1}^{DS}) = 6
\end{equation}
Despite the fact that adaptation option $C_1$ requires testing two new services and $C_2$ requires to test only one new services, the estimated cost of $C_1$ is smaller as the estimated cost of $C_2$. The reason is that the new services of $C_1$ are provided by a service provider with a gold service level agreement, requiring less extensive testing of services. In sum, if an adaptation decision would be made based on estimated cost only, adaptation option $C_1$ would be selected for adaptation.
\begin{figure}[h!]
\centering
\includegraphics[height=0.4\textwidth]{figures/cost_model_kind_example.pdf}
\caption{Example instance of Cost Estimation Model Kind}
\label{fig:example_MK2}
\end{figure}
\vspace{5pt}
\noindent\textbf{Benefit-Cost Analysis Model Kind (MK3).} This model kind describes how the \textit{estimated desirability} of each adaptation option is determined (see Table~\ref{tab:vp_mk} bottom). Estimated desirability $ED_{C_i}$ expresses the degree that stakeholders prefer the selection of an adaptation option $C_i$ over other options by comparing total estimated benefit with total estimated cost. The desirability of adaptation options increases with higher estimated benefit and lower estimated cost. The \textit{benefit-cost analyser} computes the desirability of an adaptation option. The computation of desirability requires that the estimated cost and benefit are expressed in a common metric and are scaled to be comparable. Different approaches exist to determine desirability. One common approach is so called ``Value-For-Cost'' that defines desirability as the ratio of estimated overall benefit to estimated overall cost (both scaled). Another approach subtracts the total estimated cost from the total estimated benefit to determine the desirability of an adaptation option. More advanced approaches may include regression and forecasting techniques to determine desirability.
\vspace{5pt}\noindent
\textit{Example.} Figure~\ref{fig:example_MK3} shows the benefit-cost model kind instantiated for the health assistance system. We use value-for-cost (VFC) to express the desirability of adaptation options. The value-for-cost calculator computes VFC for adaptation option $C_i$ as follows:
\begin{equation}\label{eq5}
VFC_{C_i} = \frac{s_b(EB_{C_i})}{s_c(EC_{C_i})}
\end{equation}
with $s_b$ a function that scales estimated benefit $EB_{C_i}$ and $s_c$ a function that scales the estimated cost $EC_{C_i}$. In this example, we use trivial scaling functions that return the values of the original estimates, i.e., $s_b(EB_{C_i})= EB_{C_i}$ and $s_c(EC_{C_i})= EB_{C_i}$.
Applied to the two adaptation options $C_1$ and $C_2$ that we already used to illustrate estimated benefit and estimated cost, we obtain the following values for VFC.
\begin{equation}\label{eq5}
VFC_{C_1} = \frac{24.5}{4} = 6.13;\mbox{\ \ } VFC_{C_2} = \frac{29.0}{6} = 4.83
\end{equation}
Although adaptation option $C_2$ has a higher estimated benefit as adaptation option $C_1$, the desirability of adaptation option $C_1$ in terms of value-for-cost is significantly better as for adaptation option $C_2$. The reason is that the estimated cost associated with adapting the current configuration to the new configuration is higher for adaptation option $C_2$ compared to $C_1$. Hence, if an adaptation decision would be made using value-for-cost based on estimated benefit and cost of only adaptation options $C_1$ and $C_2$, adaptation option $C_1$ would be selected for adaptation.
\begin{figure}[h!]
\centering
\includegraphics[width=0.6\textwidth]{figures/cost_benefit_analysis_model_kind_example.pdf}
\caption{Example instance of Desirability Estimation Model Kind}
\label{fig:example_MK3}
\end{figure}
\vspace{5pt}
\noindent\textbf{Risk Estimation Model Kind (MK4).} This model kind describes how the risk of each adaptation option is estimated (see Table~\ref{tab:vp_mk2} left). Risk in general refers to potential effects of uncertainties on system objectives in terms of their likelihoods and consequences (positive or negative or both)~\cite{RiskWebsite}.
A \textit{risk attribute} represents a particular type of risk that is implied by adapting the managed system with a given adaptation option. Different risk attributes can be associated with applying an adaptation option, such as safety, environment, finances, etc. \textit{Risk metrics} define measures to quantify risk attributes. A \textit{risk estimator} is a mechanism that enables estimating the risk attributes of the adaptation options. A variety of techniques have been established in different domains to estimate risks. Essential to these techniques is that they capture the stakeholders their concerns and intent~\cite{Fischhoff2015}. Example mechanisms include consequence/likelihood matrix, cause-consequence analysis, and decision-tree analysis~\cite{RiskWebsite}. These methods differ in the purpose of the assessment, the information that is requited/available, the importance of the decision, the time available to make a decision, among other criteria. Hence, the choice for a mechanism should be tailored to the context and requirements at hand. The \textit{estimated risk} represents the overall expected risk of applying an adaptation option based on the estimated risk attributes and the combined risk metrics.
Combining risk \mbox{metrics accounts for the interactions and dependencies between risks.}
To support architects with identifying risk attributes for a problem at hand, we devised a list of high-level risk attributes with associate risk metrics, see Table~\ref{tab:risk_dim_risk_met}. This table is extracted from literature on risks, including~\cite{RiskWebsite,Fischhoff2015,Elmontsri2014,BAYBUTT2015163,Alberts2002,3194710}.
\begin{table}[htbp]
\centering
\caption{Generic risk attributes with possible metrics.}
\label{tab:risk_dim_risk_met}
\begin{tabular}{|c|c|}
\hline
\textbf{Risk attribute} & \textbf{Risk metrics} \\ \hline
Health & Fatalities, aid required \\ \hline
Safety & Fatalities, aid required \\ \hline
Security & Vulnerability, impact \\ \hline
Privacy & Data loss, impact \\ \hline
Community & Outrage, damage \\ \hline
Environment & Harm, damage \\ \hline
Financial & Loss, costs \\ \hline
\end{tabular}
\end{table}
\vspace{5pt}\noindent
\textit{Example.} Figure~\ref{fig:example_MKRisk} shows an instance of the risk estimation model kind for the health assistance system with two risk attributes: risk on the confidentially of the data of patients based on exposure of data, and risk on the health of patients based on not 100\% accurate analysis results. We illustrate risk estimation for the health assistance system using a \textit{consequence/likelihood matrix}.
\begin{figure}[h!]
\centering
\includegraphics[height=0.4\textwidth]{figures/risk_model_kind_example.pdf}
\caption{Example instance of Risk Estimation Model Kind}
\label{fig:example_MKRisk}
\end{figure}
A consequence/likelihood matrix (or risk matrix) enables specifying an estimated risk according to its consequence and likelihood. The matrix requires customised scales for consequence (Y-axis) and likelihood (X-axis). A common approach is to use discrete scales with three to five points that can be qualitative or quantitative. The scales are determined based on the concerns of the stakeholders and their objectives. The scale for consequences can have positive or negative consequences.
Table~\ref{tab:risk_metric_example} gives an overview of the risk metrics for confidentially of data elicited from the stakeholders.\footnote{The metrics used in this example are inspired by examples provided in the Risk Standard IEC 31010:2019~\cite{RiskWebsite}. Yet, this is just an example for illustration purposes, a wide variety of scales and values may apply depending on the situation at hand.} For instance, a service provider with label gold will store patient data locally. Exposure of data is expected to happen rarely and if it would happen it will have a negligible effect. On the other hand, a service provider with bronze label will share patient data with partners. Consequently, exposure of data is likely and if it would happen it may lead to sensitive data loss.
\begin{table}[htbp]
\centering
\caption{Risk metrics for confidentially of data of the health assistance system.}
\label{tab:risk_metric_example}
\begin{tabular}{|c|c|c|c|}
\hline
\textbf{SP Label} & \textbf{Data Policy} & \textbf{Likelihood} & \textbf{Consequence}\\ \hline
Gold & data stored local & rarely (1/3) & negligible effect (1) \\ \hline
Silver & stored with partners & possibly (2/3) & limited impact (2) \\ \hline
Bronze & shared with partners & likely (3/3) & sensitive data loss (3) \\ \hline
No label & not specified & almost certain (4/3) & significant impact (4) \\ \hline
\end{tabular}
\end{table}
The different options of likelihood and consequence have associated values that allow to determine risk when multiple services are combined (likelihood 1/3 to 4/3, and consequence 1 to 4). We apply the following rules in the example:
\begin{equation}\label{eqlc}
LC_{C_i} = round(LS_{SPi}^{MAS} + LS_{SPi}^{DS} + LS_{SPi}^{AS})
\end{equation}
\begin{equation}\label{eq6}
CC_{C_i} = max(CS_{SPi}^{MAS}, CS_{SPi}^{DS}, CS_{SPi}^{AS})
\end{equation}\vspace{2pt}
The \textit{likelihood} of a combination of services $LC_{C_i}$ of a configuration (adaptation option) is computed by rounding the sum of the likelihood of the individual services. On the other hand, the \textit{consequence} of a combination of services $CC_{C_i}$ is determined by the maximum consequence of any of the services of the configuration.
Figure~\ref{fig:consequence-likelihood-matrix-data} shows a consequence/likelihood matrix for the risk attribute confidentially of the data. In the example, the scale for consequences for confidentiality of data in terms of ``data exposure'' have a 4-point scale from ``negligible effect'' to ``significant impact.'' Likelihood in terms of ``data exposure'' also have a 4-point scale from ``rarely'' to ``almost certain.'' Each cell of the matrix expresses the estimated risk at one of five possible levels, with level I corresponding to the lowest risk and level V the highest. A risk estimator will map each adaptation option to one cell of the matrix based on the risk metrics determined by the stakeholders (Table~\ref{tab:risk_metric_example}) and the rules defined above. As an example, adaptation option $C_2$ (with a medical analysis service, a drug service, and an alarm service all provided by provider 1) is mapped as follows:
\begin{equation}\label{eqlc}
LC_{C_2} = round(LS_{SP1}^{MAS} + LS_{SP1}^{DS} + LS_{SP1}^{AS}) = round(2/3 + 2/3 + 2/3) = 2
\end{equation}
\begin{equation}\label{eq6}
CC_{C_2} = max(CS_{SP1}^{MAS}, CS_{SP1}^{DS}, CS_{SP1}^{AS}) = max(2, 2, 2) = 2
\end{equation}\vspace{2pt}
A value of $LC_{C_2} = 2$ corresponds to likelihood of data exposure ``possibly'' and a value of $CC_{C_2} = 2$ corresponds to an estimated consequence of data exposure ``limited impact.'' As a result, the estimated risk for confidentiality of adaptation option $C_2$ is level II, i.e., $ERL_{C_2}^{Data}$ = 2 (see Figure~\ref{fig:consequence-likelihood-matrix-data}).
Likewise, adaptation option $C_1$ (with a medical analysis service provided by service provider 1, an a drug and alarm service provided by provider 2) can be mapped to likelihood ``rarely'' and consequence ``limited impact,'' with estimated risk for confidentiality
$C_1$ level I, i.e., $ERL_{C_1}^{Data}$ = 1.
\begin{figure}[h!]
\centering
\includegraphics[width=0.8\textwidth]{figures/cl-example-small2.png}
\caption{Example of a consequence/likelihood matrix for confidentially of the data.}
\label{fig:consequence-likelihood-matrix-data}
\end{figure}
In a similar way, risk metrics and a consequence/likelihood matrix can be defined for risk on the health of patients based on the accuracy of analysis results.
The overall estimated risk for each adaptation option is then determined by combining the estimated risk per risk attribute. To that end, different approaches can be applied, from basic adding or multiplying elements to providing a magnitude for a risk using a weighting factor to either the consequence or likelihood~\cite{RiskWebsite}. Regardless of the method used, it is important to ensure that the units are consistent and that the impact of a very high risk of one attribute should be treated properly as it may be ``hidden'' by very low risks of the other attributes when combined. To that end, adaptation options with estimated risks above certain thresholds may be ruled out before composing risk attributes.
Let us determine the overall estimated risk of adaptation options for the health assistance system using a weighted sum as an example. Assume we have a 4 x 4 consequence/likelihood matrix for health of patients with risk levels I to V similar to the consequence/likelihood matrix for data confidentiality. Further, assume that the estimated risk for health of patients of adaptation option $C_1$ is level II, i.e., $ERL_{C_1}^{Health}$ = 2, and the risk of adaptation option $C_2$ is $ERL_{C_2}^{Health}$ = 1. With a weight factor $W^{Data} = 0.2$ and $W^{Health} = 0.8$, the overall estimated risk can then be determined as follows:
\begin{equation}\label{eq5}
ER_{C_1}= ERL_{C_1}^{Data} * W^{Data} + ERL_{C_1}^{Health} * W^{Health} = 1 * 0.2 + 2 * 0.8 = 1.8
\end{equation}
\begin{equation}\label{eq5}
ER_{C_2}= ERL_{C_2}^{Data} * W^{Data} + ERL_{C_2}^{Health} * W^{Health} = 2 * 0.2 + 1 * 0.8 = 1.2
\end{equation}\vspace{2pt}
Hence, in this example, selecting adaptation option $C_2$ for adaptation would result in a lower estimated risk than selecting adaptation option $C_1$. Therefore, $C_2$ would be preferred over $C_1$ if only the estimate risk would matter.
\vspace{5pt}
\noindent\textbf{Decision-Making Model Kind (MK5).}
The fifth and last model kind describes how adaptation decisions are made (see Table~\ref{tab:vp_mk2} right). A \textit{decision-making mechanism} provides the means to select an adaptation option from the set of available options taking into account the estimated desirability (based on the estimated desirability analysis in terms of estimated benefit and cost), and estimated risk (based on estimated risk analysis). The \textit{selected adaption option} $C_s$ represents the new configuration that is selected to be applied to the managed system in order to adapt it. In general decision-making realises the following abstract function:
\begin{equation}\label{eq5}
C_s = select(C_c, \{(C_i, ED_{C_i}, ER_{C_i})\})
\end{equation}
$\{(C_i, ED_{C_i}, ER_{C_i})\}$ represents the set of triples of all adaptation options $C_i$ together with their associated estimated desirability $ED_{C_i}$ and estimated risk $ER_{C_i}$.
The $select$ function can be implemented in different ways, from a simple weighted combination of the parameters up to an integrated computation of benefit-cost-risk~\cite{Boardman2011} that may require additional or more detailed data.
\vspace{5pt}\noindent
\textit{Example.} Figure~\ref{fig:example_MK4} shows the decision-making model kind instantiated for the health assistance system. We illustrate decision-making using a mechanism that determines the best combination of services from the possible service configurations based on a weighted combination of estimated value-for-cost and risk.
\begin{figure}[h!]
\centering
\includegraphics[height=0.5\textwidth]{figures/decision-making_model_kind_example.pdf}
\caption{Example instance of Decision-Making Model Kind}
\label{fig:example_MK4}
\end{figure}
The $select$ function is implemented as follows:
\begin{equation}\label{eq5}
EBCR_{C_s} = \max\limits_{}\sum_{i=1}^{n} (ED_{C_i} * W_{VFC} - ER_{C_i} * W_{R})
\end{equation}
The adaptation option $C_s$ that is selected for adaption is the option that maximises the estimated benefit-cost-risk $EBCR_{C_s}$. $EBCR_{C_s}$ is computed as the difference between the weighted estimated desirability $ED_{C_i} * W_{VFC}$ and the weighted estimated risk $ER_{C_i} * W_{R}$.
The weights $W_{VFC}$ and $W_{R}$ determine the importance stakeholders put in the estimated desirability of the selected adaptation option, i.e., its value-for-cost in the health assistance system, and the estimated risk. If we assume equal weights, i.e., $W_{VFC} = 0.5$ and $W_{R} = 0.5$, and we use the values for estimated desirability and risk for $C_1$ and $C_2$ from the previous examples, the decision will be made as follows:
\begin{equation}\label{eq5}
EBCR_{C_1} = ED_{C_1} * W_{VFC} - ER_{C_1} * W_{R} = 6.13 * 0.5 - 1.8 * 0.5 = 2.17\vspace{-5pt}
\end{equation}
\begin{equation}\label{eq5}
EBCR_{C_2} = ED_{C_2} * W_{VFC} - ER_{C_2} * W_{R} = 4.83 * 0.5 - 1.2 * 0.5 = 1.81\vspace{5pt}
\end{equation}
If $C_1$ and $C_2$ would be the only two adaptation options to select from, the decision-making mechanism would select adaptation option $C_1$
over $C_2$. However, if the stakeholders would prefer different weights for estimated desirability and risk, the outcome may be different. We elaborate on this in the next section.
\subsection{Viewpoint Analysis}
The viewpoint defines two types of analysis presented in Table~
\ref{tab:analysis}: \textit{benefit-cost tradeoff analysis} and \textit{desirability-risk tradeoff analysis}.
\begin{table}[!h]
\renewcommand{\arraystretch}{1.2}
\caption{Viewpoint -- Analysis}\vspace{-5pt}
\label{tab:analysis}
\centering
\begin{tabular}{ p{13.4cm} }
\toprule
\textbf{Analyses:}\\
\textit{A1 - Benefit-Cost Tradeoff Analysis (using MK3):} Assesses the effects of different weights for benefit and cost on the overall estimated desirability of adaptation options of a given configuration with a given benefit-cost analysis mechanism.\\
\textit{A2 - Desirability-Risk Tradeoff Analysis (using MK5):} Assesses
the effects of different weights for desirability and risk on the selection of adaptation options of a given current configuration with a given decision-making mechanism. \\
\bottomrule
\end{tabular}
\end{table}
\vspace{5pt}
\noindent\textbf{Benefit-Cost Tradeoff Analysis.}
This analysis is applied to a selection of relevant adaptation scenarios, each comprising a current configuration with a selection of adaptation options. The analysis then assesses the effects of assigning different weights to the estimated benefit and estimated cost on the desirability of the adaptation options. The results can then be checked with domain knowledge obtained from stakeholders, historical information, field tests, or any other relevant data sources. The analysis results help balancing the tradeoffs between estimated benefit and estimated cost when designing the benefit-cost analyser. This analysis is usually performed at design time, but may also be useful in the context of a system evolution; for instance when new goals or risks are identified that need to be incorporated into the self-adaptive system.
\vspace{5pt}
\noindent\textit{Example.}
We illustrate benefit-risk tradeoff analysis for the simple scenario of the health assistance system that we used to illustrate the benefit-cost model kind. In that example we used trivial scaling functions that return the values of the original estimates for benefit and cost, i.e., $s_b(EB_{C_i})= EB_{C_i}$ and $s_c(EC_{C_i})= EB_{C_i}$ and we applied that to determine estimated VFC of two adaptation options ($C_1$ and $C_2$).
We look now how a parametric scaling function for benefit gives preference to adaptation options with high benefit as follows:
\begin{equation}\label{eq5}
VFC_{C_i} = \frac{T + (EB_{C_i} - T) * x}{EC_{C_i}}
\end{equation}
The scaling function of estimated benefit is determined based on $T$, a threshold for estimated benefit, and a multiplier $x$. The scaling function of estimated cost remains trivial, returning the values of the original estimates for cost. The overall estimated benefit of an adaptation option is determined by making the sum of the threshold and the fraction of the estimate above the threshold multiplied with a factor $x$.
Figure~\ref{fig:example_decision_weigths} shows how estimated value-for-cost ($VFC_{C_i}$) is determined for two adaptation options $C_1$ and $C_2$.
\begin{figure}[h!]
\centering
\includegraphics[height=0.4\textwidth]{figures/VFC-example.pdf}
\caption{Change of desirability (VFC) based on weights for estimated benefit and cost.}
\label{fig:example_VFC}
\end{figure}
In this particular setting, threshold $T$ is set to 25 and $x$ is changed in a range from 1 to 10. Note that the setting with $x = 1$ corresponds to the original setting we used to illustrate the desirability model kind ($VFC_{C_1} = 6.13$ and $VFC_{C_2} = 4.83$).
As we can see, for values of $x$ equal or smaller than $3.9$ the value-for-cost of adaptation option $C_1$ would be preferred over that of $C_2$. For the complementary range of values the opposite choice would be preferred. This means that above $x = 3.9$ the higher contribution of estimated benefit of $C_2$ above the threshold (namely 29.0 compared to 24.5 for $C_1$), would compensate the higher cost (6 for $C_2$ versus 4 for $C_1$). The final choice for the threshold and multiplication factor $x$ is something the stakeholders need to make.
\vspace{5pt}
\noindent\textbf{Desirability-Risk Tradeoff Analysis.}
This analysis is applied to a selection of relevant adaptation scenarios, each comprising a configuration and a set of adaptation options. The analysis assesses the effects of assigning different weights to estimated desirability and risk on the selection of adaptation options by the decision-making mechanism. The results can then be compared with domain knowledge. The analysis results help balancing estimated desirability (based on estimated benefit and cost) and estimated risk in the decision-making process. The results will help determining the knowledge required by the decision-making mechanism. Desirability-risk tradeoff analysis is usually performed at design time, but it can also be useful during system evolution.
\vspace{5pt}
\noindent\textit{Example.}
We illustrate the desirability-risk tradeoff analysis for the simple scenario of the health assistance system that we used to illustrate the decision making model kind. In that example we assumed equal weights, i.e., $W_{VFC} = 0.5$ and $W_{R} = 0.5$ to select one of two possible adaptation options ($C_1$ and $C_2$).
We look now how a change of the weights have an effect on the decision-making. Figure~\ref{fig:example_decision_weigths} shows how estimated desirability-risk of the two adaptation options ($EBCR_{C_1}$ and $EBCR_{C_2}$) change with different weights.
For values of $W_{VFC}$ equal or smaller than threshold X (e.g., 0.31 and hence, values of $W_{R}$ approximately equal or larger than 0.69) adaptation option $C_2$ would be preferred over $C_1$.This means, the stakeholders would give much more attention to risk as to desirability in terms of value-for-cost. For the complementary range of values for the weights the opposite choice would be made. The final choice for the weights is something the stakeholders need to make.
\begin{figure}[h!]
\centering
\includegraphics[height=0.4\textwidth]{figures/decision-making-example.pdf}
\caption{Changing decision based on weights for estimated desirability (VFC) and risk.}
\label{fig:example_decision_weigths}
\end{figure}
\section{Conclusion}
\label{sec:concl}
In this paper, we presented a specification of an architecture viewpoint for benefit-cost-risk-aware decision-making in self-adaptive systems, aligned with ISO/IEC/IEEE 42010. The viewpoint is intended to address the concerns of architects, system owners, users and other stakeholders of self-adaptive systems. The novelty of the viewpoint lays in the combination of estimated benefit, cost, and risk as first-class citizens in the decision-making process to select configurations to adapt the system. We devised the viewpoint to be flexible in the mechanisms used to make different decisions. The viewpoint is also intended to be compatible with other architectural approaches that are required to design other aspects of a self-adaptive system, such as monitoring of the system and its environment, the generation of plans, and the execution of these plans to enact adaptations.
\bibliographystyle{ACM-Reference-Format}
\bibliographystyle{splncs04}
| {'timestamp': '2022-12-01T02:20:45', 'yymm': '2211', 'arxiv_id': '2211.17218', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17218'} | arxiv |
\section{Introduction}
\label{sec:intro}
Variational autoencoders (VAEs) \cite{kingma14} are deep latent generative models which have been popularly used in various domains of data such as images, natural language and sound \cite{gulrajani17, gregor15, bowman15, chung15, roberts18}. VAEs introduce an amortized inference network (\textit{i.e}\onedot} \def\Ie{\textit{I.e}\onedot an \textit{encoder}) to approximate the posterior distribution of latent variable $\z$ and maximize the evidence lower-bound (ELBO) of the data.
However, the two major limitations of VAEs are: (1) the constrained expressiveness of the fully-factorized Gaussian posterior assumption and (2) the amortization error \cite{cremer18} of the inference model due to the dynamic posterior prediction.
There have been various attempts to address these problems. A representative line of works belongs to the category of normalizing flows \cite{rezende15, kingma16, tomczak16}, which apply a chain of invertible transformation with tractable densities in order to represent a more flexible posterior distribution.
However, not only do they incur additional parameter overhead for the inference model but are yet prone to the amortization error as they entirely depend on the dynamic inference.
Recently, iterative approaches based on gradient-based refinement of the posterior parameters have been proposed \cite{krishnan18, kim18, marino18}.
These methods aim to reduce the amortization error by augmenting the dynamic inference with an additional inner-loop optimization of the posterior.
Nonetheless, they still rely on the fully-factorized Gaussian assumption, and accordingly fail to enhance the expressiveness of the posterior.
We develop a novel approach that tackles both challenges by (1) iteratively updating the mode of the approximate posterior and (2) defining a full-covariance Gaussian posterior centered on the mode, whose covariance is determined by the local behavior of the generative network. By deducing the approximate posterior directly from the generative network, not only are we able to minimize the amortization error but also model the rich correlations between the latent variable dimensions.
We start from the class of neural networks of rectified linear activations (\textit{e.g.} ReLU) \cite{montufar14, pascanu14} and Gaussian output, which is universally popular for modeling continuous data such images \cite{krizhevsky12, gregor15} and also as a building block of deep latent models \cite{rezende14, sonderby16}.
Subsequently, we present a generalized framework named \textit{Variational Laplace Autoencoders} (VLAEs), which encompasses the general class of differentiable neural networks.
We show that the ReLU networks are in fact a special case of VLAEs that admits efficient computation. In addition, we illustrate an example for Bernoulli output networks.
In summary, the contributions of this work are as follows:
\begin{itemize}
\item We relate Gaussian output ReLU networks to probabilistic PCA \cite{tipping99} and thereby derive an iterative update for finding the mode of the posterior and a full-covariance Gaussian posterior approximation at the mode.
\item We present \textit{Variational Laplace Autoencoders} (VLAEs), a general framework for training deep generative models based on the \textit{Laplace approximation} of the latent variable posterior. VLAEs not only minimize the amortization error but also provide the expressive power of full-covariance Gaussian, with no additional parameter overhead for the inference model. To the best of our knowledge, this work is the first attempt to apply the Laplace approximation to the training of deep generative models.
\item We evaluate our approach on five benchmark datasets of MNIST,
Omniglot,
Fashion-MNIST,
SVHN and
CIFAR-10.
Empirical results show that VLAEs bring significant improvement over other recent amortized or iterative approaches, including VAE \cite{kingma14}, semi-amortized VAE \cite{kim18, marino18, krishnan18} and VAE with Householder Flow \cite{tomczak16}.
\end{itemize}
\section{Background}
\label{sec:background}
\subsection{Variational Autoencoders}
\label{sec:vae}
For the latent variable model $p_{\vtheta}(\x, \z) = p_{\vtheta}(\x|\z) p(\z)$, variational inference (VI) \cite{hinton1993, waterhouse1996, jordan1999} fits an approximate distribution $q(\z; \vct{\lambda})$ to the intractable posterior $p_{\vtheta}(\z|\x)$ and maximizes the \textit{evidence lower-bound} (ELBO):
\begin{align}
\mathcal{L}_{\vtheta}(\x; \vct{\lambda})
&= \mathbb{E}_{q(\z; \vct{\lambda})}[\ln p_{\vtheta}(\x, \z) - \ln q(\z; \vct{\lambda})] \\
&= \ln p_{\vtheta}(\x) - D_{KL}(q(\z; \vct{\lambda})||p_{\vtheta}(\z|\x)) \label{eq:elbo_gap} \\
&\le \ln p_{\vtheta}(\x),
\end{align}
where $q(\z; \vct{\lambda})$ is assumed to be a simple distribution such as diagonal Gaussian and $\vct{\lambda}$ is the variational parameter of the distribution (\textit{e.g.} the mean and covariance).
The learning involves first finding the optimal variational parameter $\vct{\lambda}^*$ that minimizes the variational gap $D_{KL}(q(\z; \vct{\lambda})||p_{\vtheta}(\z|\x))$ between the ELBO and the true marginal log-likelihood, and then updating the generative model $\vct{\theta}$ using $\mathcal{L}_{\vtheta}(\x; \vct{\lambda}^*)$.
Variational autoencoders (VAE) \cite{kingma14} amortize the optimization problem of $\vct{\lambda}$ using the inference model $\vphi$ that dynamically predicts the approximate posterior as a function of $\x$:
\begin{align}
\mathcal{L}_{\vtheta, \vphi}(\x)
&= \mathbb{E}_{q_{\vphi}(\z|\x)}[\ln p_{\vtheta}(\x, \z) - \ln q_{\vphi}(\z|\x)]. \label{eq:elbo}
\end{align}
The generative model (\textit{decoder}) and the inference model (\textit{encoder}) are jointly optimized.
While such amortized variational inference (AVI) is highly efficient, there remain two fundamental challenges: (1) the limited expressiveness of the approximate posterior and (2) the amortization error, both of which will be discussed in the following sections.
\subsection{Limited Posterior Expressiveness}
\label{sec:limited_express}
VAEs approximate the posterior with the fully-factorized Gaussian $q_{\vphi}(\z|\x) = \mathcal{N}(\vct{\mu}_{\vphi}(\x), \text{diag}(\vct{\sigma}^2_{\vphi}(\x))$.
However the fully-factorized Gaussian may fail to accurately capture the complex true posterior distribution, causing the \textit{approximation error} \citep{cremer18}.
As the ELBO (Eq.(\ref{eq:elbo})) tries to reduce the gap $D_{KL}(q_{\vphi}(\z|\x)||p_{\vtheta}(\z|\x))$,
it will force the true posterior $p_{\vtheta}(\z|\x)$ to match the fully-factorized Gaussian $q_{\vphi}(\z|\x)$, which negatively affect the capacity of the generative model \cite{mescheder17}.
Hence, it is encouraged to use more expressive families of distributions; for example, one natural expansion is to model the full-covariance matrix $\mat{\Sigma}$ of the Gaussian. However, it requires $O(D^2)$ variational parameters to be predicted, placing a heavy burden on the inference model.
Normalizing flows \cite{rezende15, kingma16, tomczak16} approach this issue by using a class of invertible transformations whose densities are relatively easy to compute.
However, the flow-based methods have drawbacks in that they incur additional parameter overhead for the inference model and are prone to the amortization error described below.
\subsection{The Amortization Error}
\label{sec:amortization_error}
Another problem of VAEs stems from the nature of amortized inference where the variational parameter $\vct{\lambda}$ is not explicitly optimized, but is dynamically predicted by the inference model. The error of the dynamic inference is referred to as the \textit{amortization error} and is closely related to the performance of the generative model \cite{cremer18}.
The suboptimal posterior predictions loosen the bound in the ELBO (Eq.(\ref{eq:elbo_gap})) and result in biased gradient signals flowing to the generative parameters.
Recently, \citet{kim18} and \citet{marino18} address this issue by iteratively updating the predicted variational parameters using gradient-based optimization.
However, they still rely on the fully-factorized Gaussian assumption, limiting the expressive power of the posterior.
\begin{figure}[t]
\vskip 0.05in
\begin{center}
\centerline{\includegraphics[width=0.8\columnwidth]{figures/piece_wise_linear_manifold}}
\caption{VAE's manifold learned on 2D toy data using a 1D latent variable. The VAE with rectified linear activation learns a piece-wise linear manifold and locally performs probabilistic PCA.}
\label{fig:toy}
\end{center}
\vskip -0.2in
\end{figure}
\section{Approach}
\label{sec:proposal}
We first describe probabilistic PCA (section \ref{sec:ppca}) and piece-wise linear ReLU networks (section \ref{sec:plnn}). Based on the local linearity of such networks, we derive an iterative approach to find the mode of the posterior and define a full-covariance Gaussian posterior at the mode (section \ref{sec:iterative_inference}). Finally, we present a general framework for training deep generative models using the Laplace approximation of the latent variable posterior (section \ref{sec:vlae}).
\subsection{Probabilistic PCA}
\label{sec:ppca}
Probabilistic PCA \cite{tipping99} relates latent variable $\z$ to data $\x$ through linear mapping $\W$ as
\begin{align}
p(\z) &= \mathcal{N}(\vct{0}, \I), \\
p_{\vtheta}(\x|\z) &= \mathcal{N}(\mat{W} \z + \vct{b}, \sigma^2 \I),
\end{align}
where $\mat{W}, \vct{b}, \sigma$ are the parameters to be learned.
Note that this is basically a \textit{linear} version of VAEs.
Under this particular model, the posterior distribution of $\z$ given $\x$ can be computed in a closed form \cite{tipping99}:
\begin{align}
p_{\vtheta}(\z|\x) &= \mathcal{N}(\frac{1}{\sigma^2} \mat{\Sigma} \W^T (\x - \vct{b}), \mat{\Sigma}), \label{eq:pca}\\
\text{ where } \mat{\Sigma} &= (\frac{1}{\sigma^2} \W^T \W + \I)^{-1}. \label{eq:pca_sigma}
\end{align}
\subsection{Piece-wise Linear Neural Networks}
\label{sec:plnn}
Consider a following ReLU network $\vct{y} = g_{\vtheta}(\z)$:
\begin{alignat}{3}
&\h_{l+1} &&= \relu(\W_{l} \h_{l} + \vct{b}_{l}), \text{ for } l=0, \dots, L-1 \\
&\vct{y} &&= \W_L \h_L + \vct{b}_L, \label{eq:relu_network}
\end{alignat}
where $\h_{0} = \z$, $\relu(\x) = \max(\vct{0}, \x)$ and $L$ is the number of layers.
Our motivation is based on the observation that neural networks of rectified linear activations (\textit{e.g}\onedot} \def\Eg{\textit{E.g}\onedot ReLU, Leaky ReLU, Maxout) are \textit{piece-wise linear} \cite{pascanu14, montufar14}. That is, the network segments the input space into linear regions within which it locally behaves as a linear function:
\begin{align}
g_{\vtheta}(\z+\vct{\epsilon}) \approx \W_{\z} (\z + \vct{\epsilon}) + \vct{b}_{\z}, \label{eq:local_linearity}
\end{align}
where the subscripts denote the dependence on $\z$.
To see this, note that applying a ReLU activation is equivalent to multiplying a corresponding mask matrix $\mat{O}$:
\begin{align}
\relu(\W \x + \vct{b}) = \mat{O} (\W \x + \vct{b}) \label{eq:relu_mask},
\end{align}
where $\mat{O}$ is a diagonal matrix whose diagonal element $o_i$ defines the activation pattern \cite{pascanu14}:
\begin{align}
o_{i} =
\begin{cases}
1 \qquad \text{ if } \vct{w}_i^T \x + b_i > 0, \\
0 \qquad \text{ otherwise. }
\end{cases} \label{eq:relu_mask2}
\end{align}
The set of input $\x$ that satisfies the activation pattern $\{o_i\}_{i=1}^d$ such that $\{\x \,|\, \mathbb{I}(\vct{w}_i^T \x + b_i > 0) = o_i, \text{ for } i=1, \dots, d\}$ defines a convex polytope as it is an intersection of half-spaces. Accordingly, within this convex polytope the mask matrix $\mat{O}$ is constant.
We can obtain $\W_{\z}$ and $\vct{b}_{\z}$ in Eq.(\ref{eq:local_linearity}) by computing the activation masks during the forward pass and recursively multiplying them with the network weights:
\begin{align}
\vct{y}
&= \W_L \relu(\W_{L-1} \h_{L-1} + \vct{b}_{L-1}) + \vct{b}_L \label{eq:linear_map_start} \\
&= \W_L \mat{O}_{L-1} (\W_{L-1} \h_{L-1} + \vct{b}_{L-1}) + \vct{b}_L \\
&= \W_L \mat{O}_{L-1} \W_{L-1} \cdots \mat{O}_{0} \W_{0} \z + \dots \label{eq:linear_map1} \\
&= \mat{W}_{\z} \z + \vct{b}_{\z}. \label{eq:linear_map2}
\end{align}
Note that $\W_{\z}$ is the Jacobian of the network $\partial g_{\vtheta}(\z) / \partial \z$. Similar results apply to other kinds of piece-wise linear activations such as Leaky ReLU~\cite{maas13} and MaxOut~\cite{goodfellow13}.
\subsection{Posterior Inference for Piece-wise Linear Networks}
\label{sec:iterative_inference}
Consider the following nonlinear latent generative model:
\begin{align}
p(\z) &= \mathcal{N}(\vct{0}, \I), \label{eq:model1}\\
p_{\vtheta}(\x|\z) &= \mathcal{N}(g_{\vtheta}(\z), \sigma^2 \I), \label{eq:model2}
\end{align}
where $g_{\vtheta}(\z)$ is the ReLU network. In general, such nonlinear model does not allow the analytical computation of the posterior. Instead of using the amortized prediction $q_{\vphi}(\z|\x) = \mathcal{N}(\vct{\mu}_{\vphi}(\x), \text{diag}(\vct{\sigma}^2_{\vphi}(\x))$ like VAEs, we present a novel approach that exploits the piece-wise linearity of generative networks.
The results in the previous section hints that the ReLU network $g_{\vtheta}(\z)$ learns the piece-wise linear manifold of the data as illustrated in Fig.\ref{fig:toy}, meaning that the model is locally equivalent to the probabilistic PCA. Based on this observation, we propose a new approach for posterior approximation which consists of two parts: (1) find the mode of posterior where probability density is mostly concentrated, and (2) apply local linear approximation of the generative network (Eq.(\ref{eq:local_linearity})) at the mode and analytically compute the posterior using the results of probabilistic PCA (Eq.(\ref{eq:pca})). Algorithm \ref{alg:inference} outlines the proposed method.
\begin{algorithm}[t]
\caption{Posterior inference for piece-wise linear nets}
\label{alg:inference}
\begin{algorithmic}
\STATE {\bfseries Input:} data $\x$, piece-wise linear generative network $g_{\vtheta}$, \\
inference network $\text{enc}_{\vphi}$, update steps $T$, decay $\alpha_t$
\STATE {\bfseries Output:} full-covariance Gaussian posterior $q(\z|\x)$
\STATE $\vct{\mu}_0 = \text{enc}_{\vphi}(\x)$
\FOR{$t=0$ {\bfseries to} $T-1$}
\STATE Compute linear approximation $g_{\vtheta}(\z) \approx \W_{t} \z + \vct{b}_{t}$
\STATE $\mat{\Sigma}_t \leftarrow (\sigma^{-2} \W_t^T \W_t + \I)^{-1}$
\STATE $\vct{\mu}' \leftarrow \sigma^{-2} \mat{\Sigma}_{t} \W_{t}^T (\x - \vct{b}_{t})$
\STATE $\vct{\mu}_{t+1} \leftarrow (1 - \alpha_t) \vct{\mu}_t + \alpha_t \vct{\mu}'$
\ENDFOR
\STATE Compute linear approximation $g_{\vtheta}(\z) \approx \W_{T} \, \z + \vct{b}_{T}$
\STATE $\mat{\Sigma}_T \leftarrow (\sigma^{-2} \W_T^T \W_T + \I)^{-1}$
\STATE $q(\z|\x) \leftarrow \mathcal{N}(\vct{\mu}_T, \mat{\Sigma}_T)$
\STATE {\bfseries Return} $q(\z|\x)$
\end{algorithmic}
\end{algorithm}
We derive an update equation for the posterior mode exploiting the local linearity of ReLU networks. The results of probabilistic PCA (Eq.(\ref{eq:pca})) leads to the solution for the posterior mode under the linear model $\vct{y} = \W \z + \vct{b}$. Based on this insight, we first assume linear approximation to the generative network $g_{\vtheta}(\z) \approx \W_{t} \z + \vct{b}_{t}$ at the current estimate $\vct{\mu}_t$ at step $t$ and update our mode estimate using the solution (Eq.(\ref{eq:pca})) under this linear model:
\begin{align}
\vct{\mu}_{t+1} &= \frac{1}{\sigma^2} \mat{\Sigma}_{t} \W_{t}^T (\x - \vct{b}_{t}), \label{eq:update_equation}
\end{align}
where $\mat{\Sigma}_{t}$ is defined as in Eq.(\ref{eq:pca_sigma}).
To take advantage of the efficiency of the amortized inference, we initialize the estimate using an inference model (encoder) as $\vct{\mu}_0 = \text{enc}_{\vphi}(\x)$ and iterate the update (Eq.(\ref{eq:update_equation})) for $T$ steps. Fig. \ref{fig:iterative_inference_toy} illustrates the process of iterative mode updates.
We find that smoothing the update with decay $\alpha_t < 1$ improves the stability of the algorithm:
\begin{align}
&\vct{\mu}_{t+1} = (1 - \alpha_t) \vct{\mu}_t + \alpha_t \vct{\mu}' \label{eq:update} \\
&\text{ where } \vct{\mu}' = \frac{1}{\sigma^2} \mat{\Sigma}_{t} \W_{t}^T (\x - \vct{b}_{t}).
\end{align}
Finally, by assuming the linear model $g_{\vtheta}(\z) \approx \W_{T} \, \z + \vct{b}_{T}$ at $\vct{\mu}_T$, the approximate Gaussian posterior is defined:
\begin{align}
\label{eq:new_post_approx}
q(\z|\x) &= \mathcal{N}(\vct{\mu}_T, \mat{\Sigma}_{T}), \\
\text{ where } \mat{\Sigma}_T &= (\frac{1}{\sigma^2} \W^T_T \W_T + \I)^{-1}.
\end{align}
We train our model by optimizing the ELBO in Eq.(\ref{eq:elbo}) by plugging in $q(\z|\x)$ of Eq.(\ref{eq:new_post_approx}). For sampling from the multivariate Gaussian and propagating the gradient to the inference model, we calculate the Cholesky decomposition $\mat{L} \mat{L}^T = \mat{\Sigma}_T$ and apply the reparameterization $\z = \vct{\mu} + \mat{L} \vct{\epsilon}$, where $\vct{\epsilon}$ is the standard Gaussian noise.
We highlight the notable characteristics of our approach:
\begin{itemize}
\item We iteratively update the posterior mode rather than solely relying on the amortized prediction. This is in spirit similar to semi-amortized inference \cite{kim18,marino18,krishnan18}, but critical differences are: (1) our method can make large jumps than prevalent gradient-based methods by exploiting the local linearity of the network, and (2) it is efficient and deterministic since it require no sampling during updates. Fig. \ref{fig:iterative_inference} intuitively depicts these effects.
\item We gain the expressiveness of the full-covariance Gaussian posterior (Fig \ref{fig:covariance})
where the covariance is analytically computed from the local behavior of the generative network.
This is in contrast with normalizing flows \cite{rezende15, kingma16, tomczak16} which introduce extra parameter overhead for the inference model and hence are prone to the amortization error.
\end{itemize}
\begin{figure}[t]
\begin{center}
\centerline{\includegraphics[width=\columnwidth]{figures/iterative_inference_toy}}
\caption{Illustration of the iterative update (Eq.(\ref{eq:update_equation}))\protect\footnotemark for the posterior mode, drawn on the data space.
(a) The posterior mode $\vct{\mu}^*$ corresponds to the best reconstruction $\hat{\x}^*$ of data $\x$ on the network manifold, \textit{i.e}\onedot} \def\Ie{\textit{I.e}\onedot $\hat{\x}^* = g_{\vtheta}(\vct{\mu}^*)$.
$\hat{\x}_t$ shows the estimate at step $t$.
(b) We apply linear approximation to the network (dashed line).
(c) We solve for $\vct{\mu}_{t+1}$ under this linear model (Eq.(\ref{eq:update_equation})). The network warps the result according to its manifold (dotted arrow).
(d) Updated estimate. $\hat{\x}_{t+1}$ is now closer to $\hat{\x}^*$ than previous $\hat{\x}_t$.
}
\label{fig:iterative_inference_toy}
\end{center}
\vskip -0.2in
\end{figure}
\footnotetext{We here assume $\sigma^2 \rightarrow 0$ for the purpose of illustration. For $\sigma^2 > 0$, the prior shrinks the mode toward zero.}
\begin{figure}[t]
\begin{center}
\centerline{\includegraphics[width=0.8\columnwidth]{figures/optimization_surface_print}}
\caption{Illustration of the iterative mode update (Eq.(\ref{eq:update_equation})) on the ELBO landscape. The models are trained on MNIST using 2-dim latent variable. The update paths for the posterior mode $\vct{\mu}$ are depicted for five steps. The VLAE obtains the closest estimate, making large jumps during the process for faster convergence.
}
\label{fig:iterative_inference}
\end{center}
\vskip -0.2in
\end{figure}
\begin{figure}[h]
\begin{center}
\centerline{\includegraphics[width=\columnwidth]{figures/covariances_row}}
\caption{The covariance matrix of $q(\z|\x)$ from four different models. (a) VAE \citep{kingma14}. (b) Semi-Amortized VAE \cite{kim18}. (c) Householder Flow \cite{tomczak16}. (d) VLAE. While the former two only model diagonal elements, the latter two can model the full-covariance. The VLAE captures the richest correlations between dimensions.}
\label{fig:covariance}
\end{center}
\vskip -0.2in
\end{figure}
\subsection{Variational Laplace Autoencoders}
\label{sec:vlae}
So far, the proposed approach assumes the neural networks with rectified linear activations and Gaussian output. We here present a general framework \textit{Variational Laplace Autoencoders} (VLAE), which are applicable to the general class of differentiable neural networks. To estimate the posterior $p_{\vtheta}(\z|\x)$, VLAEs employ the \textit{Laplace approximation} \cite{bishop06} that finds a Gaussian approximation based on the local curvature at the posterior mode.
We present how the Laplace method is incorporated for training deep generative models, and show the model in section \ref{sec:iterative_inference} is a special case of VLAEs where it admits efficient computations.
Consider the problem of approximating the posterior $p_{\vtheta}(\z|\x)$ where we only have access to the unnormalized density $p_{\vtheta}(\x, \z)$. The Laplace method finds a Gaussian approximation $q(\z|\x)$ centered on the mode of $p_{\vtheta}(\z|\x)$ where the covariance is determined by the local curvature of $\log p_{\vtheta}(\x, \z)$. The overall procedure is largely divided into two parts: (1) finding the mode of posterior distribution and (2) computing the Gaussian approximation centered at the mode.
First, we iteratively search for the mode $\vct{\mu}$ of $p_{\vtheta}(\z|\x)$ via
\begin{align}
\nabla_{\z} \log p_{\vtheta}(\x, \z) \rvert_{\z=\vct{\mu}} = \vct{0}. \label{eq:mode}
\end{align}
We can generally apply gradient-based optimization for this purpose.
After determining the mode, we run the second-order Taylor expansion centered at $\vct{\mu}$:
\begin{align}
&\log p_{\vtheta}(\x, \z) \approx \log p_{\vtheta}(\x, \vct{\mu}) - \frac{1}{2} (\z - \vct{\mu})^T \mat{\Lambda} (\z - \vct{\mu}), \\
&\text{ where } \mat{\Lambda} = - \nabla_{\z}^2 \log p_{\vtheta}(\x, \z) \rvert_{\z=\vct{\mu}}.
\end{align}
As this form is equivalent to Gaussian distribution, we define the approximate posterior as
\begin{align}
&q(\z|\x) = \mathcal{N}(\vct{\mu}, \mat{\Sigma}), \\
&\text{ where } \mat{\Sigma}^{-1} = \mat{\Lambda} = - \nabla_{\z}^2 \log p_{\vtheta}(\x, \z) \rvert_{\z=\vct{\mu}}.
\end{align}
This posterior distribution is then used to estimate the ELBO in Eq.(\ref{eq:elbo}) for training the generative model. Alg. \ref{alg:vlae} summarizes the proposed framework.
\begin{algorithm}[tb]
\caption{Variational Laplace Autoencoders}
\label{alg:vlae}
\begin{algorithmic}
\STATE {\bfseries Input:} generative model $\vtheta$, inference model $\vphi$
\STATE Sample $\x \sim p_{\text{data}}(\x)$
\STATE Initialize $\vct{\mu}$ = $\text{enc}_{\vphi}(\x)$
\FOR{$t=0$ {\bfseries to} $T-1$}
\STATE Update $\vct{\mu}$ (e.g. using gradient descent)
\ENDFOR
\STATE $\mat{\Sigma} \leftarrow (-\nabla^2_{\z} \ln_{\vtheta} p(\x, \z)|_{\z=\vct{\mu}})^{-1}$
\STATE $q(\z|\x) \leftarrow \mathcal{N}(\vct{\mu}, \mat{\Sigma})$
\STATE Sample $\vct{\epsilon} \sim \mathcal{N}(\vct{0}, \I)$
\STATE Compute the Cholesky decomposition $\mat{L}\mat{L}^T = \mat{\Sigma}$
\STATE $\z \leftarrow \vct{\mu} + \mat{L} \vct{\epsilon}$
\STATE Estimate the ELBO: $\mathcal{L}_{\vtheta, \vphi}(\x)= \ln p_{\vtheta}(\x, \z) - \ln q_{\vphi}(\z|\x)$
\STATE Update generative model: $\vtheta \leftarrow \vtheta + \alpha \nabla_{\vtheta} \mathcal{L}_{\vtheta, \vphi}(\x)$
\STATE Update inference model: $\vphi \leftarrow \vphi + \alpha \nabla_{\vphi} \mathcal{L}_{\vtheta, \vphi}(\x)$
\end{algorithmic}
\end{algorithm}
\textbf{Gaussian output ReLU networks}. We now make a connection to the approach in section \ref{sec:iterative_inference}. For the generative model defined in Eq.(\ref{eq:model1})--(\ref{eq:model2}), the joint log-likelihood is
\begin{align}
&\log p_{\vtheta}(\x, \z) \nonumber \\
&= -\frac{1}{2 \sigma^2}(\x - g_{\vtheta}(\z))^T (\x - g_{\vtheta}(\z)) - \frac{1}{2} \z^T \z + C,
\end{align}
where $C$ is a constant independent of $\z$. Taking the gradient with respect to $\z$ and setting it to zero,
\begin{align}
\nabla_{\z} \log p_{\vtheta}(\x, \z) = -\frac{1}{\sigma^2} \frac{\partial g_{\vtheta}(\z)^T}{\partial \z} (g_{\vtheta}(\z) - \x) - \vct{z} = \vct{0}. \nonumber
\end{align}
By assuming linear approximation $g_{\vtheta}(\z) \approx \W_{\z} \z + \vct{b}_{\z}$ (Eq.(\ref{eq:local_linearity})) and plugging it in, the solution is
\begin{align}
\z = \frac{1}{\sigma^2} (\frac{1}{\sigma^2} \W_{\z}^T \W_{\z} + \I)^{-1} \W_{\z}^T (\x - \vct{b}_{\z}),
\end{align}
which is equivalent to the update equation of Eq.(\ref{eq:update_equation}).
Moreover, under the linear model above:
\begin{align}
\mat{\Lambda} = - \nabla_{\z}^2 \log p(\x, \z) &= (\frac{1}{\sigma^2} \W_{\z}^T \W_{\z} + \I), \label{eq:hessian_linear}
\end{align}
which agree with $\mat{\Sigma}^{-1}$ in Eq.(\ref{eq:pca}). That is, by using the local linearity assumption, we can estimate the covariance without the expensive computation of the Hessian of the generative network.
\textbf{Bernoulli output ReLU networks}. We illustrate an example for how VLAEs can be applied to Bernoulli output ReLU networks:
\begin{align}
&\log p_{\vtheta}(\x|\z) = \sum_i^n x_i \log y_i(\z) + (1 - x_i) \log (1 - y_i(\z)), \nonumber \\
&\text{ where } \vct{y}(\z) = \frac{1}{1 + \exp(-g_{\vtheta}(\z))}.
\end{align}
Using $\nabla_{g_{\vtheta}(\z)} \log p(\x|\z) = \x - \vct{y}(\z)$ and chain rule, the gradient and the Hessian is
\begin{align}
&\nabla_{\z} \log p_{\vtheta}(\x, \z) = \frac{\partial g_{\vtheta}(\z)^T}{\partial \z} (\x - \vct{y}(\z)) - \z, \\
&\nabla_{\z}^2 \log p_{\vtheta}(\x, \z) = \frac{\partial^2 g_{\vtheta}(\z)^T}{\partial \z^2} (\x - \vct{y}(\z)) \\
&- \frac{\partial g_{\vtheta}(\z)^T}{\partial \z} \text{diag}(\vct{y}(\z) \cdot (\vct{1} - \vct{y}(\z))) \frac{\partial g_{\vtheta}(\z)}{\partial \z} - \mat{I}. \nonumber
\end{align}
Plugging in the linear approximation $g_{\vtheta}(\z) \approx \W_{\z} \z + \vct{b}_{\z}$, the result simplifies to
\begin{align}
&\nabla_{\z} \log p_{\vtheta}(\x, \z) = \W_{\z}^T (\x - \vct{y}(\z)) - \z, \label{eq:bernoulli_derivative}\\
&\nabla_{\z}^2 \log p_{\vtheta}(\x, \z) = -(\W_{\z}^T \mat{S} \W_{\z} + \mat{I}), \\
&\text{ where } \mat{S}_{\z} = \text{diag}(\vct{y}(\z) \cdot (\vct{1} - \vct{y}(\z))).
\end{align}
To solve Eq.(\ref{eq:bernoulli_derivative}), we first apply the first-order approximation of $\vct{y}(\z)$:
\begin{align}
\vct{y}(\z')
&\approx \vct{y}(\z) + \frac{\partial \vct{y}(\z)}{\partial \z} (\z' - \z) \\
&= \vct{y}(\z) + \mat{S}_{\z} \W_{\z} (\z' - \z).
\end{align}
We plug it into Eq.(\ref{eq:bernoulli_derivative}) and solve the equation for zero,
\begin{align}
\z' =
&(\W_{\z}^T \mat{S}_{\z} \W_{\z} + I)^{-1} \W_{\z}^T (\x - \vct{y}(\z) + \mat{S}_{\z} \W_{\z} \z). \nonumber
\end{align}
This leads to the update equation for the mode similar to the Gaussian case (Eq.(\ref{eq:update_equation})):
\begin{align}
&\vct{\mu}_{t+1} = \mat{\Sigma}_{t} \W_{t}^T (\x - \vct{b}_{t}), \label{eq:update_equation_bernoulli} \\
&\text{ where } \mat{\Sigma}_{t} = (\W_{t}^T \mat{S}_{t} \W_{t} + \mat{I})^{-1},
\vct{b}_t = (\vct{y}_t - \mat{S}_{t} \W_{t} \vct{\mu}_t). \nonumber
\end{align}
After $T$ updates, the approximate posterior distribution for the Bernoulli output distribution is defined as
\begin{align}
q(\z|\x) &= \mathcal{N}(\vct{\mu}_T, \mat{\Sigma}_{T}).
\end{align}
\subsection{Efficient Computation}
\label{sec:computation}
For a network with width $O(D)$, the calculation of $\W_{\z}$ (Eq.(\ref{eq:linear_map1})--(\ref{eq:linear_map2})) and the update equation (Eq.(\ref{eq:update_equation})) requires a series of matrix-matrix multiplication and matrix inversion of $O(D^3)$ complexity, whereas the standard forward or backward propagation through the network takes a series of matrix-vector multiplication of $O(D^2)$ cost.
As this computation
can be burdensome for bigger networks\footnote{In our experiments, the computational overhead is affordable with GPU acceleration. For example, our MNIST model takes 10 GPU hours for 1,000 epochs on one Titan X Pascal.}, we discuss efficient alternatives for: (1) iterative mode seeking and (2) covariance estimation.
\textbf{Iterative mode seeking}.
For piece-wise linear networks, nonlinear variants of Conjugate Gradient (CG) can be effective as the CG solves a system of linear equations efficiently. It requires the evaluation of matrix-vector products $\W_{\z} \z$ and $\W_{\z}^T \vct{r}$, where $\vct{r}$ is the residual $\x - (\W_{\z} \z + \vct{b})$. These are computable during the forward and backward pass with $O(D^2)$ complexity per iteration. See Appendix for details.
For general differentiable neural networks, the gradient-based optimizers such as SGD, momentum or ADAM \cite{kingma15} can be adopted to find the solution of Eq.(\ref{eq:mode}). The backpropagation through the gradient-based updates requires the evaluation of Hessian-vector products but there are efficient approximations such as the finite differences \citep{lecun1993automatic} used in \citet{kim18}.
\textbf{Covariance estimation}.
Instead of analytically calculating the precision matrix $\mat{\Lambda} = \mat{\Sigma}^{-1} = \sigma^{-2} \W^T \W + \I$ (Eq.(\ref{eq:hessian_linear})) we may directly approximate the precision matrix using truncated SVD for top $k$ singular values and vectors of $\mat{\Lambda}$.
The truncated SVD can be iteratively performed using the power method where each iteration involves evaluation of the Jacobian-vector product $\W^T \W \z$. This can be computed through the forward and backward propagation at $O(D^2)$ cost. One way to further accelerate the convergence of the power iterations is to extend the amortized inference model to predict $k$ vectors as seed vectors for the power method. However, we still need to compute the Cholesky decomposition of the covariance matrix for sampling.
\section{Related Work}
\label{related_works}
\citet{cremer18} and \citet{krishnan18} reveal that VAEs suffer from the inference gap between the ELBO and the marginal log-likelihood.
\citet{cremer18} decompose this gap as the sum of the \textit{approximation error} and the \textit{amortization error}.
The approximation error results from the choice of a particular variational family, such as fully-factorized Gaussians, restricting the distribution to be factorial or more technically, have a diagonal covariance matrix.
On the other hand, the amortization error is caused by the suboptimality of variational parameters due to the amortized predictions.
This work is most akin to the line of works that contribute to reducing the amortization error by iteratively updating the variational parameters to improve the approximate posterior \cite{kim18,marino18,krishnan18}.
Distinct from the prior approaches which rely on gradient-based optimization, our method explores the local linearity of the network to make more efficient updates.
Regarding the approximation error, various approaches have been proposed for improved expressiveness of posterior approximation. Importance weighted autoencoders \cite{burda15} learn flexible posteriors using importance weighting. \citet{tran16} incorporate Gaussian processes to enrich posterior representation. \citet{maaloe16} augment the model with auxiliary variables and \citet{salimans15} use Markov chains with Hamiltonian dynamics.
Normalizing flows \cite{tabak13, rezende15, kingma16, tomczak16} transform a simple initial distribution to an increasingly flexible one by using a series of \textit{flows}, invertible transformations whose determinant of the Jacobian is easy to compute. For example, the Householder flows \cite{tomczak16} can represent a Gaussian distribution with a full covariance alike to our VLAEs. However, as opposed to the flow-based approaches, VLAEs introduce no additional parameters and are robust to the amortization error.
The Laplace approximation have been applied to estimate the uncertainty of weight parameters of neural networks \citep{mackay1992practical, ritter2018scalable}. However, due to the high dimensionality of neural network parameters (often over millions), strong assumptions on the structure of the Hessian matrix are required to make the computation feasible \citep{lecun1990optimal, ritter2018scalable}. On the other hand, the latent dimension of deep generative models is typically in the hundreds, rendering our approach practical.
\section{Experiments}
\label{sec:experiments}
We evaluate our approach on five popular datasets: MNIST \cite{lecun98}, Omniglot \cite{lake13}, Fashion-MNIST \cite{xiao17}, Street View House Numbers (SVHN) \cite{netzer11} and CIFAR-10 \cite{krizhevsky09}.
We verify the effectiveness of our approach not only on the ReLU networks with Gaussian output (section \ref{sec:exp_gaussian}), but also on the Bernoulli output ReLU networks in section \ref{sec:vlae} on dynamically binarized MNIST (section \ref{sec:exp_bernoulli}).
We compare the VLAE with other recent VAE models, including
(1) VAE \cite{kingma14} using the standard fully-factorized Gaussian assumption, (2) Semi-Amortized VAE (SA-VAE) which extends the VAE using gradient-based updates of variational parameters \cite{kim18, marino18, krishnan18} (3) VAE augmented with Householder Flow (VAE+HF) \cite{tomczak16} \cite{rezende15} which employs a series of Householder transformation to model the covariance of the Gaussian posterior. For bigger networks, we also include (4) VAE augmented with Inverse Autoregressive Flow (VAE+IAF) \cite{kingma16}.
We experiment two network settings: (1) a small network with one hidden layer. The latent variable dimension is 16 and the hidden layer dimension is 256. We double both dimensions for color datasets of SVHN and CIFAR10. (2) A bigger network with two hidden layers. The latent variable dimension is 50 and the hidden layer dimension is 500 for all datasets. For both settings, we apply ReLU activation to hidden layers and use the same architecture for the encoder and decoder. See Appendix for more experimental details.
The code is public at {\color{magenta}{http://vision.snu.ac.kr/projects/VLAE}}.
\subsection{Results of Gaussian Outputs}
\label{sec:exp_gaussian}
Table~\ref{tab:results} summarizes the results on the Gaussian output ReLU networks in the small network setting. The VLAE outperforms other baselines with notable margins in all the datasets, proving the effectiveness of our approach. Remarkably, a single step of update ($T=1$) leads to substantial improvement compared to the other models, and with more updates the performance further enhances. Fig. \ref{fig:recon_image} depicts how data reconstructions improve with the update steps.
Table \ref{tab:results_big} shows the results with the bigger networks, which bring considerable improvements. The VLAE again attains the best results for all the datasets. The VAE+IAF is generally strong among the baselines whereas the SA-VAE is worse compared to others. One distinguishing trend compared to the small network results is that increasing the number of updates $T$ often degrade the performance of the models. We suspect the increased depth due to the large number of updates or flows causes optimization difficulties, as we observe worse results on the training set as well.
For both network settings, the SA-VAE and VAE+HF show mixed results. We hypothesize the causes are as follows:
(1) The SA-VAE update is noisy as the gradient of ELBO (Eq.(\ref{eq:elbo})) is estimated using a single sample of $\z$. Hence, it may cause instability during training and may require more iterations than used in our experiments for better performance.
(2) Although the VAE+HF is endowed with flexibility to represent correlations between the latent variable dimensions, it is prone to suffer from the amortization error as it completely relies on the dynamic prediction of the inference network, whereas the inference problem becomes more complex with the enhanced flexibility.
On the other hand, we argue that the VLAE is able to make significant improvements in fewer steps because the VLAE update is more powerful and deterministic (Eq.(\ref{eq:update_equation})), thanks to the local linearity of ReLU networks. Moreover, the VLAE computes the covariance of latent variables directly from the generative model, thus providing greater expressiveness with less amortization error.
\begin{table}[t!]
\centering
\small
\setlength{\tabcolsep}{2pt}
\caption{Log-likelihood results on small networks, estimated with 100 importance samples. Gaussian output is used except the last column with the Bernoulli output. $T$ refers to the number of updates for the VLAE and SA-VAE \cite{kim18} or the number of flows for the VAE+HF \cite{tomczak16}.}
\label{tab:results}
\vskip 0.15in
\begin{sc}
\begin{tabular}{lcccccc}
\toprule
& \multirow{2}{*}{mnist} & omni- & fashion & \multirow{2}{*}{svhn} & \multirow{2}{*}{cifar\scriptsize10} & binary \\
& & glot & mnist & & & mnist \\
\midrule
VAE & 612.9 & 343.5 & 606.3 & 4555 & 2364 & -96.73 \\
SA-VAE & & & & & & \\
\quad $T$=1 & 614.1 & 341.4 & 606.7 & 4553 & 2366 & -96.85 \\
\quad $T$=2 & 615.2 & 346.6 & 604.1 & 4551 & 2366 & -96.73\\
\quad $T$=4 & 612.8 & 348.6 & 606.6 & 4553 & 2366 & -96.71 \\
\quad $T$=8 & 612.1 & 345.5 & 608.0 & 4559 & 2365 & -96.89\\
VAE+HF & & & & & & \\
\quad $T$=1 & 610.5 & 341.5 & 604.3 & 4557 & 2366 & -96.75\\
\quad $T$=2 & 613.1 & 343.1 & 606.5 & 4569 & 2361 & -96.52\\
\quad $T$=4 & 612.9 & 333.8 & 604.9 & 4564 & 2362 & -96.44\\
\quad $T$=8 & 615.6 & 332.6 & 605.5 & 4536 & 2357 & -96.14\\
\midrule
VLAE & & & & & & \\
\quad $T$=1 & 638.6 & 362.0 & 614.9 & 4639 & 2374 & -94.68\\
\quad $T$=2 & 645.4 & 372.7 & 615.5 & 4681 & 2381 & -94.46\\
\quad $T$=4 & 649.9 & 372.3 & 615.6 & 4711 & 2387 & \textbf{-94.41}\\
\quad $T$=8 & \textbf{650.3} & \textbf{380.7} & \textbf{618.8} & \textbf{4718} & \textbf{2392} & -94.57 \\
\bottomrule
\end{tabular}
\end{sc}
\vskip -0.2in
\end{table}
\begin{figure}[t]
\vskip 0.1in
\begin{center}
\centerline{\includegraphics[width=\columnwidth]{figures/n_step_reconstruction_color}}
\caption{Examples of images reconstructed by VLAE with five update iterations proceeding from left to right. The pixel correlations greatly improve on the first update. The ground-truth samples are shown on the rightmost.}
\label{fig:recon_image}
\end{center}
\vskip -0.3in
\end{figure}
\subsection{Results of Bernoulli Outputs}
\label{sec:exp_bernoulli}
To show the generality of our approach on non-Gaussian output, we experiment ReLU networks with Bernoulli output on dynamically binarized MNIST. Each pixel is stochastically set to 1 or 0 with a probability proportional to the pixel intensity \cite{salakhutdinov08}.
The rightmost columns in Table \ref{tab:results}--\ref{tab:results_big} show the results on dynamically binarized MNIST. The VLAE attains the highest log-likelihood as in the Gaussian output experiments. The results demonstrate that VLAEs are also effective for non-Gaussian output models.
\begin{table}[t!]
\centering
\small
\setlength{\tabcolsep}{2pt}
\caption{Log-likelihood results on bigger networks, estimated with 5000 importance samples. See the caption of Table \ref{tab:results} for details.}
\label{tab:results_big}
\vskip 0.15in
\begin{sc}
\begin{tabular}{lcccccc}
\toprule
& \multirow{2}{*}{mnist} & omni- & fashion & \multirow{2}{*}{svhn} & \multirow{2}{*}{cifar\scriptsize10} & binary \\
& & glot & mnist & & & mnist \\
\midrule
VAE & 1015 & 602.7 & 707.7 & 5162 & 2640 & -85.38 \\
SA-VAE & & & & & & \\
\quad $T$=1 & 984.7 & 598.5 & 706.4 & 5181 & 2639 & -85.20 \\
\quad $T$=2 & 1006 & 589.8 & 708.3 & 5165 & 2639 & -85.10 \\
\quad $T$=4 & 999.8 & 604.6 & 706.4 & 5172 & 2640 & -85.43 \\
\quad $T$=8 & 990.0 & 602.7 & 697.0 & 5172 & 2639 & -85.24 \\
VAE+HF & & & & & & \\
\quad $T$=1 & 1028 & 602.5 & 715.6 & 5201 & 2637 & -85.27 \\
\quad $T$=2 & 1020 & 603.1 & 710.4 & 5179 & 2636 & -85.31 \\
\quad $T$=4 & 989.8 & 607.0 & 710.0 & 5209 & 2641 & -85.22 \\
\quad $T$=8 & 944.3 & 608.5 & 714.6 & 5196 & 2640 & -85.41 \\
VAE+IAF & & & & & & \\
\quad $T$=1 & 1015 & 609.4 & 721.2 & 5037 & 2642 & -84.26 \\
\quad $T$=2 & 1057 & 617.5 & 724.1 & 5150 & 2624 & -84.16 \\
\quad $T$=4 & 1051 & 617.5 & 721.0 & 4994 & 2638 & -84.03 \\
\quad $T$=8 & 1018 & 606.7 & 725.7 & 4951 & 2639 & -83.80 \\
\midrule
VLAE & & & & & & \\
\quad $T$=1 & \textbf{1150} & 727.4 & 817.7 & 5324 & \textbf{2687} & -83.72 \\
\quad $T$=2 & 1096 & \textbf{731.1} & 825.4 & 5159 & 2686 & -83.84 \\
\quad $T$=4 & 1054 & 701.2 & \textbf{826.0} & 5231 & 2683 & -83.73 \\
\quad $T$=8 & 1009 & 661.2 & 821.0 & \textbf{5341} & 2639 & \textbf{-83.60} \\
\bottomrule
\end{tabular}
\end{sc}
\vskip -0.2in
\end{table}
\section{Conclusion}
\label{sec:conclusion}
We presented \textit{Variational Laplace Autoencoders} (VLAEs), which apply the Laplace approximation of the posterior for training deep generative models. The iterative mode updates and full-covariance Gaussian approximation using the curvature of the generative network enhances the expressive power of the posterior with less amortization error.
The experiments demonstrated that on ReLU networks, the VLAEs outperformed other amortized or iterative models.
As future work, an important study may be to extend VLAEs to deep latent models based on the combination of top-down information and bottom-up inference \cite{kingma16, sonderby16}.
\section*{Acknowledgements}
This work is supported by Samsung Advanced Institute of Technology, Korea-U.K. FP Programme through NRF of Korea (NRF-2017K1A3A1A16067245)
and IITP grant funded by the Korea government (MSIP) (2019-0-01082).
\section{Image Samples}
\label{sec:generation_outputs}
Figure \ref{fig:reconstruction} and \ref{fig:generated} illustrates examples of reconstruction and generation samples made by the VLAE on MNIST \cite{lecun98}, Fashion MNIST \cite{xiao17}, Omniglot \cite{lake13}, SVHN \cite{netzer11} and CIFAR 10 \cite{krizhevsky09}. Overall, the reconstructions are sharp but generated samples tend to be blurry, especially when the data is complex (e.g. CIFAR10). We expect using convolutional architectures to be helpful for improving image generation qualities.
\section{Experimental Details}
\label{sec:exp_details}
We optimize using ADAM \cite{kingma15} with learning rate 0.0005. Other parameters of the optimizer is set to default values. We experiment with $T=1, 2, 4, 8$ where $T$ is the number of iterative updates for VLAE and SA-VAE, or the number of flow transformations for VAE+HF.
We set the batch size to 128. All models are trained up to 2000 epochs at maximum and evaluated using the checkpoint that gives the best validation performance.
We set $\alpha_t = 0.5 / (t+1)$ as decay for the VLAE update. For SA-VAE, the variational parameter $\vct{\lambda}_t$ is updated $T$ times using SGD: $\vct{\lambda}_{t+1} = \vct{\lambda}_t + \alpha \frac{\partial}{\partial \vphi} \mathcal{L}_{\vtheta}(\x; \vct{\lambda}_t)$ with $\alpha=0.0005$. The value of $\alpha$ is determined using a grid search among \{1.0, 0.1, 0.001, 0.0005, 0.0001\} on the small network. We estimate the gradient using a single sample of $\z$ and apply the gradient norm clipping to avoid divergence of SA-VAE.
In our experiments, we find that the bigger models are susceptible to the parameter initialization, and their latent variables are prone to collapse if not properly initialized.
We also observe VLAE and VAE+IAF are relatively robust to hyperparameter settings compared to other models.
In order to prevent latent variable collapse, we use He's initialization \citep{he15} to preserve variance of backward propagation with gain of $2^{1/3}$ to account for the network structure that consists of two ReLU layer and one linear layer. In this way, the variance of gradients is preserved in initial phase of training. Furthermore, the data is mean-normalized and scaled so that the reconstruction loss at initial state is approximately $1$.
These changes successfully prevent latent variable collapse and significantly improve overall performance of the models.
This finding hints that it is crucial to preserve gradient variance throughout the networks.
Note that the gradient signal to the encoder comes from two sources: (1) KL divergence term $D_{KL}(q_{\vphi}(\z|\x)||p(\z))$ (2) Reconstruction term $\mathbb{E}_{q_{\vphi}(\z|\x)}[\ln p_{\vtheta}(\x|\z)]$. While the gradient from the KL divergence term is directly fed into the encoder, the gradient from the reconstruction term - which is essential for preventing the latent variable collapse - have to propagate backwards through the decoder to reach the encoder. We hypothesize that if the networks are not initialized properly, the reconstruction gradient is overwhelmed by the KL divergence gradient which drives the approximate posterior $q_{\vphi}(\z|\x)$ to collapse to the prior $p(\z)$ in the initial stage of training.
\section{Conjugate Gradient Method}
To measure the performance of the Conjugate Gradient (CG) method as an alternative to the update equations of the main draft, we implement the VLAE+CG model where the mode update equation is replaced with the CG ascent step.
We use nonlinear Conjugate Gradient of Polak-Ribi\'ere method. For more details on nonlinear Conjugate Gradient methods, we refer readers to \citep{shewchuk1994introduction, dai2010nonlinear}. With $T=4$, we find that VLAE+CG yields about 25\% speed-up compared to the VLAE with minor performance loss ($\sim$ 1\%) on MNIST.
| {'timestamp': '2022-12-01T02:21:44', 'yymm': '2211', 'arxiv_id': '2211.17267', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17267'} | arxiv |
\section*{Acknowledgements}
This project was in part supported by Samsung, Stanford HAI, a PECASE from the ARO,
ARL grant W911NF-21-2-0104, a Vannevar Bush Faculty Fellowship, and
gifts from the Adobe and Snap Corporations.
\section{Introduction}
\label{sec:intro}
Creating a new 3D asset is a laborious task, which often requires manual design of triangle meshes, texture maps, and object placements.
As such, numerous methods were proposed to automatically create diverse and realistic variations of existing 3D assets. For example, procedural modeling techniques \cite{ebert2003texturing, mvech1996visual} produce variations in 3D assets given predefined rules and grammars, and example-based modeling methods \cite{funkhouser2004modeling, kalogerakis2012probabilistic} combine different 3D components to generate new ones.
With our work, we propose a different, generative strategy that is able to create realistic variations of a single 3D scene from a small number of photographs. Unlike existing 3D generative models, which typically require 3D assets as input~\cite{funkhouser2004modeling, wu2022learning}, our approach only takes a set of unposed images as input and outputs a generative model of a single 3D scene, represented as a neural radiance field~\cite{mildenhall2021nerf}.
\begin{figure}[t!]
\centering
\includegraphics[width=.47\textwidth]{figures/teaser.png}
\caption{SinGRAF{} generates different plausible realizations of a single 3D scene from a few unposed input images of that scene. In this example, i.e., the ``office\_3'' scene, we use 100 input images, four of which are shown in the top row. Next, we visualize four realizations of the 3D scene as cubemap-style panoramas, rendered using the generated neural radiance fields. Note the variations in scene layout, including chairs, tables, lamps, and other parts, while staying faithful to the structure and style of the input images.}
\label{fig:teaser}
\end{figure}
Our method, dubbed SinGRAF, builds on recent progress in unconditional 3D-aware GANs~\cite{chan2021pi, schwarz2020graf} that train generative radiance fields from a set of single-view images. However, directly applying these 3D GANs to our problem is challenging, because they typically require a large training set of diverse images and often limit their optimal operating ranges to objects, rather than entire scenes. SinGRAF{} makes a first attempt to train a 3D generative radiance field for individual indoor 3D scenes, creating realistic 3D variations in scene layout from unposed 2D images.
Intuitively, our method is supervised to capture the internal statistics of image patches at various scales and generate 3D scenes whose patch-based projections follow the input image statistics.
At the core of our method lies continuous-scale patch-based adversarial \cite{goodfellow2020generative} training. Our radiance fields are represented as triplane feature maps~\cite{Chan2022} produced by a StyleGAN2~\cite{karras2020analyzing} generator. We volume-render our generated scenes from randomly sampled cameras with {\em varying fields of view}, to simulate the appearance of image patches at various scales. A scale-aware discriminator is then used to compute an adversarial loss to the real and generated 2D patches to enforce realistic patch distributions across all sampled views. Notably, our design of continuous-scale patch-based generator and discriminator allows patch-level adversarial training without expensive hierarchical training \cite{Shaham_2019_ICCV,wu2022learning, Xu_2021_CVPR}. During the training, we find applying perspective augmentations to the image patches and optimizing the camera sampling distribution to be important for high-quality scene generation.
The resulting system is able to create plausible 3D variations of a given scene trained only from a set of unposed 2D images of that scene. We demonstrate our method on two challenging indoor datasets of Replica~\cite{straub2019replica} and Matterport3D~\cite{chang2017matterport3d} as well as a captured outdoor scene. We evaluate SinGRAF{} against the state-of-the-art 3D scene generation methods, demonstrating its unique ability to induce realistic and diverse 3D generations.
\section{Related Work}
\label{sec:related}
\paragraph{Synthesis from 3D Supervision.} A large body of prior work aims at creating variations of scenes or objects. Procedural modeling approaches~\cite{ebert2003texturing, parish2001procedural, mvech1996visual, musgrave1989synthesis} are widely used for auto-generating repetitive scenes such as terrains, buildings, or plants. These methods typically require manually designing the rules and grammars to procedurally add new 3D elements. Example-based methods \cite{kalogerakis2012probabilistic, funkhouser2004modeling, xu2012fit} aim at extracting patterns from 3D asset examples to synthesize new models. This line of data-driven approaches learns how to mix and match different components to create a plausible 3D asset. Similarly, scene synthesis techniques \cite{paschalidou2021atiss, fisher2012example, wang2018deep} learn a distribution of plausible object arrangements from professionally designed scene datasets. All of these methods require datasets of 3D assets, part segmentation, or object arrangement designs, which are expensive to collect.
\paragraph{3D-aware GANs.}
Leveraging the recent developments of neural implicit representations \cite{park2019deepsdf,mescheder2019occupancy,chen2019learning,sitzmann2019siren} and radiance fields \cite{sitzmann2019srns,mildenhall2021nerf, barron2021mip, lindell2022bacon,muller2022instant},
3D GANs \cite{chan2021pi,niemeyer2021giraffe,Chan2022,gu2021stylenerf,or2022stylesdf, xu20223d, zhou2021cips,DeVries_2021_ICCV,bautista2022gaudi,shi20223daware,skorokhodov2022epigraf,xue2022giraffehd,zhang2022mvcgan,deng2022gram,xiang2022gramhd,Tewari_2022_CVPR,bahmani20223d} train generative 3D radiance fields from a set of single-view images. These methods render the sampled scenes from various viewpoints via volume rendering and supervise adversarially. Many of these approaches apply their discriminators on full-resolution images during training, but some also employ patch-based discriminators~\cite{schwarz2020graf,meng2021gnerf,skorokhodov2022epigraf}. The resulting 3D GANs can create diverse 3D radiance fields that enable view-consistent NVS. Existing 3D GANs, however, rely on a large amount of training data, while our model only uses a few images of a single 3D scene.
\paragraph{Few-Shot Generative Models.}
Recently, researchers have started applying generative modeling techniques to few-shot settings, where only a few or single examples are given.
In the 2D image domain, SinGAN and its extensions \cite{Xu_2021_CVPR,Shaham_2019_ICCV,hinz2021improved} explored the idea of training a CNN-based hierarchical generator on a single image, supervised using patch discrimination at multiple scales. The strategy of learning the internal patch distribution of a single example to train a generative model has been widely adopted for various tasks, including the synthesis of videos \cite{haim2022diverse}, motion sequences \cite{li2022ganimator}, 3D textures \cite{henzler2020learning, portenier2020gramgan}, or 3D shapes \cite{hertz2020deep,wu2022learning}.
However, none of these works applied 3D generative models from single-scene images. Concurrently to our work, \cite{wang2022singrav} trains generative radiance fields from single-scene images but focuses mainly on stochastic and repetitive synthetic scenes, rather than structured, human-made scenes.
\section{Single Scene 3D GAN}
\label{sec:approach}
Our system takes as input an unposed set of images taken from a single scene and outputs a 3D generative model $\mathbf{G}$ that can generate diverse 3D radiance fields. We assume the intrinsic parameters of the camera are available. We do not assume our target scene to be static, i.e., we allow temporal changes in the scene. In the experiment section, we show our method's behavior for dynamic scenes.
We illustrate our image generation and discrimination processes in Fig.~\ref{fig:pipeline}. Source code and pre-trained models will be made available.
\subsection{Rendering Model}
Our generative model $\mathbf{G}(\mathbf{\Gamma}, \mathbf{z})$ takes a set of query rays $\mathbf{\Gamma}$ and a noise vector $\mathbf{z}$ and outputs RGB predictions for the rays. Below we briefly discuss the rendering process of $\mathbf{G}.$
\paragraph{Generator Architecture}
$\mathbf{G}$ represents continuous radiance fields using tri-planes, following~\cite{Chan2022}. We adopt a StyleGAN2-based generator backbone ~\cite{Karras2019stylegan2}, which
consists of a mapping network that takes as input a noise vector $\mathbf{z} \sim \mathbb{R}^{128}$ and transforms it into a latent code vector $\mathbf{w} \sim \mathbb{R}^{128}$. Next, a synthesis network transforms $\mathbf{w}$ into a 2D feature image $\mathbf{F} \in \mathbb{R}^{N \times N \times 3C}$ with a total of $3C$ feature channels. Following~\cite{Chan2022}, we split these feature channels into three axis-aligned feature planes $\mathbf{F}_{xy},\mathbf{F}_{xz},\mathbf{F}_{yz} \in \mathbb{R}^{N \times N \times C}$.
A color $\mathbf{c}$ and density $\sigma$ value can now be queried at an arbitrary 3D coordinate $\mathbf{x}$ by aggregating the triplane features and processing them by a small multilayer perceptron--style decoder, $\textrm{\sc{mlp}}: \mathbb{R}^C \rightarrow \mathbb{R}^4$, as
\begin{equation}
\left( \mathbf{c} \left( \mathbf{x} \right), \sigma \left( \mathbf{x} \right) \right) = \textrm{\sc{mlp}} \left( \mathbf{F}_{xy} \left(\mathbf{x}\right) \! + \! \mathbf{F}_{xz} \left(\mathbf{x}\right) \! + \! \mathbf{F}_{yz} \left(\mathbf{x}\right) \right).
\end{equation}
Note that we do not model view-dependent effects.
\paragraph{Neural Rendering.}
Using volume rendering~\cite{Max:1995,mildenhall2021nerf}, we project the 3D neural field into 2D images. For this purpose, the aggregated color $\mathbf{C}(\mathbf{r})$ of a ray $\mathbf{r}\in \mathbf{\Gamma}$ is computed by integrating the field as
\begin{align}
\mathbf{C} (\mathbf{r}) & = \int_{t_{n}}^{t_{f}} T \left( t \right) \sigma \left( \mathbf{r} (t) \right) \mathbf{c} \left( \mathbf{r}(t) \right) \textrm{d} t, \\
T \left( t \right) & = \textrm{exp} \left( - \int_{t_{n}}^{t_{f}} \sigma \left( \mathbf{r} \left( s \right) \right) \textrm{d} s \right),
\label{eq:volumerendering}
\end{align}
where $t_n$ and $t_f$ indicate near and far bounds along the ray $\mathbf{r} (t) = \mathbf{o} + t \mathbf{d}$ pointing from its origin $\mathbf{o}$ into direction $\mathbf{d}$. The continuous volume rendering equation (\cref{eq:volumerendering}) is typically computed using the quadrature rule~\cite{Max:1995}.
Our volume rendering step directly outputs RGB color images or patches; we do not apply a superresolution module on the rendered values. Moreover, we use 96 samples per ray and do not use hierarchical ray sampling \cite{mildenhall2021nerf}.
\subsection{Training Process} \label{sec: training}
\paragraph{Progressive Patch Scaling.}
Given a set of input images, most existing 3D GANs generate and discriminate images at full resolution. However, as shown in the ablation study (Sec.~\ref{sec:analysis}), adversarial training at full scale leads to a collapse of the learned distribution to a single mode, likely because the joint information of the images uniquely determines a single 3D structure. Therefore, we turn to learn the internal patch distribution of the images, inspired by some existing works \cite{Shaham_2019_ICCV, wu2022learning, Xu_2021_CVPR}.
Directly extending hierarchical patch-based GANs \cite{Shaham_2019_ICCV,wu2022learning, Xu_2021_CVPR}, however, would require expensive training of a pyramid of generators with progressively-growing feature plane resolutions. To address the issue, we notice that our tri-plane features define a continuous radiance field and thus are able to render patches at an arbitrary resolution and scale. Therefore, we use a single generator network and continuously control the scale of the patches during training, forgoing the progressive training of multiple generator networks \cite{Shaham_2019_ICCV,Xu_2021_CVPR,wu2022learning}.
\begin{figure}[t!]
\centering
\includegraphics[width=.47\textwidth]{figures/patch_scale_small.pdf}\\
\caption{Visualizations of patches at different scales.}
\label{fig:patch_scale}
\end{figure}
Given input images $\{I_1, ... ,I_N | I_i \in \mathbb{R}^{H'\times H'\times 3}\}$ of resolution $H' \times H'$ and field of view (FOV) $\theta$, we consider the image plane $\mathcal{P}$ of a virtual camera with the same FOV.
During training, we volume-render patches with {\em fixed} resolution $H \times H$ but with varying scale $s$. Here, the scale $s\in [0,1]$ indicates the spatial extent of a patch on the image plane of $\mathcal{P}.$ When $s=1.0$ the patch covers the entire image plane with $H\times H$ pixels, which is used for full-resolution training of existing 3D GANs \cite{chan2021pi,schwarz2020graf}. With smaller $s,$ the patch will cover a smaller window in the image plane with the same resolution, thus containing more details. The location of the patch window on $\mathcal{P}$ is sampled randomly. We render a sampled patch $\rho$ with its associated rays $\mathbf{\Gamma}_\rho$: $\mathbf{G}(\mathbf{\Gamma}_\rho,\mathbf{z}).$ Similarly, a ground truth patch can be sampled by cropping $I_i$'s with a given patch scale $s$ (see Fig.~\ref{fig:patch_scale}).
The scale value $s$ is sampled randomly for each patch from a uniform distribution $s\sim \texttt{U}(s_{\min}(t), s_{\max}(t)),$ where $t$ is the current training epoch. We schedule the scale distribution so that in early epochs, we have larger patches to provide scene structural information and gradually decrease the scales towards the end of the training to induce better quality and diversity. Refer to supplementary for details.
Our discriminator network $\mathbf{D}$, whose architecture closely follows that of \cite{Karras2019stylegan2}, takes as input patches and outputs a scalar, indicating the realism of the patches. Because our patches have varying scales, we additionally condition $\mathbf{D}$ with the scale value $s$ of each patch $\rho$:
\begin{equation}
\mathbf{D}: \mathbf{G}(\mathbf{\Gamma}_\rho,\mathbf{z}) \times s \mapsto \mathbb{R}.
\end{equation}
Implementation-wise, we simply repeat the scale value to match the patch resolution.
\paragraph{Data augmentation.}
Our approach aims at generating a 3D scene from a limited set of 2D observations. As such, it is desirable to augment the available data during training. To this end, we apply data augmentation techniques for both image and camera pose data.
In addition to the usual image augmentation techniques used for 2D GANs, such as translation, cropping, and cutout, we suggest a perspective augmentation approach, which is appropriate for generating 3D scenes with patch discrimination. Based on the known camera pose, we re-project image patches so as to imitate camera rotations followed by perspective projections. Camera rotations without changing the position do not induce occlusions or parallax; thus, this approach is applicable to captured content. Moreover, because our model discriminates patches instead of full images, unknown regions after rotation and perspective projection can be cropped. In practice, we start our training without rotational augmentation but gradually introduce and increase this augmentation up to $15^\circ$ for later training epochs where the patch scale $s$ decreases. Additional details on data augmentation are included in the supplement.
\paragraph{Camera Pose Distribution.}
To render patches from radiance fields we need to sample a virtual camera to render from. We define the camera pose distribution non-parametrically using a set of 1,000 cameras: $\mathcal{T}=\{T_1,...,T_{1000}|T_i\in SE(3)\}$; each virtual camera $\tau$ is randomly chosen from $\mathcal{T}$ during training.
We reject the sampled $\tau$ when the occupancy value of the camera center in the neural fields is above some threshold. The $T_i$'s are initially sampled from a zero-mean 2D Gaussian on a plane with shared heights with random rotation about the vertical axis. During training, we jitter the $T_i$'s on translation and rotation.
The randomly initialized camera distribution, however, may not be a good representation of the real camera distribution of the input images. While our method can generate reasonable 3D scenes when training with random distributions, we find it beneficial to optimize the camera distribution $\mathcal{T}$ for higher-quality outputs. Such optimization will transform the distribution to accommodate poses with various rotations. Therefore, we optimize the $T_i$'s via automatic differentiation using our adversarial loss in the early stage of the training. We eventually stop the optimization since smaller patches at the later stage contain weak pose information. In practice, we decompose the poses into more easily optimizable forms, which we discuss further in the supplementary.
\paragraph{Training Objective}
Besides the regular min-max adversarial loss \cite{goodfellow2020generative}, we find it useful to adopt two regularization losses: R1 gradient penalty \cite{mescheder2018training} and discriminator reconstruction loss \cite{liu2020towards} ($\mathcal{E}_{R}$). Combining the regularizations with the adversarial loss, we have the final objective as follows:
\begin{align}
\mathcal{E}(\mathbf{G},&\mathbf{D},\mathcal{T})=\mathbb{E}_{\mathbf{z},\tau \sim \mathcal{T},s,\rho}\left[ f(\mathbf{D}(\mathbf{G}(\mathbf{\Gamma}_\rho,\mathbf{z}))) \right]+\\
&\mathbb{E}_{I,s,\rho}\left[f(-\mathbf{D}(\rho,s)) +
\lambda_{1} |\nabla_\rho \mathbf{D}(\rho,s)|^2 \right]+\lambda_{2}\mathcal{E}_{R}(\mathbf{D}), \nonumber
\end{align}
where $f(a)=-\log(1+\exp(-a)),$ and $\lambda$'s are balancing parameters. Note that the sampled patch $\rho$ is a function of the sampled scale $s$. We minimize the objective using the ADAM optimizer with learning rate of 2e-4.
\section{Experiments}
\label{sec:results}
We conduct a number of experiments to test SinGRAF's capabilities to (i) create realistic 3D scene variations across a diverse set of challenging indoor scenes, (ii) reliably produce view-consistent 3D representations, and (iii) handle scene dynamics. At the end of the section, we show ablation studies and justify our design decisions.
\subsection{Datasets}
We test and compare our approach on five scenes from the Replica dataset and one scene from the Matterport3D dataset, featuring realistically scanned indoor scenes. Within the Replica dataset, we choose to cover a good range of different scene types, including offices, apartments, and hotel rooms. The Replica dataset, however, only contains scanned indoor scenes that are typical of their own categories. To stress-test our algorithm, we add a large `castle' ballroom dataset from the Matterport3D dataset that has a very different appearance from `regular' indoor scenes. For each of the above 6 scenes, we render 100 views by sampling camera locations from a zero-mean Gaussian distribution with random rotations about the height axis. We reject the cameras that collide with occupied volumes. Lastly, we showcase our method on a captured image dataset where we use our own photographs of an outdoor scene. We capture the images using a hand-held consumer-grade smartphone camera and pass them to our algorithm without intrinsic or extrinsic calibrations.
\begin{figure*}
\centering
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\linewidth]{figures/results/result_hotel_0_small.pdf}
\caption{``hotel\_0'' scene from the Replica dataset.
}
\label{fig:results_hotel_0}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\linewidth]{figures/results/result_apartment_0_small.pdf}
\caption{``apartment\_0'' scene from the Replica dataset.}
\label{fig:results_apartment_0}
\end{subfigure}
\\
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\linewidth]{figures/results/result_frl_apartment_4_small.pdf}
\caption{``frl\_apartment\_4'' scene from the Replica dataset. }
\label{fig:results_frl_apartment_4}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.49\textwidth}
\includegraphics[width=\linewidth]{figures/results/result_castle_small.pdf}
\caption{``castle'' scene from the Matterport3D dataset.}
\label{fig:castle}
\end{subfigure}
\caption{Results of four difference scenes, as indicated. For each example, we show some of the input images, the result achieved by the GSN~\cite{DeVries_2021_ICCV} baseline, and three realizations of SinGRAF's results for the same input images. Note that GSN is deterministic and not able to generate different realizations of this scene while SinGRAF is capable of generating a diverse set of realizations with high image quality.}
\label{fig:results}
\end{figure*}
\subsection{Baselines}
As a baseline, we compare SinGRAF against the current state-of-the-art 3D scene generative method, GSN \cite{DeVries_2021_ICCV}. While numerous 3D-GAN methods were proposed, we could not find any other suitable baseline that demonstrated the modeling of apartment-scale scenes, such as the ones from the Replica dataset. Concurrently to our work, GAUDI \cite{bautista2022gaudi} extended GSN to model even larger-scale scenes with generative modeling, but the code is not publicly available for us to run. To compare against GSN, we use their public codebase and run their algorithm using the same 100-image datasets. During training, we sample the virtual cameras
from the 10,000 camera samples used in their original paper.
Following the original implementation, the images are volume-rendered at $64\times 64$ resolution and upsampled to $128\times 128$ with a learned CNN.
\subsection{Metrics}
To measure the generated image quality we use the popular Kernel Inception Distance (KID) score, which reliably measures the distance between two sparsely sampled (N$\leq$500) image distributions. This is in contrast with FID, which introduces significant biases in the low-data regime. We randomly sample 500 images for all methods in the same way as each of them samples during training. The 500 ground truth images are sampled as we generate the training images.
We measure the diversity of scene generation by sampling multiple images from a fixed camera and computing average LPIPs distance (average pair-wise LPIPS distances), following \cite{Huang_2018_ECCV}. Note that, however, because our generated scenes are 3D, there exist loopholes to our diversity metric. For example, the diverse images generated from a fixed camera could be identical in the 3D space under rigid transformations. However, we did not observe this edge case and observe that the high diversity score from a fixed view leads to diversity beyond rigid transformations and vice versa.
\begin{table}[t!]
\centering
\footnotesize
\begin{tabular}{lcccc|cc}
\toprule
& \multicolumn{2}{c}{GSN ($128^2$)}
& \multicolumn{2}{c|}{$\!\!\!$SinGRAF ($128^2$)}
& \multicolumn{2}{c}{$\!\!$SinGRAF ($256^2$)} \\
& KID$\downarrow$ & Div.$\uparrow$
& KID$\downarrow$ & Div.$\uparrow$
& KID$\downarrow$ & Div.$\uparrow$ \\
\midrule
office\_3 & .061 & .001 & \bf .044 & \bf .297 & .050 & .378 \\
hotel\_0 & .049 & .012 & \bf .037 & \bf .413 & .046 & .490 \\
apt.0 & .069 & .001 & \bf .037 & \bf .401 & .049 & .467 \\
frl\_apt.4 & .052 & .001 & \bf .037 & \bf .335 & .055 & .408 \\
castle & \bf .050 & .001 & .064 & \bf .248 & .088 & .318 \\
office\_0 & .075 & .001 & \bf .053 & .001 & .062 & .003 \\
dynamic $\!\!\!\!$ & .089 & .013 & \bf .033 & \bf .298 & .050 & .365 \\
\bottomrule
\end{tabular}
\caption{Quantitative Results. We measure the realism and diversity of the 3D scenes generated from SinGRAF and GSN on Replica and Matterport3D scenes. KID compares the distributional difference between the rendered and ground truth images of the scenes. We measure the diversity by rendering images with various latent vectors from fixed camera. Overall, we outperform the GSN baseline on both metrics in all but one case. }
\label{tbl:comparison}
\end{table}
\subsection{Scene Generation Results}
We showcase the visual quality and diversity of our trained generative model across scenes. As can be seen in Figs.~\ref{fig:teaser},~\ref{fig:results_hotel_0},~\ref{fig:results_apartment_0},~\ref{fig:results_frl_apartment_4}, our method is able to synthesize plausible and realistic variants of the original scenes under a wide range of indoor scene environments. For example, the ``office\_3" scene shown in Fig.~\ref{fig:teaser} contains a meeting table (orange), a sofa (grey), and a coffee table (white). Note how our model is able to augment the room by duplicating, elongating, or rotating the meeting table and the sofa. For the ``apartment\_0" and ``hotel\_0" scenes shown in Figs.~\ref{fig:results_hotel_0},~\ref{fig:results_apartment_0}, our model was able to capture {\em structural} diversity of the scenes while preserving the details and general appearance of the scene. As shown in the results of ``frl\_apartment\_4" (Fig.~\ref{fig:results_frl_apartment_4}) our model was able to generate scenes with very different sizes by duplicating large scene structures. The results in the ``castle" scene, shown in Fig.~\ref{fig:castle}, features various structural changes along with the diversity of the number and locations of the chairs in the scene. Overall, SinGRAF was able to synthesize a remarkable amount of variation across scenes, even when the scene is small and simple, e.g., ``office\_3" or ``hotel\_0."
\begin{figure}[t!]
\centering
\includegraphics[width=.47\textwidth]{figures/results/view_consistency_apartment_0_small.pdf}\\
\includegraphics[width=.47\textwidth]{figures/results/view_consistency_office_3_small.pdf}\\
\caption{View consistency test with small rotations ($15^\circ$). We check the 3D consistency of the neural fields generated by SinGRAF and GSN by visualizing the scene from varying viewpoints. GSN produces inconsistent discontinuities and abrupt structure changes (i.e., plant in the right), while SinGRAF demonstrates smooth and 3D-consistent view changes. Note that the shown cubemap panorama naturally induces some image distortions.
}
\label{fig:results_view}
\end{figure}
On the other hand, applying the strongest current baseline for scene generation, GSN \cite{DeVries_2021_ICCV}, produces mode-collapsed results without diversity for all of the tested scenes. Quantitatively, as shown in Tab.~\ref{tbl:comparison}, SinGRAF outperforms GSN both in terms of realism and diversity.
\paragraph{Video Results.}
We urge readers to watch our supplementary videos to fully appreciate the quality and diversity of our 3D scenes.
\subsection{View-Consistent Scene Generation}
We notice that even for the single-mode results of GSN, the scene renderings are of suboptimal quality, containing spurious blur (Fig.~\ref{fig:results_apartment_0}) or unnaturally abrupt content changes by viewpoints (Fig.~\ref{fig:results_hotel_0}). We hypothesize that GSN learned to generate plausible images but does not learn to create consistent 3D structures. To test this hypothesis, we visualize both GSN and our method when rotating the panorama twice by 15$^\circ$ each (Fig.~\ref{fig:results_view}). For the case of GSN, the slight change of viewpoints resulted in significant structural changes, for example changing the room or changing the shape of the furniture. In contrast, SinGRAF reliably generates consistent images and scene structures with varying viewpoints, indicating strong 3D awareness of the learned representations.
\subsection{Modeling Scene Dynamics}
We highlight that SinGRAF is especially robust in capturing scene dynamics since it does not rely on any pixel-wise reconstruction loss. To verify this claim, we run our method on the ``frl\_apartment" scene in the Replica dataset that has been captured with various configurations (5 different scene setups). The synthesis results shown in Fig.~\ref{fig:results_frl_apartment_dynamic} indeed confirm SinGRAF's ability to train a high-quality generative model on scenes that are not static. Note that, given diverse input configurations, SinGRAF was able to induce more variations to the scenes, by reorganizing the objects in the scenes. We note that training on these dynamic configurations did not result in diverse scene generation of GSN -- it produced single mode outputs.
\begin{figure}[t!]
\centering
\includegraphics[width=.47\textwidth]{figures/results/result_frl_apartment_dynamic_small.pdf}\\
\caption{Modeling scene dynamics. We train our model using 500 images from five different scene configurations of the ``frl\_apartment''. Our resulting generative model produces 3D scenes with highly diverse variations of objects and structures, e.g., the locations of furniture.}
\label{fig:results_frl_apartment_dynamic}
\end{figure}
\begin{figure}[t!]
\centering
\includegraphics[width=.47\textwidth]{figures/results/result_garden2_small.pdf}\\
\caption{Casually-captured scene. Given 100 input images photographed with a smartphone, our method is successful in generating high-quality variations of the 3D scene.
}
\label{fig:results_capture}
\end{figure}
\subsection{Towards Casually-captured Scenes}
We also test our method ``in the wild'', i.e., with captured content rather than pre-scanned scenes. For this experiment, we took 100 photographs of an outdoor apartment setting using a consumer-level smartphone. This scene is particularly challenging because it contains a lot of high-frequency textures, such as trees and grass, and a large dark window with view-dependent reflections.
The camera setting also makes the problem difficult, as the intrinsic parameters are unknown and training images contain lens distortions.
We approximate the field of view of the cameras with $65^\circ$, and our model successfully generates variations with visually pleasing quality, as shown in Fig.~\ref{fig:results_capture}.
The average LPIPs distance is $0.001$ for GSN, and $0.372$ and $0.444$ for SinGRAF at $128^2$ and $256^2$ image resolution, respectively.
Although a KID score is not available for this example, because we only have 100 training images and no ground truth, this experiment demonstrates the potential of SinGRAF to be applied in the wild.
\subsection{Analysis}
\label{sec:analysis}
We analyze the effects of our design decisions through ablation studies next. The quantitative ablation results are displayed in Tab.~\ref{tbl:ablation}.
\begin{table}[t!]
\centering
\small
\begin{tabular}{lcc|cc}
\toprule
& \multicolumn{2}{c|}{$128 \times 128$}
& \multicolumn{2}{c} {$256 \times 256$} \\
& KID$\downarrow$ & Div.$\uparrow$
& KID$\downarrow$ & Div.$\uparrow$ \\
\midrule
full \& half-scale patches & .183 & .001 & NA & NA \\
progressive patches & .046 & .308 & .068 & .374 \\
+ camera opt. & .037 & .295 & .056 & .368 \\
+ perspective aug. & .037 & .335 & .055 & .408 \\
\bottomrule
\end{tabular}
\caption{Ablation study. We ablate our model to study the effects of patch discrimination, camera pose optimization, and perspective augmentation using the ``frl\_apartment\_4'' scene. Note that progressive patch scaling is essential for obtaining diverse scenes. Camera distribution optimization improves image quality while perspective augmentation maximizes scene diversity.}
\label{tbl:ablation}
\end{table}
\paragraph{Patch Discrimination.}
As suggested by prior works on single-image GAN, learning the scene-internal patch statistics is crucial in inducing diversity into generated results. Indeed, without the patch discrimination, i.e., using full-scale ($s=1.0$) images for adversarial training, results in a complete mode collapse of the model. Even when combining half-scale ($s=0.5$) and full-sale ($s=1.0$) patches as a 50\% mix, the training results in no diversity (first row of Tab.~\ref{tbl:ablation}), suggesting the importance of our progressive patch scaling strategy.
\paragraph{Camera Pose Optimization.}
We test the importance of our non-parametric camera distribution optimization scheme described in Sec.~\ref{sec: training}. As expected, adjusting the camera distributions result in higher realism of the generated outputs, resulting in lower KID scores (third row of Tab.~\ref{tbl:ablation}). On the other hand, the optimization scheme only slightly hurts the diversity of the generation.
\paragraph{Perspective Augmentation.}
Given our low-data regime, a possible way of maximizing the diversity is via data augmentation strategies, e.g., perspective image augmentation (see Sec.~\ref{sec: training}). As expected, applying perspective image augmentation leads to higher diversity (fourth row of Tab.~\ref{tbl:ablation}). What we found interesting is that adding perspective augmentation of 15$^\circ$ did not result in lower KID scores. This shows that perspective augmentation is an effective strategy in our setting.
\paragraph{Failure cases.}
We notice that for the ``office\_0" scene, shown in Fig.~\ref{fig:failure}, SinGRAF mode-collapses and fails to generate diversity. We believe that this occurs because the detailed paintings on the walls uniquely identify the location of the patches in relation to others.
\begin{figure}[tb!]
\centering
\includegraphics[width=.47\textwidth]{figures/results/result_office_0_failure.png}\\
\caption{Failure case of the ``office\_0'' scene. The lack of diversity for this scene is likely due to the paintings on the walls that uniquely determine the relative locations of most patches.}
\label{fig:failure}
\end{figure}
\section{Discussion}
\label{sec:discussion}
In this work, we take first steps towards a 3D generative model for a single scene from a set of unposed images. Our model, SinGRAF, is able to generate diverse and realistic variations of the given scene while preserving the semantics of human-made structures. In contrast to 2D single-image GAN methods \cite{Shaham_2019_ICCV}, which typically train a pyramid of generators, SinGRAF is trained with a single generator architecture, and is thus simple to implement and train. We achieve this by continuously adjusting the patch scales during training, leveraging the continuous neural fields representation. Given the unposed and scarce nature of our image data, we find it useful to optimize the camera pose distributions and apply perspective augmentations to the images.
Below we discuss three interesting implications of our approach to the field of 3D computer vision.
\vspace{-1em}
\paragraph{Reconstructing Variations.} SinGRAF, in a sense, reconstructs the distribution of plausible 3D scenes given a set of images. Traditionally, the 3D vision community largely focused on finding the {\em most likely} mode of the 3D scene for reconstruction. Relaxing this constraint to instead sample from the posterior distribution of scenes could lead to new technologies or applications.
\vspace{-1em}
\paragraph{Unposed Reconstruction.} SinGRAF does not use estimated poses of the input images as it relies on an adversarial rather than a pixel-wise loss.
While SinGRAF, in its current form, is not designed to accurately reproduce the ground truth 3D scene, it might be extended to provide control of the {\em narrowness} of the distribution, depending on the applications.
\vspace{-1em}
\paragraph{Dynamic Scene Reconstruction.} In contrast to traditional 3D reconstruction methods, scene dynamics would likely {\em improve} the quality and diversity of SinGRAF training (see Fig.~\ref{fig:results_frl_apartment_dynamic}). Such a trend implies that it could be easier to extend SinGRAF to operate on highly dynamics scenes, e.g., rock concerts, rather than developing physical models to handle complex scene dynamics.
\paragraph{Limitations.}
The quality and diversity of the SinGRAF outputs depend on the input images, scenes, and choice of views, which are hard to predict or control. Moreover, SinGRAF training is currently expensive and takes 1--2 days per scene with a single RTX 6000 GPU, although it is comparable to existing 3D GANs (e.g., GSN). We expect improvements in the training speed with the development of more efficient continuous representations, such as~\cite{muller2022instant,chen2022tensorf}.
\section{Video Results}
We highly encourage readers to view our supplementary video containing visualizations of our 3D scenes, latent interpolations, and comparisons against GSN. The video results are best suited for appreciating the 3D consistency, quality, and diversity of our generated scenes. The name of the attached video file is ``singraf\_video.mp4."
\section{Implementation Details}
\label{sec:implementation}
\subsection{Progressive Patch Scaling}
In practice, we used the input resolution of $512\times 512$ for the input images ($H'=512$) and used the fixed patch size of $64\times 64$ ($H=64$). When the scale $s=1$ the $64\times 64$ patch covers the entire image.
To progressively scale down the patches, we reduce the patch scale $s$ for the first 100 epochs. Because we are using 1,000 sample batches for each epoch, we gradually reduce $s$ during the course of 100,000 iterations and then fix $s$ for the rest of the training. Typically our model exhibits the best KID score around 300 to 400 epochs.
We randomly sample the scale factor $s$ independently for each image instance during training. We use a time-varying uniform distribution for the patch scale: $s\sim \texttt{U}(s_{\min}(t), s_{\max}(t)),$ where $t$ is the epoch index. In practice, we used $s_{\min}(0)=0.6$ and $s_{\max}(0)=0.8$ in the beginning of the training and $s_{\min}(100)=0.25$ and $s_{\max}(100)=0.55$ at epoch 100. $s_{\min}(t)$ and $s_{\max}(t)$ values are interpolated linearly as a function of $t$ over the course of 100 epochs.
\subsection{Data Augmentation}
As described in the main text, we schedule the increase of angles used for perspective augmentation during training. Similar to the progressive patch scaling, we gradually linearly increase the maximum augmentation angle for 100 epochs. We start from the angle range of $[0^\circ, 0^\circ]$ to $[-15^\circ, 15^\circ]$ linearly over the course of 100 epochs. For each real image patch we randomly and independently sample an angle from the current range and apply the perspective augmentation on the height axis.
An example visualization of this augmentation could be seen in Fig.~\ref{fig:perspective_augmentation}.
\begin{figure}[htbp
\centering
\includegraphics[width=.47\textwidth]{figures/supp/perspective_augmentation_hotel_0_1_small.pdf}\\
\includegraphics[width=.47\textwidth]{figures/supp/perspective_augmentation_hotel_0_2_small.pdf}\\
\caption{Visualizations of the perspective augmentation applied at different angles. During training, we apply up to $15^\circ$ perturbation to promote diversity.
}
\label{fig:perspective_augmentation}
\end{figure}
\subsection{Camera Pose Optimization}\label{sec: camera_opt}
As described in the main text, we non-parametrically optimize the camera pose distribution during training. Given a set of 1,000 camera poses: $\mathcal{T}=\{T_1,...,T_{1000}|T_i\in SE(3)\}$. During training, we randomly sample camera poses from $\mathcal{T}$ and render the scenes from the cameras. We let these camera poses as optimizable variables and backpropagate the gradients from the adversarial loss to optimize the individual poses. Optimizing for the $SE(3)$ transformation is known to be a difficult task, and directly optimizing the values of the transformation matrix is difficult because the matrix can escape the manifold of $SE(3)$, e.g., $RR^{\intercal}\neq I.$ Therefore, we decompose the matrix into multiple components for ease of optimization.
Specifically, given a transformation $T,$ we can decompose it into:
\begin{equation}
T=\begin{pmatrix}
R & p\\
0 & 1
\end{pmatrix}: \, R\in SO(3), \, p\in \mathbb{R}^3.
\end{equation}
The rotation matrix can be further decomposed into a multiplication of 3 matrices:
\begin{equation}
R=R_z R_y R_x: \, R_{\{\}}\in SO(3),
\end{equation}
where $R_z$, $R_y$, and $R_x$ are respectively rotation matrix about $z$, $y$, and $x$ axis. For example, we have that:
\begin{equation}
R_z =
\begin{pmatrix}
\cos\theta_z & -\sin\theta_z & 0\\
\sin\theta_z & \cos\theta_z & 0 \\
0 & 0 & 1
\end{pmatrix}:\, \theta_z \in \mathbb{R},
\end{equation}
where $\theta_z$ is the rotation around the $z$ axis. While it is possible to parameterize our rotations with $\theta_z$, $\theta_y$, and $\theta_x$, directly optimizing for the Euler angles is known to be difficult \cite{zhou2019continuity}, as there is a discontinuity at $\theta=0$. Therefore, we parameterize each rotation with the cosine and sine of the Euler angle for each axis.
Let us denote $\mathcal{R}_z$ to be the data structure we carry for rotation about the $z$ axis:
\begin{equation}
\mathcal{R}_z:=[\cos\theta_z,\sin\theta_z].
\end{equation}
We similarly define $\mathcal{R}_y$ and $\mathcal{R}_x$ using cosine and sine of the angles. Then, we know that we can uniquely construct the rotation matrix $R$ from the $\mathcal{R}$'s. For the whole transformation, we carry the four data structures to fully describe and construct the matrix $T$, which are: $[\mathcal{R}_z,\mathcal{R}_y,\mathcal{R}_x,p]$.
We can optimize for these variables during training by backpropagating the adversarial losses. Note that for each update of the rotation parameter $\mathcal{R}_{\{\}}$, we need to make sure that the cosines and sines are proper, by normalizing it so that $||\mathcal{R}_{\{\}}||=1.$
In practice, we assume that cameras are located at the same height and rotate along vertical axis. Thus, we only optimize $p_x$, $p_z$ and $\mathcal{R}_y$ during the early stages of training where the expected patch scale is larger than $0.5$.
\subsection{Training Details}
The balancing parameters for the regularization terms in Eq.(5) of the main paper are
$\lambda_{1} = 0.5$ and $\lambda_{2} = 50$.
We use the spatial resolution of $256 \times 256$ and feature channel of $C=32$ for tri-plane representation~\cite{Chan2022}, which is generated by a StyleGAN2 \cite{karras2020analyzing} generator which is modulated by a noise vector $\mathbf{z} \sim \mathbb{R}^{128}$.
For rendering, we compute the feature of each sample along a ray via bilinear interpolation followed by concatenation (for the three planes), and process the feature using a decoder $\textrm{\sc{mlp}}$ to finally obtain color and density value.
The decoder $\textrm{\sc{mlp}}$ is composed of two shared linear layers, one layer for the density branch, and two additional layers for the RGB branch.
Each hidden layer uses 64 hidden units with leakyReLU activation except the final ones used for outputting density and RGB values.
For volume-rendering we used
$96$ samples per ray without importance sampling, to generate patches of $64 \times 64$ resolution.
When applied the patch scale of $s=0.25$, the effective resolution of each patch is $256\times 256$, i.e., the amount of details that exists in each patch would be obtained when rendering at $256\times 256$. Therefore, we can render our models at $256 \times 256$ resolution with details even though we trained our models with $64\times 64$ patches, without any 2D upsampling networks.
As described in the main text, we adopt the StyleGAN2 discriminator architecture to process the patches, but we additionally concatenate the scale of each patch.
We will release the source code upon acceptance.
\section{Additional Analysis}
\label{sec:additional}
\subsection{Visualization of Diversity Loss}
As discussed in the main text, we measure the diversity of the 3D generative models by fixing a camera and rendering with varying, randomly sampled latent codes. In Fig.~\ref{fig:fixed_view}, we show examples of such renderings. Note how we can tell that GSN's model has collapsed to a single mode, thus no variations from the fixed viewpoints. On the other hand, notice how SinGRAF generates highly diverse renderings of the same scenes from the fixed camera with varying latent.
\begin{figure}[htbp
\centering
\includegraphics[width=.47\textwidth]{figures/supp/fixed_view_office_3_small.pdf}\\
\caption{Visualizing randomly sampled 3D scenes from a fixed camera view. Notice how GSN's scenes do not change with the varying latent, indicating mode collapse, while SinGRAF presents highly diverse renderings.
}
\label{fig:fixed_view}
\end{figure}
\begin{figure}[htbp
\centering
\includegraphics[width=.47\textwidth]{figures/supp/failure_office_0_small.pdf}\\
\caption{Failure case of the ``office\_0'' scene. The lack of diversity in this scene is likely due to the paintings on the walls that uniquely determine the relative locations of most patches. Still, SinGRAF generates high-quality scene which resemble to input.}
\label{fig:failure_compare}
\end{figure}
\subsection{Latent Code Interpolation}
To showcase the rich and smooth latent space we learn via training SinGRAF on single scenes, we visualize the latent space interpolation by fixing a camera and rendering the scene using latent vectors obtained via linear interpolation between two latent vectors. The results are shown in Fig.~\ref{fig:latent_interpolation}, demonstrating high-quality, and diverse latent embedding of the single scenes. We highly encourage readers to view our video results for animated interpolation in the latent space.
\begin{figure*}[t!]
\centering
\includegraphics[width=.99\textwidth]{figures/supp/latent_interpolation_small.pdf}\\
\caption{Latent code interpolations. We fix the camera viewpoint per scene and render the scene using latent vectors interpolating between two latent vectors, whose scenes are shown on the two extreme sides.
}
\label{fig:latent_interpolation}
\end{figure*}
\subsection{Perspective Rendering Results}
In the main text, we have only visualized our scenes in the cubemap panorama form. In Fig.~\ref{fig:result_sample}, we show renderings of the scenes from randomly chosen latent codes and camera poses using a perspective camera model. Note that we sampled the camera poses using the distribution $\mathcal{T}$, which is the result of the optimization process described in Sec.~\ref{sec: camera_opt} during training.
\begin{figure*}[t!]
\centering
\includegraphics[width=.99\textwidth]{figures/supp/result_sample_small.pdf}\\
\caption{Perspective rendering results. We show perspective renderings of our trained scenes from randomly chosen latent codes and camera poses.
}
\label{fig:result_sample}
\end{figure*}
\subsection{Failure Case}
We observe that when the scene contains too many local details to be identified from small field-of-view patches, SinGRAF often learns a mode-collapsed latent space. Such an example can be found in Fig.~\ref{fig:failure_compare}, where the scene contains detailed paintings on the wall that uniquely determine the locations of the patches. We note that, while this mode-collapse behavior is unpredictable and thus is a limitation of our approach, the reconstructed scene closely resembles the ground truth scene of the input images. This is surprising, given that our model is given only {\em unposed} images, suggesting a promising future direction toward reconstructing challenging scenes via adversarial training.
\section*{\Large{Supplementary}}
\input{camera/supp1.tex}
\input{camera/supp2.tex}
\end{document}
| {'timestamp': '2022-12-01T02:21:41', 'yymm': '2211', 'arxiv_id': '2211.17260', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17260'} | arxiv |
\section{Introduction}
\begin{figure}[t]
\includegraphics[width=0.45\textwidth]{./images/Intro_v3.pdf}
\vspace{-0.3cm}
\centering
\caption{(a) T-SNE \cite{van2013barnes} visualization of
the BEV features in different UDA scenarios, in which features are obviously separated by domain. (b) The performance of our method compared with previous works \cite{li2022bevdepth,wang2021exploring,li2022unsupervised}. Both methods are built on BevDepth with a ResNet-50 backbone and evaluated on the target domain.}
\label{fig:intro}
\vspace{-0.4cm}
\end{figure}
The camera-based 3D object detection has attracted increasing attention, especially in the field of autonomous driving \cite{arnold2019survey, chen2017multi, chen2016monocular}. Nowadays, it has obtained obvious advancements driven by Bird-Eye-View (BEV) perception methods \cite{philion2020lift, huang2021bevdet, li2022bevdepth,li2022unifying, li2022bevstereo} and large scale labeled autonomous driving datasets \cite{geiger2012we, caesar2020nuscenes, sun2020scalability}. However, due to the vast variety of perception scenes \cite{wang2021exploring, li2022unsupervised}, the camera-based methods can suffer significant performance degradation caused by domain shift or data distribution variation.
Recently, though mono-view 3D detection methods \cite{li2022towards, li2022unsupervised} carry out the UDA setting on camera parameters or annotation methods variation, domain adaptation problem on many real-world scenarios is still unexplored in both Mono-view \cite{cai2020monocular, wang2021fcos3d, brazil2019m3d, ding2020learning, li2022diversity, zhang2021objects, simonelli2019disentangling} and Multi-view\cite{philion2020lift, wang2022detr3d, liu2022petr, liu2022petrv2, chen2022polar, jiang2022polarformer, li2022bevformer, reading2021categorical, huang2021bevdet, li2022unifying, li2022bevdepth} settings. As shown in Fig.\ref{fig:intro}, we discover the tremendous domain gap in the scene, weather, and day-night changing scenarios from source to target data in nuscenes \cite{caesar2020nuscenes}, which leads to inferior performance of baseline \cite{li2022bevdepth} (only 0.174, 0.159, and 0.05 NDS). Therefore, we attempt to transfer a multi-view 3D detector from a labeled source domain to an unlabeled target domain.
In UDA, the main challenge for Multi-view LSS-based BEV perception is the entangle of domain shift on multiple latent spaces:
(1)\textit{2D images latent space. } Since multi-view images contain abundant semantic information, it will result in a manifold domain shift when scenarios change.
(2) \textit{3D voxel latent space.}
Voxel features that are constructed by domain-specific images feature and unreliable depth prediction will assemble more domain shift.
(3) \textit{BEV latent space.}
Due to the shift in the above aspects, the constructed BEV feature results in an accumulation of domain shift and leading to alignment noises. As shown in Fig.\ref{fig:intro} (a), we visualize the distribution of BEV features, which are obviously separated by domains on different cross domain scenarios.
To this end, we propose a novel Multi-level Multi-space Alignment Teacher-Student ($M^{2}ATS$) framework to disentangle domain shift problems in multiple latent spaces, which consists of a Depth-Aware Teacher (DAT) model and Multi-space Feature Aligned (MFA) Student model.
DAT introduces composite depth-aware information to construct better voxel and BEV features in the target domain, which contains less source domain specific information.
To construct composite depth-aware information, DAT adaptively screened out reliably predicted depth by uncertainty estimation to compensate for lidar. It promotes representation consistency between DAT and student model through transferring domain-invariant multi-space knowledge and pseudo labels, thus addressing domain shift in pixel and instance level respectively.
In order to assist DAT in further bridging global level domain gaps on multiple latent spaces, we propose MFA in the student model. It aligns three task-relevant features of two domains, including multi-view images, 3D voxel, and BEV features. In the overall $M^{2}ATS$ framework, DAT and MFA compensate each other to address the domain shift of multiple latent spaces in multi-level.
As far as we know, we are the first to study the cross domain problem in Multi-View 3D object detection. We design three classical and one continual changing UDA scenarios, which are \textbf{Scene} (from Boston to Singapore), \textbf{Weather} (from sunny to rainy and foggy), \textbf{Day-night}, and \textbf{Changing Foggy degree} in \cite{caesar2020nuscenes}. For continual changing scenarios, we construct cross domain experiments with the continuously increased density of Fog, which gradually enlarges the domain gap. Our proposed method achieves competitive performance in all scenarios (shown in Fig. \ref{fig:intro} (b)). Compared with the previous state-of-the-art (SOTA) UDA method (i.e., STM3D\cite{li2022unsupervised}), it improves the NDS by 2.5, 3.2, and 5.2\% respectively in three classical scenarios.
The main contributions are summarized as follows:
\textbf{1)} We explore the unsupervised domain adaptation (UDA) problem for BEV perception of Multi-view 3D object detection. We propose a novel Multi-level Multi-space Alignment Teacher-Student ($M^{2}ATS$) framework to address multi-latent space domain shift.
\textbf{2)} In $M^{2}ATS$, we propose a Depth-Aware Teacher (DAT) to construct uncertainty-guided depth-aware information, and then transfer the domain-invariant pixel-level features and instance-level pseudo label to the student model. $M^{2}ATS$ contains a Multi-space Feature Aligned (MFA) student model which aligns multi-space features between two domains and compensates DAT to further alleviate the domain shift at global-level.
\textbf{3)} We conduct extensive experiments on the four challenging UDA scenarios, achieving SOTA performance compared with previous Mono-view 3D and 2D detection UDA methods. And we provide a Foggy-nuScene dataset.
\begin{figure*}[t]
\includegraphics[width=0.95\textwidth]{./images/framework_v8.pdf}
\centering
\vspace{-0.22cm}
\caption{The framework of Multi-level Multi-space Alignment Teacher-Student ($M^{2}ATS$), which is composed of the Depth-Aware Teacher (DAT) and Multi-space Feature Aligned (MFA) student model. In \textbf{the bottom part}, the DAT model takes target domain input and adopts depth-aware information to construct domain-invariant features, which transfers pixel (multi-space features) along with instance-level (pseudo label) knowledge to the student model. In \textbf{the upper part}, the MFA student model aligns multi-space features (\textcolor{red}{red circle}) at the global level between two domains. $M^{2}ATS$ framework aims to comprehensively address the multi-latent space domain shift problem.}
\label{fig:method}
\vspace{-0.42cm}
\end{figure*}
\section{Related work}
\subsection{Camera-based 3D object detection}
Nowadays, 3D Object Detection plays an important role in autonomous driving and machine scene understanding.
Two paradigms are prominent in this aspect: Single-view \cite{cai2020monocular, wang2021fcos3d, brazil2019m3d, ding2020learning, liu2021autoshape, manhardt2019roi, barabanau2019monocular, li2022diversity, zhang2021objects, simonelli2019disentangling} and Multi-view\cite{philion2020lift, wang2022detr3d, liu2022petr, liu2022petrv2, chen2022polar, jiang2022polarformer, li2022bevformer, reading2021categorical, huang2021bevdet, li2022unifying, li2022bevdepth, huang2022bevdet4d, li2022bevstereo}. In Single-view detection, previous works can be categorized into several streams, i.e. leveraging CAD models \cite{liu2021autoshape, manhardt2019roi, barabanau2019monocular}, setting prediction targets as key points \cite{li2022diversity, zhang2021objects}, and disentangling transformation for 2D and 3D detection \cite{simonelli2019disentangling}. Specifically, FCOS3D \cite{wang2021fcos3d} can predict 2D and 3D attributes synchronously. M3D-RPN \cite{brazil2019m3d} considers single-view 3D object detection task as a standalone 3D region proposal network. In order to establish a more reliable 3D structure, D4LCN \cite{ding2020learning} alters 2D depth prediction with pseudo LiDAR representation. \cite{cai2020monocular} calculates the depth of the objects by integrating the actual height of the objects. To better leverage the depth information in the detection process, MonoDTR\cite{huang2022monodtr} proposes an end-to-end depth-aware transformer network. However, taking into account the precision and practicality of detection, more and more multi-view 3D object detectors are proposed.
The Multi-view paradigm can be categorized into two branches, namely transformer-based \cite{carion2020end} and LSS-based \cite{philion2020lift}.
First of all, to extend DETR \cite{carion2020end} into 3D detection, DETR3D \cite{wang2022detr3d} first predicts 3D bounding boxes with a transformer network. Inspired by DETR3D, some works adopt object queries \cite{liu2022petr, liu2022petrv2, chen2022polar, jiang2022polarformer} or BEV grid queries \cite{li2022bevformer} to extract features from images and utilize attention method, resulting in better 2D-to-3D transformation. However, transformer-based methods don't project image features onto BEV representation. Following LSS \cite{philion2020lift}, some methods \cite{reading2021categorical, huang2021bevdet, li2022unifying} predict a distribution over lidar depth and generate a point cloud with multi-view image features for 3D detection. Specifically, BevDepth \cite{li2022bevdepth} introduces depth supervision and speeds up the operation of voxel pooling. Bevdet4d \cite{huang2022bevdet4d} and BevStereo \cite{li2022bevstereo} thoroughly explore temporal information in the task and concatenate volumes from multiple time steps. In this paper, we adopt BevDepth \cite{li2022bevdepth} as the baseline 3D object detector for its simple and powerful working flow, along with its great potential in cross domain feature extraction.
\subsection{UDA in 3D object detection}
Domain Adaptive Faster R-CNN \cite{chen2018domain} first probes the cross domain problem in object detection. Based on \cite{ganin2015unsupervised}, most previous works \cite{cai2019exploring, saito2019strong, wang2021exploring, xu2020exploring, xu2020cross, yu2022cross} follow the cross domain alignment strategy
and explore the influence of domain shift in multi-level features. As for 3D object detection, \cite{luo2021unsupervised, li2022unsupervised, zhang2021srdan} investigate Unsupervised Domain Adaptation (UDA) strategies for point cloud 3D detectors. In particular, \cite{luo2021unsupervised, zhang2021srdan} adopt alignment methods to align the feature and instance level information between two domains. STM3D \cite{li2022unsupervised} develop self-training strategies to realize UDA by consistent and high-quality pseudo
labels. Recently, some works \cite{barrera2021cycle, acuna2021towards, ng2020bev, saleh2019domain} investigate the cross domain strategies in BEV perception, which aim to reduce the simulation-to-real domain shift. In terms of camera-based monocular 3d object detection, \cite{li2022towards, li2022unsupervised} first attempt to disentangle the camera parameters and guarantee the geometry consistency in cross domain phase. In contrast, we dedicate ourselves to solving the domain gap in multi-view 3d object detection tasks, which infer 3D scenes from the BEV perspective. We propose a novel Multi-level Multi-space Alignment
Teacher-Student framework to deal with the accumulation of domain shift on multi-latent spaces.
\section{Methods}
\subsection{Overall framework}
\label{sec:overall}
In this paper, we study the Unsupervised Domain Adaptation (UDA) problem in LSS-based Vision-Centric Bird-Eye-View (BEV) perception \cite{philion2020lift,li2022bevdepth}, where the accumulation of multi-latent space domain shift existed. As shown in Fig. \ref{fig:method}, \textbf{Multi-level Multi-space Alignment Teacher-Student} ($M^{2}ATS$) framework contains a Depth-Aware Teacher (DAT) and Multi-space Feature Aligned (MFA) Student model. Along with transferring multi-latent space knowledge from DAT to the student model, the MFA student model simultaneously aligns the task-relevant features between two domains in the same latent spaces. We discuss each component and its interactions in the following.
\textbf{Depth-Aware Teacher model}. As shown in Fig. \ref{fig:method}, DAT extracts features and generates pseudo label from the target domain data, and transfers the pixel and instance-level knowledge to the student model. Specifically, due to the unreliable depth prediction and sparse property of target lidar, it suffers domain shift and incompletion when constructing voxel and BEV features.
Therefore, we introduce a depth-aware mechanism that completes the sparse lidar by the predicted depth and adopts uncertainty estimation to reserve reliable depth prediction. DAT then adopts depth-aware information as an intermediate to construct domain-invariant voxel and BEV features and generates reliable pseudo labels to fully exploit target domain data. The goal is to align the representation of DAT and the student model, thus alleviating domain shift accumulation.
\textbf{Multi-space Feature Aligned} student model.
As shown in Fig. \ref{fig:method}, the MFA student model receives the transferred knowledge and deals with domain shift at the global level. It extracts features from both source and target domains while introducing an alignment mechanism to pull close the representation of two domains in multi-latent space. The alignments lie in the 2D image, voxel, and BEV features, which aim to obtain domain-invariant features and alleviate domain shift at global level. MFA and DAT compensate each other to address the domain shift in the same latent spaces.
\subsection{Preliminary}
\label{sec:setup}
For the UDA setting \cite{zhao2020review}, we are provided by labeled source domain $D_{s} = \{\{I^i_{s}\}^M_{j=1},L^i_{s},G^i_{s}\}^{N_{s}}_{i=1}$ and unlabeled target domain $D_{t} = \{\{I^i_{t}\}^M_{j=1},L^i_{s}\}^{N_{t}}_{i=1}$ of N samples and M camera views, in which $I^i$, $L^i$, and $G^i$ denote images, lidar, and detection ground truth respectively. We adopt an encoder \cite{he2016deep} to extract image features, and use lidar data $L^i$ to supervise its depth prediction. These joint projects to 3D voxel feature $VF^i$, which are then voxel pooled to BEV feature $BF^i$. Note that, we only utilize lidar supervision during training following previous camera-based works \cite{li2022bevdepth}.
\subsection{Depth-aware teacher}
\label{sec:DAT}
\begin{figure}[t]
\includegraphics[width=0.38\textwidth]{./images/unc_v3.pdf}
\centering
\vspace{-0.2cm}
\caption{The detailed process of constructing depth-aware information. The uncertainty map is estimated by MC Dropout \cite{gal2016dropout}.}
\label{fig:unc}
\vspace{-0.38cm}
\end{figure}
Since detection perception is generated from voxel and BEV features which are initially constructed by depth prediction, the performance depends heavily on the accuracy of the depth sub-network estimation \cite{li2022bevdepth,li2022bevstereo}. However, cross domain transferring significantly aggravating depth prediction error \cite{liu2022unsupervised}. Therefore, in Depth-Aware Teacher (DAT) model, our goal is to leverage depth-aware information to construct domain-invariant depth information along with corresponding voxel and BEV features.
To this end, we construct composite depth information in the teacher model by combining sparse lidar data with reliable and domain-invariant depth prediction. Note that, domain shift lies in the original depth prediction of the target domain, we thus adaptively screened out reliable prediction of the target domain by depth uncertainty estimation. In contrast to uncertainty guidance, a more simple selection mechanism, which selects based on confidence score, moves decision boundaries to low-density regions in sampling-based approaches. However, it may lead to inaccuracy due to the poor calibration of neural networks. Moreover, the domain gap issue will result in more severe miscalibration \cite{guo2017calibration}. Therefore, we adopt Dropout methods \cite{gal2016dropout,ghiasi2018dropblock} with uncertainty measurement instead of confidence predictions. Specifically, similar to \cite{rizve2021defense}, instead of designing a particular uncertainty measure, we pioneering introduce uncertainty guidance to ignore depth prediction of the source domain specified. And we offer a new solution to address the domain shift in dense prediction task, which leverages an uncertainty map to select reliable and domain-invariant pixel prediction in the target domain. When utilizing reliable depth information to build the following features in the target, the source data trained model has a better feature representation and concentrates more on depth estimation tasks without domain shift influence.
The uncertainty map of depth prediction is:
\begin{equation}
D^i_{map} = \left\{
\begin{array}{l}
1 , \quad \mathcal{U}(D^i)\le \mathcal{E}_{thresh}\\
0 , \quad \mathcal{U}(D^i)\ge \mathcal{E}_{thresh}
\end{array}
\right.
\end{equation}
where $\mathcal{U}(D^i)$ is the uncertainty of $i^{th}$ pixel depth prediction, and $\mathcal{E}_{thresh}$ is the selected threshold, which is decided on the variance of the uncertainty values. As shown in Fig.\ref{fig:unc}, we utilize an uncertainty map to obtain reliable depth prediction and composite target sparse Lidar data, constructing depth-aware information.
Inspired by the prevalent soft teacher \cite{sohn2020simple, xu2021end}, the rest of the teacher model is built with mean teacher mechanism \cite{tarvainen2017mean}. The weights of teacher model $\mathcal{T}_{DAT}$ at time step $t$ is the exponential moving average (EMA) of successive student model $\mathcal{S}_{TGT.}$, shown below:
\begin{equation}
\label{eq:2}
\mathcal{T}_{DAT.}^{t} = \alpha \mathcal{T}_{DAT.}^{t-1} + (1-\alpha) \mathcal{S}_{TGT.} ^{t}
\end{equation}
, where $\alpha$ is a smoothing coefficient. With the help of depth-aware information and mean-teacher mechanism, the DAT model can continuously transfer multi-latent space (\ie, images, voxel, BEV, output) knowledge to the student, including pixel-level features and instance-level pseudo labels. The student model thus can concentrate more on task-driven knowledge learning without domain shift.
\subsection{Multi-space feature aligned student}
\label{sec:MFA}
In student model learning, aside from the pixel and instance-level transferred knowledge from DAT, we further introduce Multi-space Feature Alignment (MFA) method to deal with the domain shift at the global level. In order to further alleviate the domain specific feature influence, we pull close the features representation of the source and target domain in multiple latent spaces, including 2D images, voxel, and BEV. Specifically, we utilize the domain adversarial training method \cite{ganin2016domain} which inserts gradient reversal layers and reverses back-propagated gradients for domain discriminators to optimize the model and extract domain-invariant features. Different from the previous alignment method \cite{wang2021exploring, yu2022cross}, LSS-based approaches hold multi-space features so that we align multi-space global information synchronously. The MFA loss $\mathcal{L}_{MFA}$ is shown in Eq.\ref{eq:MFA}, where ${F}_{s,l}$ and ${F}_{t,l}$ is the source and target domain features at $l$ latent space $(L\in\{images, voxel, BEV\})$ and $D$ denotes the domain discriminator.
\begin{equation}
\label{eq:MFA}
\mathcal{L}_{MFA}({F}_{s},{F}_{t}) = \sum_{l\in L}(\log{D}({F}_{s,l}) + \log(1-{D}({F}_{t,l}))
\end{equation}
In the $M^{2}ATS$ framework, DAT and MFA compensate each other to deal with the multi-latent spaces domain shift problem in multi-level.
\subsection{Training objectives and inference}
\label{sec:loss}
The $M^{2}ATS$ framework contains a Depth-Aware Teacher (DAT) model and Multi-space Feature Aligned (MFA) Student model, the teacher model is updated by EMA operation. When adopting the DAT model to transfer multi-space features to the student, the knowledge transfer loss $\mathcal{L}_{MKT}$ is shown as follows:
\begin{equation}
\mathcal{L}_{MKT} = \sum_{l\in L}\frac{1}{W_{l}'\times H_{l}'}\sum_{i\in \mathcal{P}}||F_{Te,l}^{{i}}-F_{St,l}^{{i}}||^{2}
\label{eq:KT}
\end{equation}
where $F_{Te,l}^{i}$ and $F_{St,l}^{i}$ stand for the $i^{th}$ pixel value from DAT model and student model at $l$ latent space, $L\in\{images, voxel, BEV\}$ . $W_{l}^{'}$ and $H_{l}^{'}$ stand for width and height of the transferred features, $\mathcal{P} =\{1,2,..,W_{l}'\times H_{l}'\}$. We thus pull close the distance of the feature between model $\mathcal{T}_{DAT}$ and $\mathcal{S}_{TGT}$ with MSE loss. With the help of pixel-level domain-invariant knowledge transfer, we can reduce the domain shift in the three latent spaces. Meanwhile, the integrated domain adaptation loss $\mathcal{L}_{DA}$ is shown in Eq.\ref{eq:domain}.
\begin{equation}
\mathcal{L}_{DA} = \lambda_1*\mathcal{L}_{UNC} + \lambda_2*\mathcal{L}_{MKT} + \lambda_3*\mathcal{L}_{MFA}
\label{eq:domain}
\end{equation}
, where $\mathcal{L}_{UNC}$ is the detection loss \cite{li2022bevdepth} penalized by target domain pseudo label, which is generated by teacher model.
In order to maintain the balance of loss penalties, $\lambda_1$ is set to 1, $\lambda_2$ and $\lambda_3$ is set to 0.1.
During inference, same with other camera-based methods \cite{li2022bevdepth,li2022bevformer,li2022bevstereo}, we only adopt multi-view camera data.
\section{Evaluation}
We conduct extensive experiments to demonstrate the effectiveness of the Multi-level Multi-space Alignment Teacher-Student ($M^{2}ATS$) framework.
In Sec~\ref{sec:4.1}, the details of the setup of UDA scenarios and implementation details are given.
In Sec~\ref{sec:4.2}, we evaluate the cross domain performance of $M^{2}ATS$ in the three classical and one continual changing scenarios, including scene, weather, day-night, and continuously increased foggy degree Adaptation.
The comprehensive ablation studies are conducted in Sec~\ref{ablation}, which investigate the impact of each component.
Finally, we provide qualitative analysis to better present the effectiveness of our proposed framework in Sec~\ref{sec:4.4}.
\begin{table*}[t]
\centering
\caption{Results of different methods for scene adaptation scenario on the validation set \cite{caesar2020nuscenes}, from Boston to Singapore. DA means utilizing the domain adaption method, and R50 and R101 adopt Resnet 50 and 101 as the backbone.}
\vspace{-0.2cm}
\setlength{\tabcolsep}{1.3mm}{
\begin{tabular}{c|c|c|c|cccccc}
\hline
& Method & Backbone & \cellcolor{lightgray} NDS ↑& \cellcolor{lightgray} mAP ↑ & mATE ↓ & mASE ↓ & mAOE ↓ & mAVE ↓ & mAAE ↓ \\
\hline\hline
& BEVDet\cite{ huang2021bevdet} & R50 & 0.126 & 0.117 & 0.873 & 0.787 & 1.347& 1.302 & 0.666 \\
Baseline & BEVDepth\cite{li2022bevdepth} & R50 & 0.174 & 0.115 & 0.888 & 0.412 & 1.031 & 1.056 & 0.527 \\
& BEVDepth\cite{li2022bevdepth} & R101 & 0.187 & 0.115 & 0.874 & 0.391 & 0.944 & 1.021 & 0.501 \\
\hline
\multirow{2}{*}{DA} & SFA\cite{wang2021exploring}(BEVDepth) & R50 & 0.181 & 0.124 & 0.856 & 0.411 & 1.023 & 1.075 & 0.540 \\
& STM3D\cite{li2022unsupervised}(BEVDepth) & R50 & 0.183 & 0.129 & 0.840 & 0.421 & 1.050 & 1.055 & 0.550 \\
\hline
\multirow{2}{*}{DA} & Ours(BEVDepth) & R50 & \textbf{0.208} & \textbf{0.148} & \textbf{0.813} & \textbf{0.402} & \textbf{0.907} & \textbf{1.134} & \textbf{0.536} \\
&Ours(BEVDepth) & R101 & \textbf{0.211} & \textbf{0.166} & \textbf{0.758} & \textbf{0.427} & \textbf{1.127} & \textbf{1.108} & \textbf{0.535} \\
\hline
\end{tabular}%
}
\label{tab:scene}%
\vspace{-0.1cm}
\end{table*}%
\begin{table*}[t]
\centering
\caption{Results of different methods for weather adaptation scenarios on the validation set \cite{caesar2020nuscenes}, from Sunny to Rainy and Foggy-3.}
\vspace{-0.2cm}
\setlength{\tabcolsep}{1.3mm}{
\begin{tabular}{c|c|c|ccc|ccc}
\hline
& & & & Target Rainy & & & Target Foggy-3 & \\
& Method & Backbone & \cellcolor{lightgray} NDS ↑& \cellcolor{lightgray} mAP ↑ & mATE ↓ & \cellcolor{lightgray} NDS ↑& \cellcolor{lightgray} mAP ↑ & mATE ↓ \\
\hline\hline
& BEVDet\cite{ huang2021bevdet} & R50 & 0.232 & 0.207 & 0.818 & 0.135 & 0.072 & 0.867 \\
Baseline & BEVDepth\cite{li2022bevdepth} & R50 & 0.268 & 0.196 & 0.824 & 0.159 & 0.079 & 0.882 \\
& BEVDepth\cite{li2022bevdepth} & R101 & 0.272 & 0.212 & 0.842 & 0.202 & 0.122 & 0.804 \\
\hline
\multirow{2}{*}{DA} & SFA\cite{wang2021exploring}(BEVDepth) & R50 & 0.281 & 0.200 & 0.840 & 0.228 & 0.133 & 0.840 \\
& STM3D\cite{li2022unsupervised}(BEVDepth) & R50 & 0.276 & 0.212 & 0.820 & 0.234 & 0.145 & 0.721 \\
\hline
\multirow{2}{*}{DA} & Ours(BEVDepth) & R50 & \textbf{0.305} & \textbf{0.243} & \textbf{0.819} & \textbf{0.266} & \textbf{0.173} & \textbf{0.805} \\
& Ours(BEVDepth) & R101 & \textbf{0.308} & \textbf{0.247} & \textbf{0.726} & \textbf{0.271} & \textbf{0.174} & \textbf{0.793} \\
\hline
\end{tabular}%
}
\label{tab:weather}%
\vspace{-0.20cm}
\end{table*}%
\begin{table*}[t]
\centering
\caption{Results of different methods for day-night adaptation scenario on the validation set \cite{caesar2020nuscenes}. }
\vspace{-0.25cm}
\setlength{\tabcolsep}{1.1mm}{
\begin{tabular}{c|c|c|c|cccccc}
\hline
& Method & Backbone & \cellcolor{lightgray} NDS ↑& \cellcolor{lightgray} mAP ↑ & mATE ↓ & mASE ↓ & mAOE ↓ & mAVE ↓ & mAAE ↓ \\
\hline\hline
& BEVDet\cite{ huang2021bevdet} & R50 & 0.010 & 0.009 & 0.990 & 0.977 & 1.078 & 1.509&0.984 \\
Baseline & BEVDepth\cite{li2022bevdepth} & R50 & 0.050 & 0.012 & 0.042 & 0.646 & 1.129 & 1.705 & 0.915 \\
& BEVDepth\cite{li2022bevdepth} & R101 & 0.062 & 0.036 & 1.033 & 0.706 & 0.973 & 1.447 & 0.895 \\
\hline
\multirow{2}{*}{DA} & SFA\cite{wang2021exploring}(BEVDepth) & R50 & 0.092 & 0.032 & 0.995 & 0.556 & 0.993 & 1.480 & 0.948 \\
& STM3D\cite{li2022unsupervised}(BEVDepth) & R50 & 0.070 & 0.035 & 0.979 & 0.549 & 1.063 & 1.587 & 0.937 \\
\hline
\multirow{2}{*}{DA} & Ours(BEVDepth) & R50 & \textbf{0.132} & \textbf{0.054} & \textbf{0.711} & \textbf{0.465} & \textbf{1.072} & \textbf{1.504} & \textbf{0.772} \\
& Ours(BEVDepth) & R101 & \textbf{0.188} & \textbf{0.127} & \textbf{0.189} & \textbf{0.484} & \textbf{0.820} & \textbf{1.784} & \textbf{0.711} \\
\hline
\end{tabular}%
}
\label{tab:day}%
\vspace{-0.1cm}
\end{table*}%
\subsection{Experimental setup}
\label{sec:4.1}
\subsubsection{Datasets and adaptation scenarios}
We evaluate our proposed framework on nuscenes \cite{caesar2020nuscenes}, which is a large-scale autonomous-driving dataset. In order to pave the way for Unsupervised Domain Adaptation (UDA) in multi-view 3d object detection, we split the nuscenes into different paired source-target domain data. We introduce three classical and challenging cross-domain scenarios, which are \textbf{Scene}, \textbf{Weathers}, and \textbf{Day-Night} adaptation. In addition, Due to the lack of foggy weather (a normal target data), we generate a foggy dataset (Foggy-nuscenes) in various dense degrees inspired by Foggy-Cityscapes \cite{sakaridis2018semantic}. The Foggy-nuscenes dataset will be released for research. Besides, we also evaluate $M^{2}ATS$ in the continual changing scenario of increased foggy degrees.
\textbf{Scene Adaptation} We set Boston as the source scene data and realize UDA on the Singapore target domain. Since scene layouts are frequently changing in autonomous driving, the domain gap occurs in multiple scenes.
\textbf{Weathers Adaptation} The sunny weather is considered as source domain data, rainy and foggy weather is considered as target domain data. Various weather conditions are common phenomena in the real world, and multi-view 3d object detection should be reliable under such conditions.
\textbf{Day-Night Adaptation} We design daytime data as the source domain and realize UDA on the target domain (night data). Since the camera-based method has a tremendous domain gap from day to night, it is essential to explore the domain adaptation method in the day-night scenario.
\textbf{Continues Changing Adaptation} We set sunny weather data as the source domain and set continuously increased foggy degree data as the target domain. Specifically, we realize UDA from sunny to Foggy-1, Foggy-3, and Foggy-5 step by step with the degree of fog increased. Since the continual changing domain gap usually appears in autonomous driving, the domain shift is essential to be addressed. Moreover, we demonstrate the detailed information and generation method of the dataset in the appendix.
\subsubsection{Implementation details}
$M^{2}ATS$ framework is built based on BEVDepth \cite{li2022bevdepth}. According to previous work \cite{li2022bevdepth, reading2021categorical, huang2021bevdet, li2022unifying}, ResNet-50 and ResNet-101 \cite{he2016deep} serve as backbone to extract image features respectively. We adopt $256\times 704$ as image input size and the same data augmentation methods as \cite{li2022bevdepth}. We apply AdamW \cite{loshchilov2017decoupled} optimizer with 2e-4 learning rate and without any decay. For training, the source domain pretrain and UDA experiments are trained for 24 and 12 epochs \textbf{without CBGS} \cite{zhu2019class}. During inference, our method infers without any test time augmentation or model ensemble. We report the evaluation metrics following previous 3d detection works\cite{li2022bevdepth,huang2021bevdet}, including nuScenes Detection Score (NDS), mean Average Precision (mAP), as well as five True Positive (TP) metrics including mean Average Translation Error (mATE), mean Average Scale Error (mASE), mean Average Orientation Error (mAOE), mean Average Velocity Error (mAVE), mean Average Attribute Error (mAAE). All experiments are conducted on NVIDIA Tesla V100 GPUs.
\subsection{Main results}
\label{sec:4.2}
\begin{figure*}[t]
\includegraphics[width=0.95\textwidth]{./images/Vis_v3.pdf}
\centering
\vspace{-0.2cm}
\caption{ Visualizations on the benefits of our proposed method. (a) Qualitative results: The upper and bottom parts are visualization of BevDepth \cite{li2022bevdepth} and our proposed method respectively. The results are visualized on the weather adaptation scenario. (b) Visualization of feature distributions using T-SNE \cite{van2013barnes}. The \textcolor{blue}{blue spots} denote the source features, while \textcolor{red}{red spots} represent target features.}
\label{fig:vis}
\vspace{-0.2cm}
\end{figure*}
We compare our proposed method with other BEV perception methods to verify the superior performance of $M^{2}ATS$. Meanwhile, to further demonstrate our special design in addressing domain shift of LSS-based multi-view 3D object detection, we reproduce other promising 2D and mono-view 3D detection Domain Adaptation (DA) methods on BEVDepth \cite{li2022bevdepth}, \ie, SFA \cite{wang2021exploring} and STM3D \cite{li2022unsupervised}.
\noindent\textbf{Scene Adaptation} As shown in Tab.\ref{tab:scene}, $M^{2}ATS$ outperforms all the baseline methods, which obviously exceeds BEVDepth \cite{li2022bevdepth} of R50 and R101 backbone by 3.4\% and 2.4\% NDS. It thus demonstrates that our proposed method can effectively address the multi-latent spaces domain shift caused by scene and environmental change. Compared with other SOTA DA methods, $M^{2}ATS$ outperforms SFA and STM3D by 2.7\% and 2.5\% NDS respectively. And it even improves mAP by 1.9\% compared with 2nd place. The comparison further demonstrates that our proposed method is specially designed for LSS-based 3D object detection.
\noindent\textbf{Weathers Adaptation} As shown in Tab. \ref{tab:weather}, in Sunny to Foggy-3 scenario adaptation, $M^{2}ATS$ outperforms other baseline methods by a significant margin. It even exceeds BEVDepth by around 10\% in both NDS and mAP (R50 setting). Moreover, compared with SFA and STM3D, $M^{2}ATS$ improves NDS by 3.8\% and 3.2\% respectively since it utilizes multi-space domain invariant features to realize a better representation in extreme weather data. In order to evaluate the generalization of $M^{2}ATS$, we also conduct experiments on Sunny to Rainy, $M^{2}ATS$ also increases 2.4\% NDS compared with 2nd place.
\noindent\textbf{Day-Night Adaptation} The Day-Night adaptation is the most challenging scenario for camera-based methods, $M^{2}ATS$ significantly improves the detection performance and solves the domain shift problem in the Night domain. As shown in Tab. \ref{tab:day}, the tremendous domain gap makes baseline methods perform extremely poorly with only 0.062 NDS and 0.036 mAP under R101. While $M^{2}ATS$, especially with R101 as its backbone, can achieve 0.188 NDS and 0.127 mAP. Even compared with other domain adaptation methods, it also achieves a superior improvement of more than 4.0\% and 6.2\%. Since previous DA methods like STM3D and STA ignore the inaccuracy depth estimation in Night data, it thus can not effectively deal with Day-Night domain shift in the LSS-based method.
\noindent\textbf{Continues Changing Adaptation} As shown in Tab. \ref{tab:fog}, due to the page limitation, we only compare $M^{2}ATS$ with the baseline method. Along with the increased foggy degree, the baseline method shows an obvious performance degradation. However, $M^{2}ATS$ alleviates the gradually increased domain gap and outperforms the baseline method by 12.3\% NDS in the final Foggy-5 domain.
\begin{table}[t]
\begin{center}
\caption{Results of different methods for continuous changing adaptation scenario on Nuscenes-Foggy, from Sunny to Foggy-1, Foggy-3, and Foggy-5 step by step. The metric is NDS}
\vspace{-0.2cm}
\setlength{\tabcolsep}{0.8mm}{
\begin{tabular}{c|c|ccc}
\hline
Train on&Method(R50) & Foggy-1 & Foggy-3 & Foggy-5 \\
\hline
\hline
\multirow{2}{*}{Sunny}& BEVDepth \cite{li2022bevdepth}& 0.2214 & 0.1592 & 0.096\\
&Ours(BEVDepth) & \textbf{0.2835} & \textbf{0.2728} & \textbf{0.2190} \\
\hline
\end{tabular}}
\label{tab:fog}
\vspace{-0.6cm}
\end{center}
\end{table}
\subsection{Ablation study}
\label{ablation}
To better reflect the role of each component in $M^{2}ATS$, we conduct ablation experiments to analyze how each component can deal with domain shift for LSS-based BEV perception. It should be noted that the ablation study is only conducted on \textbf{Sunny-Rainy} weather adaptation. The ablation study of other scenarios is presented in the appendix.
\noindent\textbf{The effectiveness of DAT and MFA.}
As shown in Tab. \ref{tab:abl}, vanilla BEVDepth ($Ex_{0}$) can only achieve 26.8\% NDS and 19.6\% mAP when the scenario is transformed from sunny to the rainy domain. For DAT, it transfers multi-latent space knowledge to the student model via domain invariant multi-space features and more reliable pseudo labels, which are constructed by depth-aware information. As shown in $Ex_{1}$, the student model can learn pixel and instance level knowledge from DAT, NDS, and mAP are improved by 1.5\% and 3.5\% respectively. $Ex_{2}$ evaluates the benefits of mean-teacher mechanism, achieving further 0.4\% mAP improvement. By gradually aligning the multi-space feature ($Ex_{3-5}$) in the student model, our method will get a 2\% improvement in NDS, which demonstrates that it is essential to align the global-level representation of two domains in multi-latent spaces. When we combine DAT and MFA in $M^{2}ATS$ ($Ex_{6-7}$), NDS can be further enhanced to 30.5\% while mAP can achieve 24.3\%. We can come to the conclusion that NDS and mAP continuously increase with the addition of each component in DAT and MFA, demonstrating that each of these modules is necessary and effective. It also proves that DAT and MFA can compensate each other to address the domain shift in multi-latent spaces.
\begin{table}[t]
\begin{center}
\caption{Ablation studies on the Sunny to Rainy scenario. It shows the effectiveness of DAT and MFA in the framework. For DAT, it consists of three components, including depth-aware information(DA), mean-teacher(MT), and multi-latent space knowledge transfer(KT). For MFA, it concludes three-latent space alignments, which are Bev(BA), image(IA), and voxel(VA) feature alignment.}
\vspace{-0.2cm}
\setlength{\tabcolsep}{1.1mm}{
\begin{tabular}{c|ccc|ccc|cc}
\hline
Name & DA & MT & KT& BA& IA & VA & \cellcolor{lightgray} NDS ↑&\cellcolor{lightgray} mAP ↑ \\
\hline
\hline
$Ex_{0}$ & - & - & - & - & - & - & 0.268 & 0.196 \\
\hline
$Ex_{1}$ & \Checkmark & - & \Checkmark & - & - & - & 0.283 & 0.231 \\
$Ex_{2}$ & \Checkmark & \Checkmark & \Checkmark & - & - & - & 0.286 & 0.235 \\\hline
$Ex_{3}$ & - & - & - & \Checkmark & - & - &0.276 & 0.200\\
$Ex_{4}$ & - & - & - & \Checkmark & \Checkmark & - & 0.282 & 0.204\\
$Ex_{5}$ & - & - & - & \Checkmark & \Checkmark & \Checkmark & 0.288 & 0.207 \\\hline
$Ex_{6}$ & \Checkmark & -& \Checkmark & \Checkmark&\Checkmark & \Checkmark & 0.301 & 0.238 \\
$Ex_{7}$ & \Checkmark & \Checkmark & \Checkmark & \Checkmark & \Checkmark & \Checkmark & 0.305 & 0.243 \\
\hline
\end{tabular}}
\label{tab:abl}
\vspace{-0.3cm}
\end{center}
\end{table}
\begin{table}[t]
\begin{center}
\caption{The ablation study on the effectiveness of each component in depth-aware information. Pred means depth prediction, and UG means adaptive uncertainty-guided depth selection.}
\vspace{-0.2cm}
\setlength{\tabcolsep}{1.3mm}{
\begin{tabular}{c|ccc|cc}
\hline
Depth-aware: & Lidar & Pred & UG & \cellcolor{lightgray} NDS ↑& \cellcolor{lightgray} mAP ↑ \\
\hline
\hline
$Ex_{2-1}$& \Checkmark & - & - & 0.275 & 0.223 \\
$Ex_{2-2}$ & \Checkmark &\Checkmark & - & 0.278 & 0.228 \\
$Ex_{2}$ & \Checkmark & \Checkmark & \Checkmark & 0.286 & 0.235 \\
\hline
\end{tabular}}
\label{tab:abl_da}
\vspace{-0.3cm}
\end{center}
\end{table}
\begin{table}[t]
\begin{center}
\caption{The ablation study on the effectiveness of each component in Multi-latent space Knowledge Transfer. PL means transferring instance-level pseudo labels. BEV, Voxel, and Image stand for transferring on corresponding latent spaces.}
\vspace{-0.2cm}
\setlength{\tabcolsep}{0.8mm}{
\begin{tabular}{c|cccc|cc}
\hline
Latent Space: & PL & BEV & Voxel & Image & \cellcolor{lightgray} NDS ↑& \cellcolor{lightgray} mAP ↑ \\
\hline
\hline
$Ex_{2-3}$& \Checkmark& - & - & - & 0.280 & 0.213 \\
$Ex_{2-4}$& \Checkmark& \Checkmark & - & - & 0.283 & 0.222 \\
$Ex_{2-5}$& \Checkmark & \Checkmark &\Checkmark& - & 0.285 & 0.230 \\
$Ex_{2}$ & \Checkmark & \Checkmark & \Checkmark&\Checkmark & 0.286 & 0.235 \\
\hline
\end{tabular}}
\label{tab:abl_kt}
\vspace{-0.45cm}
\end{center}
\end{table}
\noindent\textbf{Detailed ablation study of DAT}
We study the effectiveness of depth-aware information composition and multi-latent knowledge transferring in DAT.
As shown in Tab. \ref{tab:abl_da}, only taking lidar ground truth to replace depth prediction ($Ex_{2-1}$) can improve 0.7\% NDS and 2.7\% mAP compared with $Ex_{0}$. The obviously increased mAP demonstrates that lidar data plays an important role in domain invariant voxel feature construction. However, due to the sparse property of lidar data, we utilize dense depth prediction to composite sparse lidar. In ($Ex_{2-2}$), NDS and mAP can achieve 27.9\% and 22.8\%, which only have limited improvement compared with $Ex_{2-1}$. Therefore, we introduce uncertainty guidance to adaptively select more reliable and task-relevant depth predictions. $Ex_{2}$ has obvious performance progress compared with $Ex_{2-1}$ and $Ex_{2-2}$, demonstrating the uncertainty-guided depth selection can reduce the domain shift caused by domain specific depth prediction.
As shown in Tab. \ref{tab:abl_kt}, applying for knowledge transfer in different latent spaces can be beneficial to $M^{2}ATS$. With pseudo label, BEV, voxel, and image feature transferred between DAT and student model, NDS is gradually improved from 26.8\% to 28.6\%, and mAP is improved from 19.6\% to 23.5\%. The improved performance demonstrates that multi-space global-level alignment is introduced to ease different domain shifts in each latent space. It shows that pseudo label and three spaces knowledge are all essential for the student model to address multi-latent space domain gaps, which is constructed by depth-aware information.
\subsection{Qualitative analysis}
\label{sec:4.4}
We further present some visualization results of the prediction produced by the $M^{2}ATS$ and the baseline BEVDpeth~\cite{li2022bevdepth}, as shown in Fig. \ref{fig:vis} (a). It is quite clear that the BEVDpeth fails to locate the objects well, while $M^{2}ATS$ yields more accurate localization results as its predicted \textcolor{green}{green box} overlaps better with the ground truth \textcolor{red}{red box}. We can also observe that $M^{2}ATS$ can detect objects that baseline ignores, demonstrating the superiority of $M^{2}ATS$ in object detection and presenting great potential in deploying to real-world autonomous driving applications. The visualization in Fig. \ref{fig:vis} (b) further verifies the explicit cross domain ability of $M^{2}ATS$. As a clear separation can be seen in the clusters of the \textcolor{blue}{blue-source} and \textcolor{red}{red-target} dots produced by BEVDepth, the features generated by $M^{2}ATS$ get closer together further demonstrates the ability of our proposed method in representing domain invariant features.
\begin{figure*}[t]
\includegraphics[width=0.98\textwidth]{./images/fog_v3.png}
\centering
\vspace{-0.65cm}
\caption{The visualization of Foggy-Nuscenes dataset. The first row is the original multi-view images in Nuscenes \cite{caesar2020nuscenes}, and the last three rows demonstrate images of increased foggy degree.}
\label{fig:fog}
\vspace{-0.3cm}
\end{figure*}
\section{Conclusion and discussion of limitations}
We explore the UDA problem in Multi-View 3D object detection and propose a novel Multi-level Multi-space Alignment Teacher-Student ($M^{2}ATS$) framework to fully ease multi-latent space domain shift for LSS-based BEV perception. On the one hand, Depth-Aware Teacher (DAT) leverages depth-aware information to generate reliable pseudo labels and multi-space domain-invariant features, which are transferred to the student model. On the other hand, the Multi-space Feature Aligned (MFA) student model utilizes source and target domain data to align the global-level feature representation. $M^{2}ATS$ achieves SOTA performance in three challenge UDA and continual changing domain gap scenarios. For limitations, the teacher-student framework brings more computational cost and extra small parameters (discriminator) during training. However, the student model keeps the same forward time and computational cost with a baseline in inference.
\section{Appendix}
In the supplementary material, we first present more details of our generated Foggy Nuscenes dataset in Sec .\ref{sec:1}, which aims at adding a foggy weather scene in Nuscenes \cite{caesar2020nuscenes} and providing an open source dataset (Foggy-Nuscenes) for research in autonomous driving.
Secondly, in Sec .\ref{sec:2}, we show the details of each scenario and the partition of dataset.
In Sec .\ref{sec:3}, we then provide additional and detailed cross domain training strategy.
In Sec .\ref{sec:4}, the extra ablation studies are conducted on Day-night cross-domain scenario, which investigate the impact of each component in the Multi-level Multi-space Alignment Teacher-Student ($M^{2}ATS$) framework.
Finally, we provide additional qualitative analysis on Day-night scenario to further evaluate the effectiveness of our proposed method in Sec~\ref{sec:5}.
\begin{table*}[t]
\begin{center}
\caption{The partitioning and details of four UDA scenarios. Frames means the number of multi-view image frames in the datasets.}
\vspace{-0.2cm}
\setlength{\tabcolsep}{3mm}{
\begin{tabular}{c|c|c|c|c|c}
\hline
UDA scenarios & Domain & Training sequences & Frames & Validation sequences & Frames \\
\hline
\hline
\multirow{2}{*}{Scene changing}&Source(Boston) & 857 & 15695 & 77 & 3090\\
&Target(Singapore) & 693 & 12435 & 73 & 2929\\
\hline
\multirow{2}{*}{Weather changing}&Source(Sunny) & 1276 & 23070 & 126 & 5051\\
&Target(Rainy) & 274 & 5060 & 24 & 968\\
\hline
\multirow{2}{*}{Weather changing}&Source(Nuscenes) & 1550 & 28130 & 150 & 6019\\
&Target(Foggy-3) & 1550 & 28130 & 150 & 6019\\
\hline
\multirow{2}{*}{Day-night changing}&Source(Day) & 1367 & 24745 & 135 & 5417\\
&Target(Night) & 183 & 3385 & 15 & 602\\
\hline
\multirow{4}{*}{Continual changing}&Source(Nuscenes) & 1550 & 28130 & 150 & 6019\\
&Target-1(Foggy-1) & 1550 & 28130 & 150 & 6019\\
&Target-2(Foggy-3) & 1550 & 28130 & 150 & 6019\\
&Target-3(Foggy-5) & 1550 & 28130 & 150 & 6019\\
\hline
\end{tabular}}
\label{tab:data}
\end{center}
\vspace{-0.3cm}
\end{table*}
\subsection{Supplementary description of foggy Nuscenes dataset}
\label{sec:1}
We apply the fog simulation pipeline \cite{sakaridis2018semantic} to the multi-view images provided in the Nuscenes dataset \cite{caesar2020nuscenes}. specifically, we generate synthetic foggy images for all scenes of training, validation, and test set, which reserve original annotation of 3D object detection task. We utilize five different density degree of foggy simulator to construct Foggy-Nuscenes dataset, including Foggy-1, Foggy-2, Foggy-3, Foggy-4, and Foggy-5 (gradually increasing fog density). As shown in Fig .\ref{fig:fog}, we adopt Foggy-1, Foggy-3, and Foggy-5 as the experimental datasets for weather adaptation and continual changing scenario, which have an obvious domain gap with original Nuscenes dataset \cite{caesar2020nuscenes}.
\subsection{Additional details of UDA scenarios}
\label{sec:2}
In this paper, we utilize Nuscenes \cite{caesar2020nuscenes} and Foggy-Nuscenes datasets to generate three classical and one continual changing UDA scenarios. As shown in Tab .\ref{tab:data}, for Scene changing scenario, We set Boston as the source scene data and realize UDA on the Singapore target domain. The source domain contains 15.6k frames labeled data and target domain has 12.4k frames unlabeled data. For Weather changing scenario, the sunny weather is considered as source domain data, rainy and foggy weather is considered as target domain data. In the second row, the source domain has 1276 training sequences and rainy target domain has 274 training sequences. In the third row, we leverage all Nuscenes dataset as source domain data and set Foggy-3 as target domain data. As we can see, in Day-night changing scenario, we design daytime data as the source domain and realize UDA on the target domain (night data). Since the source domain data is way more larger than the target domain data and the camera can not capture night-time data clearly, which is considered as the most challenging adaptation scenarios. Finally, we set all Nuscenes sequence as the source domain data and set continuously increased foggy degree data as the target domain. The various target domains are of the same sequence and scene with source domain, but the different foggy degree on the frames bring significant domain gap. We introduce this continual changing scenario to demonstrate the continual domain adaptation ability of our proposed method.
\begin{table}[t]
\begin{center}
\caption{Ablation studies on the Day-night scenario. It shows the effectiveness of DAT and MFA in the framework. For DAT, it consists of three components, including depth-aware information(DA), mean-teacher(MT), and multi-latent space knowledge transfer(KT). For MFA, it concludes three-latent space alignments, which are Bev(BA), image(IA), and voxel(VA) feature alignment.}
\vspace{-0.2cm}
\setlength{\tabcolsep}{1.0mm}{
\begin{tabular}{c|ccc|ccc|cc}
\hline
Name & DA & MT & KT& BA& IA & VA & \cellcolor{lightgray} NDS ↑&\cellcolor{lightgray} mAP ↑ \\
\hline
\hline
$Ex_{0}$ & - & - & - & - & - & - & 0.050 & 0.012 \\
\hline
$Ex_{1}$ & \Checkmark & - & \Checkmark & - & - & - & 0.103 & 0.034 \\
$Ex_{2}$ & \Checkmark & \Checkmark & \Checkmark & - & - & - & 0.104 & 0.041 \\\hline
$Ex_{3}$ & - & - & - & \Checkmark & - & - &0.065 & 0.038\\
$Ex_{4}$ & - & - & - & \Checkmark & \Checkmark & - & 0.071 & 0.042\\
$Ex_{5}$ & - & - & - & \Checkmark & \Checkmark & \Checkmark & 0.098 & 0.051 \\\hline
$Ex_{6}$ & \Checkmark & -& \Checkmark & \Checkmark&\Checkmark & \Checkmark & 0.124 & 0.049 \\
$Ex_{7}$ & \Checkmark & \Checkmark & \Checkmark & \Checkmark & \Checkmark & \Checkmark & 0.132 & 0.054 \\
\hline
\end{tabular}}
\label{tab:abl_ap}
\end{center}
\vspace{-0.3cm}
\end{table}
\subsection{Additional implementation details}
\label{sec:3}
Our training process of cross domain can be divided into 2 stages: pretraining on source domain and transfer training from source to target domain.
Firstly, in order to fully leverage the feature extraction ability of the model \cite{li2022bevdepth}, we load the backbone of ImageNet \cite{deng2009imagenet} pretrained parameters. Then we train the model on the source domain data in a supervised manner, which aims to obtain the source domain pretrained model parameters.
In cross domain phase, we load the integrated model parameters, which are pretrained on source domain, into the student model and conduct transferred training for 12 epochs.
$M^{2}ATS$ framework adopts source domain and target domain data as input, and only leverages source domain annotation. During training, we alternate Depth-Aware Teacher knowledge transferred and Multi-space Feature Alignment training to update student model. Finally, we directly infer the student model on target domain data and achieve the result of our proposed method.
\subsection{Additional ablation study on day-night scenario}
\label{sec:4}
The $M^{2}ATS$ framework contains a Depth-Aware Teacher (DAT) and a Multi-space Feature Aligned (MFA) student model.
To evaluate each component of the proposed $M^{2}ATS$ framework, we conduct ablation experiments to analyze how each component can mitigate domain shift for LSS-based BEV perception. It should be noted that the ablation study is conducted on the most challenging \textbf{Day-Night} scenario, in which other methods suffer tremendous performance degradation.
\begin{table}[t]
\begin{center}
\caption{The ablation study on the effectiveness of each component in depth-aware information. Pred means depth prediction, and UG means adaptive uncertainty-guided depth selection.}
\vspace{-0.2cm}
\setlength{\tabcolsep}{1.3mm}{
\begin{tabular}{c|ccc|cc}
\hline
Depth-aware: & Lidar & Pred & UG & \cellcolor{lightgray} NDS ↑& \cellcolor{lightgray} mAP ↑ \\
\hline
\hline
$Ex_{2-1}$& \Checkmark & - & - & 0.068 & 0.028 \\
$Ex_{2-2}$ & \Checkmark &\Checkmark & - & 0.084 & 0.032 \\
$Ex_{2}$ & \Checkmark & \Checkmark & \Checkmark & 0.104 & 0.041 \\
\hline
\end{tabular}}
\label{tab:abl_da_ap}
\end{center}
\vspace{-0.3cm}
\end{table}
\begin{table}[t]
\begin{center}
\caption{The ablation study on the effectiveness of each component in Multi-latent space Knowledge Transfer. PL means transferring instance-level pseudo labels. BEV, Voxel, and Image stand for transferring on corresponding latent space.}
\vspace{-0.2cm}
\setlength{\tabcolsep}{0.8mm}{
\begin{tabular}{c|cccc|cc}
\hline
Latent Space: & PL & BEV & Voxel & Image & \cellcolor{lightgray} NDS ↑& \cellcolor{lightgray} mAP ↑ \\
\hline
\hline
$Ex_{2-3}$& \Checkmark& - & - & - & 0.076 & 0.036 \\
$Ex_{2-4}$& \Checkmark& \Checkmark & - & - & 0.096 & 0.039 \\
$Ex_{2-5}$& \Checkmark & \Checkmark &\Checkmark& - & 0.101 & 0.044 \\
$Ex_{2}$ & \Checkmark & \Checkmark & \Checkmark&\Checkmark & 0.104 & 0.041 \\
\hline
\end{tabular}}
\label{tab:abl_kt_ap}
\end{center}
\vspace{-0.3cm}
\end{table}
\begin{figure*}[t]
\includegraphics[width=0.95\textwidth]{./images/vis_ap_v2.png}
\centering
\caption{Visualizations on the benefits of our proposed method. The upper and bottom parts are visualization of BevDepth \cite{li2022bevdepth} and our proposed method respectively. The \textcolor{red}{red box} is the Ground Truth, and the \textcolor{green}{green box} is the predictions.}
\label{fig:vis_ap}
\vspace{-0.3cm}
\end{figure*}
\noindent\textbf{The effectiveness of DAT and MFA.}
As shown in Tab. \ref{tab:abl_ap}, due to the faint light of target domain (night-time), vanilla BEVDepth ($Ex_{0}$) can only achieve 5.0\% NDS and 1.2\% mAP when the scenario is transformed from source domain (daytime). For DAT, it transfers multi-latent space knowledge to the student model via pixel-level multi-space features and instance-level pseudo labels, which are constructed by depth-aware information. As shown in $Ex_{1}$, the student model can learn domain-invariant knowledge from DAT, NDS and mAP are
thus improved by 5.3\% and 2.2\% respectively. $Ex_{2}$ evaluates the benefits of mean-teacher mechanism, which brings 0.7\% mAP improvement. As we can see, depth-aware information plays an important role in cross domain transferred learning and greatly improves NDS compared with baseline. By gradually aligning the multi-space feature ($Ex_{3-5}$) in the MFA student model, our method get a 4.8\% and 3.9\% improvement in NDS and mAP, which demonstrates that it is essential to align the global-level representation of two domains in multi-latent spaces. The MFA student model has a great improvement on mAP compared with baseline, in which the global-level alignment focuses more on classification and location of objects.
When we combine DAT and MFA in $M^{2}ATS$ ($Ex_{6-7}$), NDS can be further enhanced to 13.2\% while mAP can achieve 5.4\%. We can come to the conclusion that NDS and mAP continuously increase with the addition of each component in DAT and MFA, showing similar results with the previous ablation study on submission. It also proves that DAT and MFA can compensate each other to address the domain shift in multi-latent spaces.
\noindent\textbf{Detailed ablation study of DAT}
We study the effectiveness of depth-aware information composition and multi-latent knowledge transferring in DAT.
As shown in Tab. \ref{tab:abl_da_ap}, only taking lidar ground truth to replace depth prediction ($Ex_{2-1}$) can only improve 1.8\% NDS and 1.6\% mAP compared with BEVDepth ($Ex_{0}$). The obviously increased performance demonstrates that lidar data plays an important role in domain-invariant voxel feature construction. However, due to the sparse property of lidar data, we utilize dense depth prediction to composite sparse lidar data. In ($Ex_{2-2}$), NDS and mAP can achieve 8.4\% and 3.2\%, which only have limited improvement compared with $Ex_{2-1}$. Therefore, we introduce uncertainty guidance to adaptively select more reliable and task-relevant depth predictions to composite sparse lidar data. Due to the reliable composite depth-aware information, $Ex_{2}$ has obvious performance progress compared with $Ex_{2-2}$, which further improves 2.0\% NDS and 0.9\% mAP.
The results demonstrate the uncertainty-guided depth selection can reduce the domain shift caused by domain specific depth prediction.
As shown in Tab. \ref{tab:abl_kt_ap}, applying knowledge transfer on different latent spaces can be beneficial to $M^{2}ATS$. With pseudo label, BEV, voxel, and image feature transferred between DAT and student model, NDS is gradually improved from 5.0\% to 10.4\%, and mAP is improved from 1.2\% to 4.1\%. The results show that pseudo label and the knowledge of three spaces are all essential for the student model to address multi-latent space domain gaps, which is constructed by depth-aware information. In conclusion, leveraging depth-aware information has a significant impact on addressing multi-space domain shift in BEV perception, which transfers domain-invariant knowledge from teacher model to student model.
\subsection{Additional qualitative analysis}
\label{sec:5}
In contrast with the visualization on submission, we further present some visualization results of the prediction produced by the $M^{2}ATS$ and the baseline BEVDpeth~\cite{li2022bevdepth} on the most challenging scenario (day-night), as shown in Fig. \ref{fig:vis_ap}. Due to the faint light of night-time data, we can not classify and locate objects even with the naked eye, not to mention camera-based methods. It is quite clear that the BEVDpeth has various inaccurate and missing detection, while $M^{2}ATS$ yields more accurate localization results as its predicted \textcolor{green}{green box} overlaps better with the ground truth \textcolor{red}{red box}.
We can also observe that $M^{2}ATS$ can detect objects that baseline ignores, demonstrating the superiority of $M^{2}ATS$ in object detection and presenting great potential in deploying to real-world autonomous driving applications. However, our proposed method still has some missing detection which inspires us to pay more attention on the BEV perception in night-time.
{\small
\bibliographystyle{ieee_fullname}
| {'timestamp': '2022-12-01T02:18:27', 'yymm': '2211', 'arxiv_id': '2211.17126', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17126'} | arxiv |
\section{Introduction}
Several studies have demonstrated that abstract, minimal representations are not only visually pleasing but also helpful in conveying an idea more effectively by emphasizing the essence of the subject~\cite{Hertzmann_2020,biederman1988surface}. In this paper, we concentrate on converting photographs of natural scenes to sketches as a prominent minimal representation.
Converting a photograph to a sketch involves abstraction, which requires the ability to understand, analyze, and interpret the complexity of the visual scene.
A scene is composed of multiple objects, relations between the foreground and background, and an inherent hierarchy between them (see~\Cref{fig:im_complex}).
Therefore, when sketching a scene, the artist has many options regarding how to express the various components and the relations between them (see~\Cref{fig:drawing_style_lob}).
\input{files/figures/complexity_level}
\begin{figure}
\setlength{\belowcaptionskip}{-4pt}
\setlength{\tabcolsep}{1.5pt}
\centering
\includegraphics[width=1\linewidth]{figs/drawing_style_lob2.pdf}
\vspace{-0.5cm}
\caption{Drawings of different scenes created by different artists. Notice the significant differences in style and levels of abstraction between each drawing --- moving from more detailed and precise to more abstract from left to right.
In the second row, we demonstrate how the level of abstraction not only varies \textit{between} drawings, but also \textit{within} the \textit{same} drawing. In each pair, we highlight less abstract (in red) and more abstract (in blue) regions of the drawing. For example, in the middle drawing the person highlighted in red is drawn with a high level of detail as this is the object that the artist chose to emphasize.}
\label{fig:drawing_style_lob}
\end{figure}
In a similar manner, computational sketching methods must deal with scene complexity and consider a variety of abstraction levels. Our work focuses on the challenging task of \emph{scene} sketching while doing so using multiple \emph{types} and multiple \emph{levels} of abstraction.
Only a few previous works attempted to produce sketches with multiple levels of abstraction.
However, these works focus specifically on the task of \emph{object} sketching~\cite{vinker2022clipasso,Deep-Sketch-Abstraction} or \emph{portrait} sketching~\cite{Berger2013}, and often simply use the number of strokes to define the level of abstraction.
We are not aware of any previous work that attempts to separate different \emph{types} of abstractions.
We define two axes that represent two different types of abstractions, and produce gradual levels of abstraction by moving along these axes.
The first axis governs the \emph{fidelity} of the sketch. This axis moves from more precise sketches, where the sketch composition follows the geometry and structure of the photograph to more loose sketches, where the composition relies more on the semantics of the scene.
We illustrate this axis in~\Cref{fig:semantic_axis}.
The leftmost sketch is most faithful to the geometry of the input image, and as we move right, the sketch becomes less precise, deviating from the contours of the input and relying more on key semantic aspects of the input image. Observe the flowers in the rightmost sketch are added to the front, yet these flowers deviate significantly from the \textit{specific} flowers present in the input.
\begin{figure}[h]
\centering
\setlength{\belowcaptionskip}{-4pt}
\includegraphics[width=1\linewidth]{figs/semantic_axis.pdf}
\caption{The \emph{fidelity} axis. From left to right, using the same number of strokes the sketches gradually depart from the geometry of the input image, but still convey the semantic meaning of the scene. The first sketch follows the exact contours of the mountains on the horizon
while the mountains and flowers in the rightmost sketch are a more abstract representation of the scene's semantics.}
\label{fig:semantic_axis}
\vspace{-0.3cm}
\end{figure}
\begin{figure}[h]
\centering
\includegraphics[width=1\linewidth]{figs/sparse_axis.pdf}
\caption{The \emph{simplification} axis. On the left, we start with a more detailed sketch and as we move to the right the sketch is gradually simplified while still preserving recognizability.}
\label{fig:sparse_axis}
\vspace{-0.1cm}
\end{figure}
The second axis governs the level of detail the sketch contains and moves from more detailed depictions to sparser depictions, which appear more abstract. Hence, we refer to this axis as the \textit{simplicity} axis.
An example can be seen in \Cref{fig:sparse_axis}, where the same general characteristics of the scene (\emph{e.g}\onedot the mountains and flowers) are captured in all sketches, but with gradually fewer details.
To deal with scene complexity, we separate the foreground and background elements in the scene and sketch each of them separately. This explicit separation and the disentanglement into two abstraction axes provide a more flexible framework for computational sketching. Users can choose the desired sketch along the two abstraction axes, and apply different abstractions to the foreground and background elements according to their goals and personal taste from a range of possibilities, as illustrated in ~\Cref{fig:teaser}.
We define a sketch as a set of B\'{e}zier\xspace curves, and train a simple multi-layer perceptron (MLP) network to map an initial set of stroke parameters to their final locations forming the final sketch.
The training process is done per image (e.g. without an external dataset) and is guided by a pre-trained CLIP-ViT~\cite{CLIP,dosovitskiy2020image} model, leveraging its powerful ability to capture the semantics and global context of the entire scene.
To realize the \emph{fidelity} axis, we utilize different intermediate layers of CLIP-ViT to guide the training process, where shallow layers preserve the geometry of the image and deeper layers encourage the creation of looser sketches that rely more on the semantics of the scene. To realize the \emph{simplicity} axis, we jointly train an additional MLP network that learns how to best discard strokes without harming the recognizability of the sketch.
As shall be discussed, the use of the networks over a direct optimization-based approach is crucial for achieving a learned simplification of the sketch.
To alter the level of simplicity, we introduce two loss functions that are used to balance the faithfulness and sparsity of the sketch with respect to the input.
We gradually alter the relative strength of these two functions in an exponential fashion to define a perceptually smooth sequence of simplifications.
This choice of an exponential relation also aligns well with the Weber-Fechner law~\cite{fechnerlaw,Weber1834-ms} which notes that relations between a perceived change
and an actual change in a physical stimulus in many cases are non-linear.
The resulting sketches demonstrate our ability to cope with various scenes and to capture their core characteristics, while providing gradual abstraction along both the fidelity and simplicity axes.
We compare our results with existing methods for semantically-aware scene sketching.
We additionally evaluate our results quantitatively and demonstrate that the generated sketches, although abstract, successfully preserve the geometry and semantics of the input scene.
\section{Results}~\label{sec:results}
In the following sections, we demonstrate the performance of our scene sketching technique qualitatively and quantitatively. We additionaly provide visual comparisons to state-of-the-art sketching methods.
All results presented in this section were generated using the object-background separation approach. Further analysis, comparisons, and results are provided in the appendix.
\subsection{Qualitative Evaluation}
In~\Cref{fig:qualitative_pairs,fig:teaser} we show sketches at different levels of abstraction on various scenes generated by our method. For each image, we choose two representative sketches (one detailed and one more abstract) from the abstraction matrix to demonstrate the ability of our method to produce diverse levels of abstraction. Notice how the sketches are still easy to recognize as depicting the same scene even though they vary significantly in their abstraction level.
\begin{figure}
\centering
\includegraphics[width=1\linewidth]{figs/two_axes.pdf}
\vspace{-0.6cm}
\caption{Examples of smooth levels of abstraction along our abstraction axes.}
\vspace{-0.3cm}
\label{fig:two_axes}
\end{figure}
In the top of~\Cref{fig:two_axes} we show sketch abstractions along the \textit{fidelity} axis. Sketches become less precise as we move from left to right, while still conveying the semantics of the images.
For example, in the leftmost sketch of the house and the giraffe, the strokes emphasize areas with strong edges, such as the dark sky above the house and the shadow on the giraffe's legs. As we move to the right, the mountains behind the house and the shape of the tree behind the giraffe and the giraffe's body become more loose.
Importantly, even though the composition of the sketches becomes less precise, the sketches still capture the essence of the scene.
At the bottom of~\Cref{fig:two_axes} we show sketch abstractions along the \textit{simplicity} axis. Our method successfully simplifies the sketches in a smooth fashion, while still capturing the core characteristics of the scene. For example, notice how the unique pose of the ballerina is preserved across the images, even when sketched using a small number of strokes.
Observe that this simplification is achieved \textit{implicitly} through our iterative sketch simplification technique.
\input{files/figures/scene_sketching_comparison}
\input{files/figures/clipasso_comparison}
\subsection{Comparison with Existing Methods}
In ~\Cref{fig:scene_sketching_comparisons} we present a comparison with three state-of-the-art methods for scene sketching~\cite{yi2020unpaired, li2019photo, chan2022learning}.
As a simple baseline approach, we additionally apply an edge detector filter over the input image using the Sobel operator~\cite{kanopoulos1988design} followed by the sketch simplification model from Simo-Serra~\emph{et al}\onedot~\cite{simo2016learning} (referred as ``Edge Extraction'').
On the right, we present three sketches produced by our method depicting three representative levels of abstraction.
The sketches produced by UPDG~\cite{yi2020unpaired} and Chan~\emph{et al}\onedot~\cite{chan2022learning} are detailed, closely following the contours of the input images (e.g., such as the buildings in row $2$).
The sketches produced by these methods are most similar to the sketches shown in the leftmost column of our set of results, which also align well with the input scene structure.
The sketches produced by Li~\emph{et al}\onedot~\cite{li2019photo} (marked ``Photo-Sketching'') are less detailed, and may lack the semantic meaning of the input scene. For example, in the first row it is difficult to identify the sketch as being that of a person.
In contrast, our approach can produce sparse sketches while faithfully maintaining the semantics of the scene.
Importantly, none of the alternative methods can produce sketches with varying abstraction levels.
For example, observe the different levels of detail in the hair of the woman in the first row, ranging from a highly-detailed depiction to a scribble-like sketch with a few strokes.
We do note that in some cases, our sketches may lack some details such as the legs of the dog in the rightmost image and the windows of the buildings in the second row.
Finally, in contrast to the methods above, our sketches are provided in vector format, allowing the user to easily change the stroke style, as well as apply various post-processing operations.
In~\Cref{fig:clipasso_comparisons1} we provide a comparison to CLIPasso~\cite{vinker2022clipasso}.
For each scene, we present sketches obtained by CLIPasso using $128$ and $64$ strokes, respectively, which is approximately equal to the number of strokes returned by our implicit simplification.
As can be seen, when operating over a complete scene image, CLIPasso struggles in balancing the emphasis placed on the subject and the details provided in the background.
On the right, we present the sketches produced by our method at two levels of abstraction. As can be seen, our method is able to capture the scene semantics and structure even when composing a sparse sketch. In the appendix, we provide an additional comparison to CLIPasso without our scene decomposition technique.
In~\Cref{fig:clipasso_comparisons2}, we applied CLIPasso on the masked object and obtained the abstraction by explicitly specifying the number of strokes (\emph{i.e}\onedot $64,32,16,$ and $8$ strokes). In the second and third rows we show the simplification results obtained by our method, at two different fidelity levels.
Since CLIPasso only offers a single axis of abstraction (mostly governed by simplification), the fidelity level of the sketch can not be explicitly controlled.
Additionally, unlike CLIPasso, where the user must manually determine the number of strokes required to achieve different levels of abstraction, our approach \textit{learns} the desired number of strokes.
Lastly, observe that since each sketch of CLIPasso is generated independently, the resulting sketches may not portray a gradual, smooth simplification of the sketch since each optimization process may converge to a different local minimum. By training an MLP network to \textit{learn} this gradual simplification, our resulting sketches depict a smoother simplification, where each sketch is a simplified version of the previous one.
\subsection{Quantitative Evaluation}
In this section, we provide a quantitative evaluation of our method's ability to produce sketch abstractions along both the simplicity and fidelity abstraction axes.
To compute our quantitative metrics, we collected a variety of images spanning five classes of scene imagery: people, urban, nature, indoor, and animals. We collected eight images for each class, and for each image we obtained the $4\times 4$ sketch abstraction matrix using our sketching technique -- resulting in a total number of $640$ sketches.
\input{files/figures/geometry_preservation}
\paragraph{\textbf{Fidelity Changes}}
We begin by analyzing the ability to produce sketches at different levels of fidelity.
As we move right along the fidelity axis, we should expect the geometry of the sketches to increasingly deviate from that of the original input.
To assess this aspect of the generated sketches, we compute the MS-SSIM~\cite{wang2003multiscale} score between the edge map (extracted using XDoG~\cite{Winnemller2012XDoGAE}) and each generated sketch.
In~\Cref{tb:geometry_metrics_by_fidelity} we show the average MS-SSIM score across all images in the same scene category, split by the four fidelity levels.
As we move to the right along the fidelity axis, the MS-SSIM score gradually decreases, indicating that the sketches gradually become ``looser'' with respect to the input geometry.
\input{files/figures/recognizability_metrics}
\input{files/figures/quantitative_num_strokes}
\vspace{-0.25cm}
\paragraph{\textbf{Sketch Recognizability}}
It is essential to ensure that the sketches remain recognizable as depicting the same input scene across different levels of abstraction.
To evaluate this, we define a set of $150$ object class names taken from commonly used image classification and object detection datasets~\cite{lin2014microsoft,krizhevsky2009learning}. Using a pre-trained ViT-B/16 CLIP model (different than the one used for training), we performed zero-shot image classification over each input image and the corresponding $16$ generated sketches.
We then computed the percent of sketches where one of the top $3$ image classes was present in the sketch's top $3$ classes.
We consider the top $3$ predicted classes since a scene image naturally contains multiple objects to be captured by the classifier and their order may slightly vary between the original input image and the generated sketches.
~\Cref{tb:recognizability_metrics} show the average score across all images belonging to the same scene class, splitted between fidelity and simplicity levels.
Observe that the recognizability of the sketches remains relatively consistent across different simplicity levels, with a naturally slight decrease as we increase the abstraction level. This indicating that our method is able to capture the core characteristics of the scene image even at high simplicity levels, as desired.
Across different fidelity levels, we observe a rather large decrease in the recognition score in the first level for several classes (animals and people). This discrepancy can be attributed to the first fidelity level capturing image structure.
For the remaining fidelity levels, we achieve much higher score across all scene categories, indicating that the sketches along the fidelity axis indeed capture the image semantics.
We provide some example classification predictions in the appendix.
\paragraph{\textbf{Simplicity Levels}}
We examine our method's ability to generate sketches at varying levels of simplicity. For that purpose, we measure the final number of strokes used to generate the sketches.
We extract this information from the generated sketch SVGs across all $640$ sketches.
We present the results in~\Cref{fig:quantitative_num_strokes}, split between the different fidelity levels (indicated by different colors) and simplicity levels (shown along the x-axis). As can be seen, the number of strokes decreases as we move along the simplicity axis, across all fidelity levels.
\section{Summary and Future Work}
\label{sec:discussion}
We presented a method for performing scene sketching using different types and multiple levels of abstraction.
We disentangle the concept of sketch abstraction into two axes: \textit{fidelity} and \textit{simplicity}.
We demonstrated the ability to cover a wide range of abstractions across various challenging scene images of varying complexities.
There are several limitations to our method. First, since we separate foreground and background, and generate many sketches per one scene, generating a $4x4$ matrix of abstractions requires three hours on a single commercial GPU. Although further optimization is possible, sketches along the simplicity axis depends on the previous step.
Second, there are cases where some sketches of the resulting matrix contain unwanted artifacts, see the additional results in the appendix. However, in most cases, there are sufficient high-quality alternative sketches at various levels of fidelity and simplicity.
Third, we defined two axes for sketch abstraction, however, other axes of abstraction could be defined. Lastly, our resulting sketches cover only a portion of each of the axes. A future extension could focus on further extending these axes.
This work has focused on generating sketches of an input static scene image, an interesting future direction could extend the work to support video. Finally, future potential uses of our proposed method could focus on generating image-sketch paired datasets containing a range of styles and abstractions. Such data could potentially be used to train multi-modal machine learning algorithms.
\section{Related Work}
Free-hand sketch generation differs from edge-map extraction methods \cite{canny1986computational, Winnemller2012XDoGAE} in that it attempts to produce sketches that are representative of the style of human drawing to some extent. Yet, there are significant differences in drawing styles among individuals depending on their goals, skill levels, and more, see~\Cref{fig:drawing_style_lob}. As such, computation sketching methods, which aim to mimic human drawing, must consider a wide range of sketch representations.
This ranges from methods aiming to produce sketches that are grounded in the edge map of the input image~\cite{li2019photo,xie2015holistically,tong2021sketch,Deformable_Stroke}, to those that aim to produce sketches that are more abstract \cite{bhunia2021doodleformer,CLIPDraw,vinker2022clipasso,ha2017neural,qi2021sketchlattice,ge2021creative}. Several works have attempted to develop a unified algorithm that can output sketches with a variety of styles \cite{chan2022learning,yi2020unpaired,liu2021neural}. There are, however, only a few works that attempt to provide various levels of abstraction~\cite{Berger2013,Deep-Sketch-Abstraction,vinker2022clipasso}.
In the following we elaborate on the relevant previous methods, focusing on scene-sketching approaches.
We refer the reader to \cite{xu2022deep} for a comprehensive survey on computation sketching techniques.
\subsection{Photo-Sketch Synthesis}
Various works formulate the sketch generation task as an image-to-image translation task using paired data of images and the corresponding sketches~\cite{li2019im2pencil,yi2019apdrawinggan,li2019photo,artline}.
Others approach the translation task via unpaired data, often relying on a cycle consistency constraint~\cite{yi2020unpaired,song2018learning,chan2022learning}.
Li et al.~\cite{li2019photo} introduce a GAN-based contour generation algorithm and utilize multiple ground truth sketches to guide training to account for diversity present in human sketches.
Yi et al.~\cite{yi2020unpaired} generate portrait drawings with unpaired data via an adversarial training scheme by employing a cycle-consistency objective and a discriminator trained to learn a specific style.
As these works rely on curated datasets, they require training a new model for each desired style while supporting a single level of sketch abstraction.
A different approach for image-sketch synthesis formulates the sketching task as a multi-agent referential game in which two reinforcement learning agents must communicate visual concepts to each other through sketches \cite{qiu2021emergent,mihai2021learning,Zhou2018LearningTS}.
Recently, Chan et al.~\cite{chan2022learning} propose an unpaired GAN-based approach. They train a generator to map a given image into a sketch with multiple styles defined explicitly from four existing sketch datasets with a dedicated model trained for each desired style.
They utilize a CLIP-based loss between the sketch and input image to achieve semantically-aware sketches. However, their sketches tend to be more geometric in nature, compared to our method which can generate sketches at multiple levels of abstraction, including those with both a precise and loose depiction of the input.
Importantly, compared to existing work, our approach does not rely on any explicit dataset and is not limited to a pre-defined set of styles. Instead, we leverage the powerful semantics captured by a pre-trained CLIP model~\cite{CLIP}.
Additionally, our work is the only one among the alternative scene sketching approaches that generates sketches in vector form rather than pixels. This representation is much more natural for sketches and allows the user to modify the style of strokes as a post-process.
\subsection{Sketch Abstraction}
The process of sketching naturally requires the artist to perform abstraction due to the simple tools used for sketching.
Existing methods for computational sketching implicitly perform abstraction as well, fitting the sketches to a single pre-defined style.
While abstractions are fundamental to sketches, only a few works have attempted to create sketches at multiple levels of abstraction, while no previous works have attempted to do so over an entire scene.
Berger et al.~\cite{Berger2013} utilize sketches collected from various artists to learn a mapping from a face photograph to a portrait sketch at various levels of abstraction. Their method, however, requires a new dataset for each desired level of abstraction or artistic style and is only suited for faces. Muhammad et al.~\cite{Deep-Sketch-Abstraction} approach sketch abstraction with a reinforcement learning agent trained to remove strokes from an edge map without harming the sketch's recognizability. To train the agent, an external sketch classifier is trained on nine classes from the QuickDraw dataset~\cite{ha2017neural}.
\subsection{CLIPasso}
Finally, most similar to our work is CLIPasso~\cite{vinker2022clipasso} which was designed for \textit{object} sketching at multiple levels of abstraction.
They define a sketch as a set of B\'{e}zier\xspace curves and optimize the stroke parameters with respect to a CLIP-based \cite{CLIP} similarity loss between the input image and generated sketch. Multiple levels of abstraction are realized by reducing the number of strokes used to compose the sketch.
Similar to CLIPasso, we use B\'{e}zier\xspace curves to represent our sketches and employ a pre-trained CLIP model to guide the sketching process.
In contrast to CLIPasso, however, our method is not restricted to objects and can handle the challenging task of \textit{scene} sketching. Additionally, while Vinker et al. examine only a single form of abstraction, we disentangle abstraction into two distinct axes controlling both the simplicity and the faithfulness of the sketch.
Moreover, CLIPasso defines abstraction \textit{explicitly} via the number of strokes used to draw the sketch, and uses optimization-based approach to learn the parameters of the strokes. However, sketching different inputs requires a different number of strokes, and knowing the number of strokes in advance is often challenging. In contrast, we learn the desired number of strokes \textit{implicitly} by training two MLP networks to achieve a desired trade-off between simplicity and fidelity with respect to the input image.
\section{Method}~\label{sec:method}
Given an input image $\mathcal{I}$ of a scene, our goal is to produce a set of corresponding sketches at different levels of \textit{fidelity} and \textit{simplicity}. Conceptually this can be thought of as forming a 2-dimensional space of sketch abstractions, where each axis represents one form of abstraction. Sampling this space along the two abstraction axes produces a 2-dimensional abstraction matrix of size $m \times n$.
An outline of our scene sketching process is presented in~\Cref{fig:pipeline}.
We begin by producing a set of sketches at multiple levels of abstraction along the \textit{fidelity} axis (\Cref{sec:training_scheme,sec:sem_abs}), with no simplification, thus forming the top row (highlighted in \textcolor{blue}{blue}) in the abstractions matrix. Next, for each sketch at a given level of fidelity, we perform an iterative visual simplification (highlighted in \textcolor{orange}{orange}) by learning how to best remove select strokes and adjust the locations of the remaining strokes (\Cref{sec:sketch_simp}).
This process results in an abstraction matrix representing various abstractions of the complete scene.
In the following, our method is described in detail, taking into account the entire scene as a whole.
However, to allow for greater control over the appearance of the output sketches, our final scheme splits the image into two regions (the salient foreground object and the background). We apply our 2-axes abstraction method to each region separately, allowing even more flexibility in combining them to form the matrix of sketches (\Cref{sec:split_for_back}).
\subsection{Training Scheme}~\label{sec:training_scheme}
We define a sketch as a set of $n$ black strokes placed over a white background, where each stroke is a two-dimensional B\'{e}zier\xspace curve with four control points.
We mark the $i$-th stroke by its set of control points $z_i = \{(x_i,y_i)^j\}_{j=1}^4$, and denote the set of the $n$ strokes by $Z=\{z_i\}_{i=1}^n$. Our goal is to find the set of stroke parameters that produces a sketch adequately depicting the input scene image.
An overview of our training scheme used to produce a single sketch image is presented in the gray area of~\Cref{fig:pipeline_mlp}.
We train an MLP network, denoted by $MLP_{loc}$, that receives an initial set of control points $Z_{init} \in R^{n \times 4 \times 2}$ (marked in \textcolor{blue}{blue}) and returns a vector of offsets $MLP_{loc}(Z_{init}) = \Delta Z \in \mathbb{R}^{n \times 4 \times 2}$ with respect to the initial stroke locations. The final set of control points are then given by $Z = Z_{init} + \Delta Z$, which are then passed to a differentiable rasterizer $\mathcal{R}$~\cite{diffvg} that outputs the rasterized sketch,
\begin{equation}
\mathcal{S} = \mathcal{R}(Z_{init} + \Delta Z).
\end{equation}
\input{files/figures/mlp}
To guide the training process, we leverage a pre-trained CLIP model~\cite{CLIP} due to its capabilities of encoding shared information from both sketches and natural images.
As opposed to Vinker~\emph{et al}\onedot~\cite{vinker2022clipasso} that use the ResNet-based~\cite{he2016deep} CLIP model for the sketching process (and struggles with depicting a scene image),
we find that the ViT-based~\cite{dosovitskiy2020image} CLIP model is more suitable for capturing the global context required for generating a coherent sketch of a whole scene. This also follows the observation of Raghu~\emph{et al}\onedot~\cite{raghu2021vision} that ViT models better capture more global information at lower layers compared to ResNet-based models. We further analyze this design choice in the appendix.
The sketch $\mathcal{S}$ and the input image $\mathcal{I}$ are fed into a pretrained ViT-CLIP model. The loss function is then defined as the L2 distance between the corresponding activations of CLIP at a chosen layer $\ell_k$:
\begin{equation}~\label{eq:clip_loss}
\mathcal{L}_{CLIP}(\mathcal{S},\mathcal{I},\ell_k) = \big{\|}\ \cliploss{k}{\mathcal{S}} - \cliploss{k}{\mathcal{I}} \big{\|}_2^2,
\end{equation}
At each step during training, we back-propagate the loss through the CLIP model and the differentiable rasterizer $\mathcal{R}$ whose weights are frozen, and only update the weights of $MLP_{loc}$. This process is repeated iteratively until convergence. Observe that no external dataset is needed for guiding the training process. Instead, we rely solely on the expressiveness and semantics captured by the pre-trained CLIP model.
This training scheme produces a \textit{single} sketch image at a \textit{single} level of fidelity and simplicity. Below, we describe how to control these two axes of abstraction.
\subsection{Fidelity Axis}
\label{sec:sem_abs}
To achieve different levels of fidelity, as illustrated by a single row in our abstraction matrix, we select different activation layers of the ViT-CLIP model for computing the loss defined in~\Cref{eq:clip_loss}. Specifically, in all our examples we train a separate $MLP_{loc}$ using layers $\{\ell_2,\ell_7,\ell_8,\ell_{11}\}$ of ViT-CLIP.
Optimizing via deeper layers leads to sketches that are more semantic in nature and do not necessarily confine to the precise geometry of the input. Note that it is also possible to use the remaining layers to achieve additional fidelity levels (see the appendix).
\subsection{Simplification Axis}
\label{sec:sketch_simp}
The procedure described above generates a single row in the abstraction matrix. The second axis allows altering the level of \textit{simplicity} of the sketch to convey the same concept with varying amount of explicit information.
Given a sketch $\mathcal{S}_k$ at fidelity level $k$, our goal is to find a set of sketches $\{\mathcal{S}_k^1, ..., \mathcal{S}_k^m\}$ that are visually and conceptually similar to $\mathcal{S}_k$ but have a gradually simplified appearance. In practice, we would like to learn how to best remove select strokes from a given sketch and refine the locations of the remaining strokes without harming the overall recognizability of the sketch.
We illustrate our sketch simplification scheme for generating a single simplified sketch $\mathcal{S}_k^j$ in the bottom left region of ~\Cref{fig:pipeline_mlp}. We train an additional MLP network, denoted as $MLP_{simp}$, that receives a constant valued vector and is tasked with learning an $n$-dimensional vector $P = \{p_i\}_{i=1}^n$, $p_i\in[0,1]$ (marked in \textcolor{orange}{orange}). Here, $p_i$ represents the probability of the $i$-th stroke appearing in the rendered simplified sketch. $P$ is passed as an additional input to $\mathcal{R}$ which outputs the simplified sketch $\mathcal{S}_k^j$ in accordance.
One may view $p_i$ as the importance of stroke $i$ to the sketch where a value of $0$ indicates that this stroke can be discarded and a value of $1$ indicates that this stroke should be kept.
In practice, to implement the probabilistic-based removal or addition of strokes into the rendering process, we multiply the width parameter of each stroke $z_i$ with $p_i$. When rendering the sketch, strokes with a very low probability will be ``hidden`` due to their very small width.
Note that using the MLP network rather than performing a direct optimization over the stroke parameters (as is done in Vinker~\emph{et al}\onedot) is crucial as it allows us to restore strokes that have been previously removed. If we were to use direct optimization, the gradients of deleted strokes remain as such since they were multiplied by a probability of $0$.
To encourage a sparse representation of the sketch (\emph{i.e}\onedot one with fewer strokes) we minimize the normalized L1 norm of $P$:
\begin{equation}~\label{eq:struct_loss}
\mathcal{L}_{sparse}(P) = \frac{\|P\|_1}{n}.
\end{equation}
Observe that a na\"{\i}ve\xspace solution minimizing $\mathcal{L}_{sparse}$ would simply discard all strokes. Therefore, when training $MLP_{simp}$ we additionally compute the $\mathcal{L}_{CLIP}$ loss presented in~\Cref{eq:clip_loss} to ensure that the resulting sketch still resembles the original input image. During the training of $MLP_{simp}$, we also continue to fine-tune $MLP_{loc}$.
Formally, we minimize the sum:
\begin{equation}
\mathcal{L}_{CLIP}(\mathcal{S}_k^j,\mathcal{I},\ell_k) + \mathcal{L}_{sparse}(P).
\end{equation}
We back-propagate the gradients from $\mathcal{L}_{CLIP}$ to both $MLP_{loc}$ and $MLP_{simp}$ while $\mathcal{L}_{sparse}$ is used only for training $MLP_{simp}$ (as indicated by the \textcolor{red}{red} and \textcolor{purple}{purple} dashed arrows in~\Cref{fig:pipeline_mlp}).
\input{files/figures/ratio_same_rs}
\paragraph{\textbf{Balancing the Losses.}}
Naturally, the balance between the two losses $\mathcal{L}_{CLIP}$ and $\mathcal{L}_{sparse}$ affects the appearance of the simplified sketch.
Specifically, if $\mathcal{L}_{sparse}$ incurs a low value, we attain a sketch with a lower number of strokes (\emph{i.e}\onedot more abstract). This in turn results in a high value for $\mathcal{L}_{CLIP}$ since the sketch is less recognizable (see ~\Cref{fig:loss_tradeoff}).
Therefore, the balance between $\mathcal{L}_{sparse}$ and $\mathcal{L}_{CLIP}$ is essential for achieving recognizable sketches with varying degrees of abstraction.
Thus, we define the following loss function:
\begin{equation}~\label{eq:clip_loss_simp}
\mathcal{L}_{ratio} = \big{\|}\ \frac{\mathcal{L}_{sparse}}{\mathcal{L}_{CLIP}} - r \big{\|}_2^2,
\end{equation}
where the scalar factor $r$ (denoting the \textit{ratio} of the two losses) controls the strength of simplification.
As we decrease $r$, we encourage the network to output a sparser sketch and vice-versa.
The final objective for performing a visual simplification of a given sketch $\mathcal{S}_k$, at a single simplification abstraction level, is then given by:
\begin{equation}~\label{eq:clip_loss_simp_sum}
\mathcal{L}_{simp} = \mathcal{L}_{CLIP} + \mathcal{L}_{sparse} + \mathcal{L}_{ratio}.
\end{equation}
\paragraph{\textbf{Defining the Visual Simplification Factor $r$}}
To achieve the set of gradually simplified sketches $\{\mathcal{S}_k^1, ..., \mathcal{S}_k^m\}$, we define a set of corresponding factors $\{r_k^1, ..., r_k^m\}$ to be applied in~\Cref{eq:clip_loss_simp}.
We begin by determining the value of the first ratio $r_k^1$ for each $k$.
As we already generated the first row in the abstraction matrix (\Cref{sec:sem_abs}), a natural choice for $r_k^1$ is one that would reproduce the strength of simplification present in $\mathcal{S}_k$.
As such, we can consider the factor that will lead to a value of $\mathcal{L}_{sparse}$ equal to $1$ (\emph{i.e}\onedot no visual simplification is performed). Following~\Cref{eq:clip_loss_simp}, we can then define the first factor as:
\begin{equation}
r_k^1 = \frac{1}{\mathcal{L}_{CLIP}(\mathcal{S}_k,\mathcal{I},\ell_k)}.
\end{equation}
The derivation of the remaining factors $r_k^j$ is described next.
\vspace{-0.25cm}
\paragraph{\textbf{Perceptually Smooth Simplification}}
\input{files/figures/exponent_fig}
As introduced above, the set of factors determines the strength of the visual simplification. When defining this set, we aim to achieve a \textit{smooth} simplification. By \textit{smooth} we mean that there is no large jump perceptually between two consecutive steps.
We find that this is achieved when $\mathcal{L}_{sparse}$ is exponential with respect to $\mathcal{L}_{CLIP}$.
This is illustrated in~\Cref{fig:exponent}, where the first row provides an example of a \emph{smooth} transition from $\mathcal{S}_8^1$ to $\mathcal{S}_8^m$, while the second row demonstrates a non-smooth transition, where there is a large perceptual ``jump'' in the abstraction level between the second and third sketches, and almost no perceptual change in the following levels.
The two graphs at the bottom of~\Cref{fig:exponent} describe this observation quantitatively, illustrating the trade-off between $\mathcal{L}_{sparse}$ and $\mathcal{L}_{CLIP}$. We can see how the smooth transition between the sketches in the first row forms an exponential relation between $\mathcal{L}_{sparse}$ and $\mathcal{L}_{CLIP}$, while the large ``jump'' in the second row is clearly shown in the gap in the right graph.
This observation aligns well with the Weber-Fechner law~\cite{Weber1834-ms,fechnerlaw} which states that human perception is linear with respect to an exponentially-changing signal. In our case, perception is ``measured'' by the CLIP similarity between the sketch and the input image, and the abstraction signal is attained by $\mathcal{L}_{sparse}$ which is simply a function of the number of strokes.
Given this, we define an exponential function recursively by $f(j) = f(j-1)/2$. The initial value of the function is defined differently for each fidelity level $k$ as $f_k(1) = r_k^1$. To create the following $m-1$ simplification levels we sample the function $f_k$ to define the set of factors $\{r_k^2, .. r_k^m\}$.
For each $k$, the sampling step size is set proportional to the strength of the $\mathcal{L}_{CLIP}$ loss incurred at level $k$. Hence, layers that incur a large $\mathcal{L}_{CLIP}$ value are sampled with a larger step size.
We found this procedure achieves simplifications that are perceptually smooth.
An analysis of the ratios and our design choices are provided in the appendix.
\input{files/figures/iterative_simplification}
\paragraph{\textbf{Generating the Simplified Sketches}}
To generate the set of simplified sketches $\{\mathcal{S}_k^1 ... \mathcal{S}_k^m\}$, we use the set of $m$ corresponding ratios $\{r_k^1, .. r_k^m\}$ and apply the training procedure iteratively. This process is illustrated in~\Cref{fig:iterative_simplification}: to generate $\mathcal{S}_k^1$ we start with the trained $MLP_{loc}$ used to generate $\mathcal{S}_k$ (marked in \textcolor{blue}{blue}) and a randomly-initialized $MLP_{simp}$ network (marked in \textcolor{orange}{orange}). We then use $r_k^1$ to define the first $\mathcal{L}_{ratio}$ loss and generate the first simplified sketch $\mathcal{S}_k^1$.
After generating $\mathcal{S}_k^1$, we sequentially generate each $\mathcal{S}_k^j$ for $2\leq j \leq m$ by continuing training both networks for a fixed number of steps and applying $\mathcal{L}_{ratio}$ with the corresponding target ratio $r_k^j$.
\subsection{Decomposing the Scene}~\label{sec:split_for_back}
While sketching the entire scene together works well across different scenes, we found that doing so may lead to degraded performance in various cases.
First, weakening the faithfulness of the sketch with respect to the input image may over-exaggerate features of the subject (see~\Cref{fig:additional_control}, first row). In other cases, when moving along the simplification abstraction axis, the scene's subject may ``disappear'' into the background (see~\Cref{fig:additional_control}, third row).
\input{files/figures/image_preprocessing_example}
To avoid such artifacts and provide additional control over the appearance of the final sketches, we separate the scene's foreground subject from background, and sketch each of them independently.
We do so by extracting the scene's salient object(s) using a pretrained U$^2$-Net salient object detector~\cite{qin2020u2}. We then apply a pretrained LaMa~\cite{suvorov2022resolution} inpainting model to recover the missing regions.
This process is illustrated in~\Cref{fig:image_preprocessing_results}.
Having split the scene into two independent components, we compose the abstraction matrix for each using the same technique as described above.
When performing object sketching, we additionally compute $\mathcal{L}_{CLIP}$ over layer $l_4$. We find doing so assists in preserving the input geometry and finer details, and helps in avoiding artefacts as seen in the first row of~\Cref{fig:additional_control}.
\input{files/figures/additional_control}
In addition, independently sketching the scene's foreground and background provides users with more control. First, users can choose how to balance the emphasis placed on the scene subject by altering the opacity of the background sketches. Second, users may combine the foreground and background sketches at different levels of abstraction. Examples are provided in~\Cref{fig:additional_control}.
\part{}
\twocolumn[{%
\vspace{-1em}
\maketitle
\renewcommand\twocolumn[1][]{#1}%
\vspace{-2em}
\vspace{-0.1in}
\begin{center}
\centering
\vspace{-0.3cm}
\includegraphics[width=\linewidth]{figs/teaser_4.pdf}
\vspace{-0.7cm}
\captionsetup{type=figure}+\caption{
Our method converts a \textit{scene} image into a sketch with different types and levels of abstraction by disentangling abstraction into two axes of control: \textit{fidelity} and \textit{simplicity}.
For each image on the left, we illustrate two example sketches generated by our method. The first sketch is more precise and detailed, accurately depicting the scene's structure and geometry. The second is more abstract, using fewer strokes and relying more on the semantics of the image instead of on the scene's exact geometry.
These sketches were selected from a complete \textit{matrix} that was generated by our method (shown on the right), encompassing a broad range of possible sketch abstractions for a given image.
Users can select the desired sketch based on their goals and personal taste.
}
\label{fig:teaser}
\end{center}%
}]
\thispagestyle{plain}
\pagestyle{plain}
\begin{abstract}
\vspace{-0.25cm}
\input{files/abstract}
\end{abstract}
\input{files/shortIntro}
\input{files/prev_work}
\input{files/method_new}
\input{files/results}
\input{files/limitations}
{\small
\bibliographystyle{ieee_fullname}
\section{Implementation Details}~\label{sec:implementations}
In this section, we provide specific details about the implementation of our method. We will further release all code and image sets used for evaluations to facilitate further research and comparisons.
\begin{figure}[h]
\centering
\includegraphics[width=1\linewidth]{figs/inputs_mask/preprocess-rescale.pdf}
\vspace{-0.3cm}
\caption{Object re-scaling procedure.}
\vspace{-0.275cm}
\label{fig:rescaling}
\end{figure}
\subsection{Image Preprocessing}~\label{sec:image_preprocessing}
As stated in the paper, we use a pre-trained U$^2$-Net salient object detector~\cite{qin2020u2} to extract the scene's salient object(s). To receive a binary map, we threshold the resulting map from U$^2$-Net such that pixels with a value smaller than $0.5$ are classified as background, and the remaining pixels are classified as salient objects.
We then use this mask as an input to a pre-trained LaMa~\cite{suvorov2022resolution} inpainting model to recover the missing regions in the background image.
\paragraph*{\textbf{Object Scaling}}
In the case where the saliency detection process detected only one object, and this object fills less than $70\%$ of the image size, we perform an additional pre-processing step to increase the size of the object before sketching.
This assists in sketching key features of the object when using a large number of strokes.
Specifically, we first take the masked object and compute its bounding box. We then shift the masked object to the center of the image and resize the object such that it covers $\approx 70\%$ of the image.
We apply the sketching procedure on the scaled object and then resize and shift the resulting sketch back to the original location in the input image. Note that since our sketches are given in vector representation, it is possible to re-scale and shift them without changing their resolution.
This process is illustrated in~\Cref{fig:rescaling}.
\subsection{Sketch Initialization}
For initializing the locations of the $n$ strokes, we follow the saliency-based initialization introduced in Vinker~\emph{et al}\onedot~\cite{vinker2022clipasso}. Specifically, we employ the vision transformer interpretability method from Chefer~\emph{et al}\onedot~\cite{Chefer_2021_ICCV} to extract a relevancy map from a pre-trained VIT-B/32 CLIP model. We use the resulting relevancy map to sample the location of each B\'{e}zier\xspace curve such that pixels in salient regions are assigned a higher probability of being selected.
\subsection{MLP Architecture}
Our MLP networks are simple $3$-layer networks with SeLU~\cite{klambauer2017self} activations. For $MLP_{simp}$ we append a Sigmoid activation to convert the final outputs to probabilities.
\subsection{MLP Training}
\paragraph*{\textbf{Hyper-parameters}}
In all experiments, we set the number of strokes to $n = 64$ in the first phase of sketching and train $MLP_{loc}$ for $2,000$ iterations.
For generating the series of simplified sketches (Section 3.4 in the main paper), we perform $8$ iterative steps. As discussed in Section 3.4, for each fidelity level $k$, we define a separate function $f_k$ for defining the set of ratios used in $\mathcal{L}_{ratio}$. Along with this function, we define a separate step size for sampling the function $f_k$. For simplifying the background sketches, we set this step size to be $\{0.35, 0.45, 0.5, 0.9\}$ for layers $\{2, 7, 10, 11\}$, respectively. For simplifying the object sketches, we set the step sizes to be $\{0.45, 0.4, 0.5, 0.9\}$. Each simplification step is obtained by training $MLP_{simp}$ and $MLP_{loc}$ for $500$ iterations.
We employ the Adam optimizer with a constant learning rate of $1\mathrm{e}{-4}$ for training both MLP networks.
The input to $MLP_{simp}$ is set to be a constant-valued vector of dimension $n$. We set this constant equal to $1.5$, although we found that other scalar values can be also used.
\paragraph*{\textbf{Augmentations}}
As also done in Vinker~\emph{et al}\onedot~\cite{vinker2022clipasso}, we apply random affine augmentations (\emph{i.e}\onedot random perspective and random cropping transformations) to both the input image and generated sketch before passing them as inputs to the CLIP model for computing the loss.
\paragraph*{\textbf{GradNorm}}
We train $MLP_{simp}$ and $MLP_{loc}$ with three different losses simultaneously in order to achieve our visual simplifications. As these losses compete with each other, training has the potential to be highly unstable. For example, when training with multiple losses, the gradients of one loss may be stronger than the other, resulting in the need to weigh the losses accordingly.
To help achieve a more stable training process and to ensure that each loss contributes equally to the optimization process, we use GradNorm~\cite{GradNorm}, which automatically balances the training process by dynamically adjusting the gradient magnitudes. This balancing is achieved by weighing the losses inversely proportional to their contribution to the overall gradient.
\subsection{Matrix Composition}
As stated in the main paper, we separate the scene into two regions (based on their saliency map) and apply the sketching scheme to both independently, we then combine the resulting sketches to form the final matrix.
To combine the foreground and background we simply aggregate the corresponding strokes at a given level of fidelity and simplicity.
Note that we also export the mask used to separate them, if the user wish to locate it behind the object to avoid the collision of strokes.
We also export the separate matrices, to allow users to combine sketches from different levels of abstraction as a post process.
\section{Additional Results}
We begin with additional results generated by our method. In~\Cref{fig:matrix1,fig:matrix2,fig:matrix3,fig:matrix4,fig:matrix5} we provide $4\times4$ abstraction matrices for various scene images. In addition, we present additional examples of the added control provided by the separation technique in~\Cref{fig:additional_control_supp}. This includes: (1) editing the style of strokes using Adobe Illustrator and (2) combining the foreground and background sketches and varying levels of abstractions to achieve various artistic effects.
\input{files/figures/supplementary/our_matrices/our_matrices_1}
\input{files/figures/supplementary/our_matrices/our_matrices_2}
\input{files/figures/supplementary/our_matrices/our_matrices_3}
\input{files/figures/supplementary/our_matrices/our_matrices_4}
\input{files/figures/supplementary/our_matrices/our_matrices_5}
\begin{figure*}
\centering
\includegraphics[width=0.7\linewidth]{figs/stroke_style.jpg}
\rule[0.5ex]{0.7\linewidth}{1pt}
\includegraphics[width=0.7\linewidth]{figs/bird_stroke_style.jpg}
\rule[0.5ex]{0.7\linewidth}{1pt}
\includegraphics[width=0.7\linewidth]{figs/manflowers_style.jpg}
\caption{Additional control. For each image, we combine foreground and background sketches from different levels of abstraction, and edit the style of strokes using Adobe Illustrator. This illustrates the power of our method in providing various options for the user to edit the resulted sketches.}
\label{fig:additional_control_supp}
\end{figure*}
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\input{files/figures/supplementary/recognizability_example_images}
\null\newpage
\section{Additional Quantitative Analysis}
In this section, we provide additional details, examples, and results regarding the quantitative evaluations presented in the paper. First, in~\Cref{fig:recognizability_example_images} we present example inputs and representative generated sketches for each of our five scene categories used for evaluations.
\input{files/figures/supplementary/recognizability_sample_results}
\subsection{Sketch Recognizability}
To compute our recognizability metrics, we perform zero-shot classification using a pre-trained ViT-B/16~\cite{dosovitskiy2020image} CLIP model. Observe this model is different than the ViT-B/32 model used to generate sketches, ensuring a more fair evaluation of our sketches. When performing the zero-shot classification, we follow the evaluation setup used in CLIP~\cite{CLIP} and apply $80$ prompt templates when defining our $150$ classes to CLIP's text encoder. This includes prompts of the form: ``a rendering of a \{\}'', ``a drawing of a \{\}`, and ``a sketch of a \{\}''. We then compute the cosine similarity between all text embeddings and the embedding corresponding to either our input image or generated sketches.
In~\Cref{fig:recognizability_example_predictions}, we present example zero-shot classification results obtained on various input images and sketches across our five scene categories.
\input{files/figures/supplementary/quantitative_num_strokes_by_class}
\subsection{Number of Strokes by Simplicity Level}
In the main paper, we examined the number of strokes used to compose our sketches across the different fidelity and simplification levels. For conciseness, we presented the average number of strokes used across all images and all scene categories. In~\Cref{fig:quantitative_num_strokes_by_class}, we present the same results but split between the different scene categories and split between composing the foreground and background sketches. As can be seen, the resulting functions for the different fidelity levels follow an exponential relation as we strengthen the simplification level. This behavior aligns well with the Weber-Fechner law~\cite{Weber1834-ms,fechnerlaw} which states that an exponentially-changing signal corresponds to a change that is perceived to be linear.
\hfill
\input{files/figures/supplementary/ablation_resnet}
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\section{Ablation Study: General Design Choices}
\subsection{ViT vs. ResNet}
In~\Cref{fig:ablation_full_scene_resnet}, we demonstrate the scene sketching results obtained with a ResNet101-based CLIP compared to those obtained with the ViT-based CLIP model employed in this work. When computing $\mathcal{L}_{CLIP}$ using a single layer of ResNet (\emph{i.e}\onedot layer $2$, $3$, or $4$), we are unable to capture the input scene, indicating that a combination of the layers must be used for capturing the more global details of a complete scene. However, even when computing $\mathcal{L}_{CLIP}$ using multiple ResNet layers (as was done in CLIPasso), the network still struggles in capturing the details of the scene. For example, in row $3$, although we are able to roughly capture the outline of the bull's head and horns, the network is unable to capture the bull's body and scene background. In contrast, when replacing the ResNet model with the more powerful ViT model, we are able to capture both the scene foreground and background, even when using a single layer for computing the loss. This naturally allows us to control the level of fidelity of the generated sketch by simply altering the single ViT layer that is used for computing $\mathcal{L}_{CLIP}$.
\subsection{Foreground-Background Separation}
In Section 3.4 of the main paper, we introduced our scene decomposition technique where the foreground and background components of the input are sketched separately and then merged. In~\Cref{fig:ablation_foreground_background_supp} we provide additional sketching results obtained with and without the scene decomposition for both abstraction axes.
At the top, we present the resulting sketches along the fidelity axis.
Observe how the house in the leftmost sketch in the first row appears to disappear within the entire scene. Furthermore, note the artifacts that appear in the face of the dog as the abstraction increases.
In contrast, by explicitly separating the foreground and background, we can apply additional constraints over the foreground sketches to help mitigate unwanted artifacts. As a result, we are able to better maintain the correct structure of both the house and dog in the provided examples.
At the bottom of~\Cref{fig:ablation_foreground_background_supp} we show the resulting sketches along the simplification axis. Note how the house in the first row almost disappears completely, and that there are not enough strokes to depict the mountains in the background. By considering the entire scene as a whole, the model has no explicit control over how to balance the level of details placed between the object and the background. As a result, more strokes are typically used to sketch the background, which consumes a larger portion of the entire image (and therefore leads to a larger reduction in $\mathcal{L}_{CLIP}$).
\input{files/figures/supplementary/ablation_foreground_background}
\null\newpage
\null\newpage
\input{files/figures/supplementary/ablation_explicit_define_num_strokes}
\input{files/figures/supplementary/ablation_direct_lratio}
\null\newpage
\section{Ablation Study: Simplicity Axis}
In this section, we analyze the design choices for the simplification training scheme and corresponding loss objectives.
\subsection{Explicitly Defining the Number of Strokes}~\label{sec:explicit_num_strokes}
We begin by analyzing our simplification scheme as a whole. That is, are we able to achieve a smooth simplification of an input scene by simply varying the number of strokes used to sketch the scene? In~\Cref{fig:ablation_explicit_define_num_strokes} we provide results comparing our implicit simplification scheme (on the right) with results obtained by sketching the scene using a varying number of strokes defined in advance (on the left). For the latter results, we use $64, 32, 16$, and $8$ strokes for sketching. For each input, we present the simplifications achieved at the last level of fidelity (\emph{i.e}\onedot using layer $11$ of CLIP-ViT for training).
Knowing in advance the number of strokes needed to achieve a specific level of abstraction is often challenging and varies between different inputs.
For example, consider the image in the first row, containing a simpler scene of a house.
When using only $16$ strokes for sketching this image, we are able to capture the components of the scene such as the existence of the house in the center, its roof, and its door. However, when sketching the more complex urban scene in the third row, using $16$ strokes may struggle to capture the general structure of the buildings or may not converge at all. By \textit{learning} how to simplify each sketch, our simplification scheme is able to adjust the number of strokes needed to more faithfully sketch a given image at various levels of simplification, while adapting to the complexity of the input scene in the learning process.
Moreover, we observe that when defining the number of strokes explicitly, we may fail to get a smooth simplification of the initial sketch since each sketch is generated independently and may converge to a different local minimum.
For example, in the second row on the left, the sketches do not appear to be simplified versions of each previous step (\emph{e.g}\onedot between the second and third steps), but rather new sketches of the input scene with an increased level of visual simplification.
In contrast, each of our simplification results is initialized with the previous result, resulting in a smoother transition between each image.
\subsection{Replace the Ratio Loss With a Target Number of Strokes}
We note in the main paper that achieving gradual visual simplification requires balancing between $\mathcal{L}_{sparse}$ and $\mathcal{L}_{CLIP}$.
In our method, we do so by defining a set of factors used to define a balance between the relative strengths of the losses.
This section examines another possible approach: encouraging the training process to achieve a certain number of strokes during training and reducing this number at each level.
As opposed to~\Cref{sec:explicit_num_strokes} where we restrict the number of strokes completely, here we include the target number of strokes as another objective in the training process, thus allowing deviance from this number.
To implement this approach we simply redefine $L_{ratio}$ as follows:
\begin{equation}
\mathcal{L}_{ratio} = ||\mathcal{L}_{sparse} - n_{target}||,
\end{equation}
where $n_{target}$ is the desired number of strokes. Specifically, we define four levels of abstraction using $64$, $32$, $16$, and $8$ strokes. We then normalize the number of strokes to be between $0$ and $1$ and define $n_{target}$ as $\{1, 0.5, 0.25, 0.125\}$ for each level, respectively.
In~\Cref{fig:direct_lratio} we show the result of this experiment. As can be seen on the left, such an approach does not achieve the desired simplification.
As can be seen, on the left, the levels of abstraction are less gradual than on the right and do not reach full abstraction. This approach also relies on an arbitrary fixed number of strokes per abstraction level for all images, as opposed to allowing the ratio itself to implicitly define it in a content-dependent manner.
\subsection{Fine-tuning MLP-loc During Simplification}
As described in Section 3.3 of the main paper, when performing the simplification of a given sketch by training $MLP_{simp}$, we continue fine-tuning $MLP_{loc}$.
Doing so is important since by training $MLP_{loc}$, we allow to slightly adjust the locations of strokes in the canvas, which helps encourage the simplified sketch to resemble the original input image.
In~\Cref{fig:ablation_finetune_mlp_loc}, we show sketch simplifications across various inputs obtained with and without the fine-tuning of $MLP_{loc}$.
When $MLP_{loc}$ is held fixed, the simplification process is equivalent to simply selecting a subset of strokes to remove at each step. This approach will result in the appearance of visual simplification, but may not be sufficient to maintain the semantics of the scene. For example, in the last simplification step of the first example, the mountains in the background have disappeared, as have the buildings in the third example. In addition, the house in the second image can no longer be identified.
On the other hand, our results, obtained with the fine-tuning of $MLP_{loc}$, produce the desired visual simplification, while still preserving the same semantics of the input scenes.
\input{files/figures/supplementary/ablation_finetune_mlp_loc}
\input{files/figures/supplementary/ablation_linear_fk}
\subsection{Defining the Function f-k as an Exponential}
In Section 3.3 of the main paper, we describe the process of selecting the set of factors used to achieve a gradual simplification of a given sketch. To do so, we defined a function $f_k$ for each fidelity level $k$ defining the balance between $\mathcal{L}_{CLIP}$ and $\mathcal{L}_{sparse}$. We find that an $f_k$ that models in an exponential relationship between $L_{CLIP}$ and $L_{sparse}$ achieves a simplification that is perceived smooth.
In this section, we demonstrate this effect by visually demonstrating the gradual simplification we achieve when using a $f_k$ using a linear relation between $\mathcal{L}_{CLIP}$ and $\mathcal{L}_{sparse}$.
To do so, we define the linear $f_k$ such that the sampled set of factors $\{r_k^1, .. r_k^m\}$ represent a constant step size by encouraging the removal of $8$ strokes in each step.
In~\Cref{fig:ablation_linear_fk} we present the results of this alternative setup.
For each set of generated sketches, we additionally present two graphs: (1) the resulting $L_{sparse}$ as a function of $L_{CLIP}$ (left), and (2) the final number of strokes as a function of the simplification step (right).
Each point in the graphs corresponds to a single sketch with the color of the points indicating the location of the corresponding sketch along the simplification axis. That is, $0$ (or dark blue) indicates the leftmost, non-simplified sketch while $7$ (or yellow) indicates the rightmost sketch with the highest level of simplification.
Recall, as discussed in the main paper, the left graph should ideally depict an exponential relation between the two loss objectives in order for the simplification to appear smooth.
The results presented on the left side of~\Cref{fig:ablation_linear_fk} show the sketches and corresponding graphs produced when using a linear $f_k$ as defined above. The results on the right-hand side of the Figure show sketches obtained with our method when using the exponential $f_k$ as described in the main paper. As can be seen, the sketches in the linear alternative (left) remain too detailed at the initial abstraction levels and do not convey the smooth and gradual change perceptually as is present with the exponential function (right).
\input{files/figures/supplementary/same_ratios}
\input{files/figures/supplementary/same_step_size_fk}
\null\newpage
\subsection{Defining a Different Set of Factors for Each Layer}
In Section 3.3 of the main paper, we describe the process of selecting the set of factors $\{r_k^1, ..., r_k^m\}$ used to achieve a gradual simplification of a given sketch.
In this section, we validate the use of different sets of factors for each fidelity level $k$.
Note that, as stated in the main paper, the set of factors $r_k^j$ determine the balance between $\mathcal{L}_{CLIP}$ and $\mathcal{L}_{sparse}$, which directly determines the level of visual simplification.
We show on the left-hand side of~\Cref{fig:same_ratios} the simplified sketches obtained for different levels $k$ of fidelity when using the same set of factors. Specifically, we apply the set of factors used for layer $\ell_8$ to the remaining ViT layers.
As can be seen, the perceived level of visual simplification is not uniform between different layers: the simplification achieved for layer $\ell_{11}$ is too weak with very little perceived change realized across all steps. In contrast, for layer $\ell_2$ the simplification is too strong with the background quickly ``disappearing'' as we move to the right.
On the right-hand side of~\Cref{fig:same_ratios}, we present the results obtained with our method, where we fit a dedicated set of factors for each fidelity level $k$. As can be seen, the perceived level of abstraction among the different fidelity levels is more uniform and smooth.
\subsection{Defining a Different Sampling Step for Each f-k}
After defining the function $f_k$ for each fidelity level $k$, we use a different step size for sampling this function for each $k$.
We wish to achieve a similar appearance of simplification across different fidelity levels, and we find that in order to do so, using a different step size for sampling $f_k$ is crucial.
In~\Cref{fig:same_step_size}, on the left, we demonstrate results obtained when using the same step size for our four fidelity levels (\emph{i.e}\onedot ViT layers $\ell_2,\ell_7,\ell_8,\ell_{11}$).
As can be seen, for layers $\ell_2$ and $\ell_7$ the gradual simplification is not smooth and a noticeable jump in the strength of the abstraction can be seen between the second and third sketches.
Furthermore, for layer $\ell_7$, the change in step size caused the networks to converge to a noisy solution. Observe how the second sketch does not resemble a simplification of the previous one.
In contrast, the results on the right are obtained using the proposed approach of selecting different step sizes for each fidelity level $k$. As shown, the sketches do not suffer from the perceived artifacts present on the left. Moreover, the simplification results are also smooth and uniform in appearance between the different layers.
\input{files/figures/supplementary/ablation_all_vit_layers}
\section{Ablation Study: Fidelity Axis}
Finally, in this section, we perform various ablation studies to validate the design choices made with respect to our fidelity abstraction axis.
\subsection{Using l-4 for Object Sketching}
When decomposing the scene and sketching for the foreground image, we additionally compute $L_{CLIP}$ over layer $\ell_4$ of ViT. We found that doing so may help in preserving the geometry of more complex subjects, as illustrated in~\Cref{fig:ablation_l4}. This is most noticeable in finer details such as in the facial details of the old man and the dog or the body shape of the panda, for example.
\input{files/figures/supplementary/ablation_with_l4}
\subsection{Using Other ViT Layers for Training}
In order to obtain different levels of fidelity, we train $MLP_{loc}$ guided by different layers of the CLIP-ViT model for computing $\mathcal{L}_{CLIP}$.
Our model is based on the ViT-B/32 architecture that includes $11$ intermediate layers.
Our main paper presents the results of applying our training scheme to a subset of four layers: $2$, $7$, $8$, and $11$.
This subset of layers represents a range of possible fidelity levels that can be achieved by our method.
While we focus on presenting results using only these four layers, our method can naturally generate additional levels of fidelity by using the remaining intermediate layers.
We present the results of using additional layers in~\Cref{fig:ablation_all_vit_layers}.
\null\newpage
\section{Additional Comparisons}
\input{files/figures/supplementary/diffusion_comparison}
\subsection{Diffusion Models}
Recent advancements in diffusion models~\cite{ho2020denoising} have demonstrated an unprecedented ability to generate amazing imagery guided by a target text prompt or image~\cite{rombach2021highresolution,ramesh2021zero,ramesh2022hierarchical,nichol2021glide,yu2022scaling,saharia2022photorealistic}. In this section, we explore whether such models can be leveraged to generate abstract sketches of a given scene. We begin by exploring the recent Stable Diffusion model~\cite{rombach2021highresolution}. Given an input image, we perform a text-guided image-to-image translation of the input using text prompts such as: ``A black and white sketch image'' and ``A black and white single line abstract sketch.'' Results are illustrated in~\Cref{fig:diffusion_comparison}. As can be seen in the top row, Stable Diffusion struggles in capturing the sketch style even when guiding the denoising process with keywords such as ``A black and white sketch''. We do note that better results may be achieved with heavy prompt engineering or tricks such as prompt re-weighting
methods~\cite{automaticWebUi2022}. However, doing so would require heavy manual overhead for each input image.
Another approach to assist in better capturing the desired sketch style would be to fine-tune the entire diffusion model on a collection of sketch images. However, this would require collecting a few hundred or thousands of images with matching captions and training a separate model for each desired style and level of abstraction.
As another diffusion-based approach, we consider the recent Textual Inversion (TI) technique from Gal~\emph{et al}\onedot~\cite{gal2022image}. Given a few images (\emph{e.g}\onedot 5) of the desired style (\emph{e.g}\onedot sketch), TI can be used to learn a new ``word'' representing the style. Users can then use a pre-trained text-to-image model such as the recent Latent Diffusion Model~\cite{rombach2021highresolution} to generate images of the learned style. For example, users can generate a sketch image of a house using the prompt ``A photo of a house in the style of $S_*$'' where $S_*$ represents our learned sketch style.
To evaluate TI's ability to generate sketch images supported by our method, we collect $10$ sketches generated by our method --- $5$ detailed and $5$ abstract --- and learn a new token representing each of the sketch styles. In a similar fashion, we can learn a new word representing a unique object of interest (\emph{e.g}\onedot the headless statue shown in~\Cref{fig:diffusion_comparison}). We can then generate images of the learned object in our learned style using prompts of the form ``A drawing of a $S_{statue}$ in the style of $S_{detailed}$'' or ``A drawing of a $S_{statue}$ in the style of $S_{abstract}$''. Example results are presented in the bottom half of~\Cref{fig:diffusion_comparison}. As can be seen, TI struggles in composing both the learned style and subject in a single image. Specifically, TI either struggles in capturing the unique shape of the statue (\emph{e.g}\onedot its missing head) or struggles in capturing the learned sketch style (\emph{e.g}\onedot TI may generate images in color). In contrast, our method is able to generate a range of possible sketch abstractions that successfully capture the input subject.
\subsection{Scene Sketching Approaches}
In~\Cref{fig:scene_sketching_comparisons_supp} we provide additional scene sketching comparisons to alternative scene sketching methods. In~\Cref{fig:scene_sketching_comparisons_chan_supp} we provide additional sketch comparisons to all styles supported by UPDF~\cite{yi2020unpaired} and Chan~\emph{et al}\onedot~\cite{chan2022learning}. Finally, in~\Cref{fig:clipasso_comparisons_supp,fig:clipasso_comparisons_objects_supp} we provide additional comparisons to CLIPasso for both scene sketching and object sketching, including a comparison without our scene decomposition technique.
\input{files/figures/supplementary/scene_sketch_comparison}
\input{files/figures/supplementary/chan_comparison}
\input{files/figures/supplementary/clipasso_comparison}
\input{files/figures/supplementary/clipasso_comparison_objects}
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
\null\newpage
| {'timestamp': '2022-12-01T02:21:39', 'yymm': '2211', 'arxiv_id': '2211.17256', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17256'} | arxiv |
\section{Introduction and Motivation}
\label{sec:introduction}
The ever more widespread use of social media and user-contributed content
also causes an increase of toxic or offensive language and other forms of unwanted contributions which may need to get detected and removed. In this paper, we present work aimed at supporting moderators
of a large daily Austrian (German language) newspaper which allows registered users to discuss the articles published on its web-site. Users post some 20K to 50K comments per day. An analysis of commenting behaviour has shown that only a third of the users participating in the online discussion are women and that one important reason why women avoid participating in article forum discussions is the presence of sexist comments. The aim therefore was to use automatic classification of sexist/misogynist comments to support moderators in detecting such comments in order to provide a more welcoming and safer climate of discussion especially for female users.
For this, a corpus of 6600 comments was collected and annotated and subsequently used to train a classifier used to flag comments or entire discussion forums with a high number of suspected misogynist comments.
\section{Related Work}
\label{sec:relatedwork}
Together with work on toxic and offensive language classification in recent years, there has
also been increasing work on the classification of sexist or misogynist language, sometimes as part of
a more general toxic language classification task. \citet{Hewitt2016} give an overview over earlier work and describe a dataset of Tweets containing abusive sexist terms.
\citet{Anzovino2018} present work on creating a dataset of tweets, subsequently used as part of IberEval-2018 and EvalIta-2018 challenges \cite{Fersini2018} for sexism classification.
\citet{Shushkevich2019} give an overview over misogyny detection in social media, specifically Twitter.
\citet{Waseem2016} describe work on a corpus of 16K tweets for detecting toxic and hate speech including sexist slurs or defending sexism (3383 tweets with sexist content).
\citet{Frenda2019} present work on the datasets described in \cite{Fersini2018} and \cite{Waseem2016}. \citet{Sharifirad2019} include some more detailed description of sexist language and is based on another dataset of English language tweets. \citet{Parikh2019} describe work on categorizing accounts of sexism from the Everyday Sexism Project website through fine-grained multilabel classification. Other datasets are described or used in \cite{Chiril2020a} (12K tweets in French) and \cite{Grosz2020} (tweets, work-related quotes, press quotes and other sources), \cite{Bhattacharya2020a} and \cite{SafiSamghabadi2020} (Youtube comments in Indian English, Hindi and Bengla), \cite{RodriguezSanchez2020} (Spanish language tweets) and \cite{Zeinert2021} (Danish language dataset sampled from several social media sites).
The EXIST task at IberLEF 2021 \cite{RodriguezSachez2021} addresses the identification and categorization of sexism in English and Spanish language tweets and postings from \url{Gab.com}. Most recently, SemEval 2023 Task 10\footnote{\url{https://codalab.lisn.upsaclay.fr/competitions/7124}} provides an English language corpus of 20000 texts sampled from Gab and Reddit, annotated with 3 hierarchical labels.
\section{Corpus Creation}
\label{sec:corpuscreation}
The aim of manual corpus annotation was to reflect the judgement of moderators in their
everyday work. For this reason, the manual annotations were carried out by 8 annotators of
which 7 were experienced moderators. The 8th annotator is a natural language processing and corpus linguistics expert. One of the annotators is among the authors of this paper. There were 3 male and 5 female annotators.
Since the phenomenon of "sexism"/"misogyny" is complex, guidelines were created to
describe the most important kinds of sexism relevant for the annotation task. For this
we used the categorization from \cite{Parikh2019} as inspiration. The guidelines also
attempt to clarify some of the difficulties likely to be encountered: how to decide if
there is not enough context, what if the sexist remark is aimed at a man or men in general,
how to treat "reported sexism" \cite{Chiril2020}. However, the guidelines follow the
aim of providing help for annotating in a way that reflects the daily work of moderators and the newspaper's editorial concept. They are not meant as an accurate abstract definition of sexism and misogyny. The (German language) guidelines are available online\footnote{\url{https://ofai.github.io/femdwell/annotation_guidelines_v1.pdf}}. We will refer to the task as "misogyny classification" in the rest of the paper.
Postings were annotated by assigning one of 5 possible labels 0 .. 4, corresponding to
0=absence of misogyny and 4 levels of "severity" of the expressed misogyny as perceived by the individual annotators, with 1=mild, 2=present, 3=strong, 4=extreme.
This was done on the one hand to reflect the personal aspect in the assessment of misogyny, and on the other hand to identify the instances with the biggest disagreements among annotators.
Postings to be annotated were collected from several different sources: (1) a collection of
postings which had been reported with a (free text) reporting reason that included a keyword
related to sexism/misogyny, (2) postings which were reported
with a different reason, (3) postings randomly sampled from all available postings, (4) a subset of postings (2) preclassified with an early version of the binary classifier trained on the first 2800 annotated postings and (5) postings from 24 article forums which have been identified to contain an above-average number of postings considered sexist, preclassified with the same early binary classifier. Preclassified postings were selected from the highest probability label "1" postings (to correct false positives) as well as those label "0" and "1" postings with close to 0.5 probability (to add what may be hard to classify instances).
Postings were given to annotators in batches of 100, by creating a spreadsheet from the posting texts and preparing a selection field for selecting one of the 5 possible labels. The first batch of 100 postings was given to all 8 annotators and then analysed to find postings with the biggest
disagreement: for this we calculated a heuristic disagreement score based on all
pairwise distances between the labels, where the distance between labels 0 and 1 were
defined to be 4, and distances between labels $l_i, l_j >0$ defined to be $|l_i-l_j|$. Examples with high scores were then discussed among annotators to clarify the annotation guidelines or clear up misunderstandings.
After this, each round of 100 postings was given to a random selection of 3 annotators available at the time. This was done in order to compromise between annotating as many postings as possible given the available time and resources and still get enough annotators for each posting to identify disagreements. In total, 66 rounds with 6600 postings were annotated (20300 annotations). The overall distribution of assigned labels is shown in Table~\ref{table:dist5}.
\begin{table}[htbp!]
\caption{Distribution of assigned labels}
\centering
\begin{tabular}{lrrrrrr}
\toprule
Label & 0 & 1 & 2 & 3 & 4 & 1...4 \\
\midrule
\% & 66.5 & 7.3 & 14.2 & 9.4 & 2.6 & 33.5 \\
\bottomrule
\end{tabular}
\label{table:dist5}
\end{table}
\section{Annotator Agreement and Corpus Analysis}
\label{sec:corpusanalysis}
Krippendorff Alpha over all annotations was 0.36 (nominal scale) and 0.64 (ordinal scale). After binarization of the 5 possible annotations into 0 (for no sexism) and 1 (for labels $1\dots 4$), Krippendorff Alpha was 0.60.
Overall agreement was 0.65 / 0.83 (binary) if macro averaged over all agreements of pairs of users, and 0.66 / 0.82 (binary) if micro averaged over all pairs of annotations. F1.0 macro over all 22300 pairs
of annotations was 0.390 / 0.803 (binary). Overall Cohen's Kappa was 0.39 / 0.63 (binary) if macro averaged over all kappas for pairs of users. This indicates that there was considerable difference of opinion or difficulty in assigning the fine-grained labels.
As shown in Table~\ref{table:dist5} the overall rate of assigned positive labels (classes $1\dots 4$) was 0.335. Looking at all pairs of annotations in the dataset the relative frequencies of annotation pairs (confusion matrix) is shown in Table~\ref{table:conf1}. This illustrates the large rate of disagreement among annotators, especially on estimating the fine-grained degree of mysogyny (labels $1\dots 4$).
\begin{table}[htbp!]
\caption{Relative frequence of annotation pairings}
\centering
\begin{tabular}{l|lllll}
\toprule
& 0 & 1 & 2 & 3 & 4 \\
\midrule
0 & 0.525 & 0.032 & 0.037 & 0.015 & 0.003 \\
1 & 0.032 & 0.014 & 0.020 & 0.009 & 0.001 \\
2 & 0.037 & 0.020 & 0.052 & 0.036 & 0.007 \\
3 & 0.015 & 0.009 & 0.036 & 0.044 & 0.016 \\
4 & 0.003 & 0.001 & 0.007 & 0.016 & 0.013 \\
\bottomrule
\end{tabular}
\label{table:conf1}
\end{table}
We deliberately did not decide on a single "best" way to decide on a final single label as
the judgement on misogyny may depend on personal opinion and we believe it would be wrong to
assume there is a single correct value for each instance. Other instances may have received
labels by mistake (e.g. misinterpretation of the text or of the annotation guidelines). For creating
a training set we used different strategies to resolve disagreements (see Section~\ref{sec:model}).
We aim to make the corpus available for academic research, the necessary steps for doing this legally and in accordance with Austrian and EU data protection law are still ongoing.
This is not only the first German language corpus related to misogyny detection but also the first corpus in any language which covers such a wide range of often very subtle ways a comment may express mysogyny, and which contains many comments where human annotators will have different opinions on which label is most adequate.
\section{Sexism Classification Model}
\label{sec:model}
The main purpose of the deployed classification model is to alert moderators both of individual
sexist comments and article forums with a high rate of potentially sexist comments. For this
reason, our main interest is a binary classifier (original label 0 vs original labels 1 to 4).
However we also studied the performance of a model for predicting the original label, both
as seen as a multiclass classification task and as an ordinal regression task. Finally, we
investigated if combining both the binary and multiclass tasks into a multi-task model would
impair or improve the performance of the individual tasks.
All models are based on a transformer architecture \cite{Vaswani2017a} with one or two classification
heads on top of the pooling layer. We used the pretrained German BERT models \texttt{gbert-base}\footnote{\url{https://huggingface.co/deepset/gbert-base/tree/main}} and
\texttt{gbert-large}\footnote{\url{https://huggingface.co/deepset/gbert-large/tree/main}} \cite{Chan2020}.
For all models, accuracy and F1.0-macro metrics where estimated using 5-fold cross-validation
with class-stratified folds. 10\% of the training set were used as dev-set and this split
was class-stratified as well. Hyper-parameters where selected in a step-wise process where manually chosen values for a few hyper-parameters were evaluated using grid search. For many parameters, however, there was no clear best selection as the range of F1.0-macro estimation results introduced by different random seeds was larger or comparable to the changes in F1.0-macro estimation for different parameter values. In such cases we chose an intermediate value among those with similar estimates. The final set of hyper-parameters used for all models described below was:
BERT maximum sequence length 192, batch size 8, gradient accumulation: 1 batch, learning rate
7.5e-06, language model dropout rate 0.1 and no layer-wise learning rate adjustment. The AdamW optimizer with weight decay 0.01 and linear warm-up during 200 training steps was used. For all classification
heads we used an addition layer with 768 hidden units, ReLU and no dropout before the actual
output layer.
We evaluated the following single-head models: Bin (binary classification), Multi (multiclass classification), Coral (multiclass classification using an implementation of the CORAL ordinal regression model \cite{Cao2020}); and the following dual-head models: BinMulti (binary and multiclass
heads combined), BinCoral (binary and CORAL heads combined). For each of these 5 models we
evaluated a variant based on the \texttt{bert-base} model (/B) and one based on the \texttt{bert-large}
model (/L).
Table~\ref{table:mostfreq} shows the estimation results (accuracy and F1.0-macro) on a training
set where the original and binarized targets where selected as the most frequently assigned labels,
falling back to the highest most frequently assigned label or the maximum assigned label.
For dual-head multitask models there are two lines, showing the binary model as head 1 (:1) and
the multiclass model as head 2 (:2).
\begin{table}[htbp!]
\caption{Accuracy and F1.0 macro estimates ($\pm$ standard deviation) for models trained on the
most frequent original (coral, multi) and binarized (bin) sexism label}
\label{table:mostfreq}
\centering
\begin{tabular}{lrr}
\toprule
Model& Accuracy & F1.0 macro \\
\midrule
Bin/B & 0.763$\pm$0.012 & 0.735$\pm$0.007 \\
Bin/L & 0.757$\pm$0.050 & 0.685$\pm$0.159 \\
Multi/B & 0.608$\pm$0.026 & \textbf{0.305}$\pm$0.013 \\
Multi/L & 0.640$\pm$0.043 & 0.262$\pm$0.093 \\
Coral/B & 0.651$\pm$0.019 & 0.281$\pm$0.011 \\
Coral/L & 0.662$\pm$0.017 & 0.250$\pm$0.082 \\
BinMulti/B:1 & 0.757$\pm$0.017 & 0.729$\pm$0.018 \\
BinMulti/B:2 & 0.612$\pm$0.015 & 0.293$\pm$0.016 \\
BinMulti/L:1 & 0.733$\pm$0.059 & 0.666$\pm$0.153 \\
BinMulti/L:2 & 0.506$\pm$0.213 & 0.255$\pm$0.121 \\
BinCoral/B:1 & 0.756$\pm$0.012 & 0.729$\pm$0.008 \\
BinCoral/B:2 & 0.656$\pm$0.013 & 0.269$\pm$0.016 \\
BinCoral/L:1 & \textbf{0.788}$\pm$0.015 & \textbf{0.763}$\pm$0.017 \\
BinCoral/L:2 & \textbf{0.658}$\pm$0.009 & 0.281$\pm$0.013 \\
\bottomrule
\end{tabular}
\end{table}
The dual-head model combining binary and CORAL ordinal regression heads shows the best
accuracy estimates both for the binary and the multiclass tasks, and also the best
F1.0-macro for the binary tasks while the performance of the base single-head multiclass
model shows best F1.0-macro for the malticlass task. Interestingly, the models based on
\texttt{bert-large} did not always perform better than those based on \texttt{bert-base}.
\begin{table}[htbp!]
\caption{Accuracy and F1.0 macro estimates ($\pm$ standard deviation) for models trained on the
highest original (coral, multi) and binarized (bin) sexism label}
\label{table:choosemax}
\centering
\begin{tabular}{lrr}
\toprule
Model& Accuracy & F1.0 macro \\
\midrule
Bin/B & 0.760$\pm$0.008 & 0.760$\pm$0.008 \\
Bin/L & \textbf{0.777}$\pm$0.006 & \textbf{0.776}$\pm$0.005 \\
Multi/B & 0.509$\pm$0.010 & \textbf{0.353}$\pm$0.009 \\
Multi/L & 0.492$\pm$0.044 & 0.305$\pm$0.108 \\
Coral/B & 0.529$\pm$0.012 & 0.302$\pm$0.014 \\
Coral/L & 0.541$\pm$0.020 & 0.333$\pm$0.023 \\
BinMulti/B:1 & 0.762$\pm$0.009 & 0.762$\pm$0.009 \\
BinMulti/B:2 & 0.515$\pm$0.028 & 0.347$\pm$0.031 \\
BinMulti/L:1 & 0.728$\pm$0.112 & 0.692$\pm$0.194 \\
BinMulti/L:2 & 0.523$\pm$0.018 & 0.320$\pm$0.104 \\
BinCoral/B:1 & 0.770$\pm$0.010 & 0.770$\pm$0.010 \\
BinCoral/B:2 & 0.536$\pm$0.009 & 0.280$\pm$0.013 \\
BinCoral/L:1 & 0.733$\pm$0.115 & 0.696$\pm$0.196 \\
BinCoral/L:2 & \textbf{0.551}$\pm$0.018 & 0.264$\pm$0.077 \\
\bottomrule
\end{tabular}
\end{table}
We also trained the same set of models on a training corpus where both the binary and
multi-class target was always selected as the highest label assigned by any annotator ("when in
doubt, treat it as misogynist"). The results for this experiment are shown in Table~\ref{table:choosemax}. On this data, the single-head binary model performed best
both with respect to accuracy and F1.0-macro, while the single-head multiclass classification
model performed best on the multiclass task with respect to F1.0-macro.
In order to get an impression for how a binary model could be used to indicate forums where
moderator intervention may be necessary because of a high number of misogynist postings, moderators
selected 6 forums of which 3 have been found to have a high observed rate of misogynist postings and
3 without. The model BinCoral/L:1 from Table~\ref{table:mostfreq} assigned a rate of 0.23, 0.17, and 0.27 of postings in each of the first 3 forums to the misogyny class but only a rate of 0.01, 0.02 and 0.07 of the second 3 forums, thus giving a good indication of which of the forums moderators should
prioritize. Looking at the actual postings labeled to be misogynist shows that in addition to
many postings which were correctly identified, there was also a high number of false positives.
However, many of these false positives are texts which are related to topics often raised in
misogynist comments. In future work, the corpus will be expanded by providing manual annotations
for the false positives detected in those evaluation runs.
The code for all experiments is based on the FARM library\footnote{https://github.com/deepset-ai/FARM} and is available online\footnote{URL withheld for anonymous review}.
Additional future work will analyse the performance of the different classification models on
comments based on source, annotator disagreement or the kind of misogyny and improve the approach both
by further improving and extending the corpus and the models used for training.
This work was conducted as part of project FemDwell\footnote{\url{https://ofai.github.io/femdwell/}} supported through FemPower IKT 2018\footnote{\url{https://austrianstartups.com/event/call-fempower-ikt-2018}}.
\bibliographystyle{acl_natbib}
| {'timestamp': '2022-12-01T02:19:26', 'yymm': '2211', 'arxiv_id': '2211.17163', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17163'} | arxiv |
\section{Introduction}
Many task-oriented dialogue (TOD) datasets and models have been proposed along with the advancement of dialogue system research.
However, the diversity in data formats and ontologies between datasets brings inconvenience to model adaptation and uniform evaluation, which potentially hinders the study of model generalization and knowledge transfer across datasets.
To address this issue, we define a unified data format that serves as the adapter between TOD datasets and models: datasets are first transformed to the unified format and then loaded by models.
Following this design, we present ConvLab-3, a flexible dialogue system toolkit supporting many datasets and models.
\begin{figure}[t]
\centering
\includegraphics[width=0.9\linewidth]{framework.jpeg}
\caption{Unified data format is a bridge connecting different datasets and dialogue models.}
\vspace{-1em}
\label{fig:framework}
\end{figure}
As illustrated in Figure \ref{fig:framework}, a unified dataset in ConvLab-3 consists of dialogues, ontology, and database (or API interface).
We define the unified format over user goal, dialogue acts, state, API result, etc. to support common tasks, while keeping the dataset-specific annotation (e.g., emotion) intact.
Once a dataset is transformed into the unified format, it can be immediately used by models on the tasks it supports.
Similarly, a model supporting the unified format can access all transformed datasets.
This feature reduces the cost of adapting $M$ models to $N$ datasets from $M\times N$ to $M+N$, saving the time of (1) researchers to conduct (especially transfer learning) experiments, (2) developers to build an agent with custom datasets, and (3) community contributors to consistently add models, datasets, and uniform data processing functions.
Compared with other dialogue toolkits such as PyDial \cite{ultes-etal-2017-pydial}, Rasa \cite{bocklisch2017rasa}, ParlAI \cite{miller-etal-2017-parlai}, and Nemo \cite{kuchaiev2019nemo}, ConvLab-3 and its predecessors \cite{lee-etal-2019-convlab,zhu-etal-2020-convlab} provide recent powerful models for all components of a dialogue system, which allows people to assemble conversational agents with different recipes and to evaluate the agent with various user simulators.
ConvLab-3 inherits the framework of ConvLab-2 \cite{zhu-etal-2020-convlab} but provides support to the unified data format for existing datasets, commonly used and state-of-the-art models, and task evaluation scripts.
Thanks to the unified data format, we further add many TOD datasets and powerful transformer-based models, including two transferable user simulators \cite{lin-etal-2021-domain,lin-etal-2022-gentus}.
In addition, we highly advanced the RL toolkit by 1) simplifying the process of building the dialogue system and user environment with different modules, 2) improving the RL training process, and 3) adding evaluation and analysis tools.
Since the formats of different datasets are unified, it is convenient to perform dataset-agnostic evaluation and investigate the effects of different transfer learning settings such as domain adaptation \cite{zhao-eskenazi-2018-zero}, domain adaptive pre-training \cite{gururangan-etal-2020-dont}, and continual learning \cite{madotto-etal-2021-continual}.
In this paper, we explore several transfer strategies and conduct comprehensive experiments on multiple tasks and settings.
Experimental results show that the benefit of transfer learning is extremely large when labeled data in the target domain is insufficient but gradually decreases as the number of labeled data increases.
Moreover, we conduct several RL experiments with multiple data scenarios, different user simulators, and the usage of uncertainty. The results show that pre-training on different data is not necessarily beneficial for initial performance but leads to better final performance, training with different user simulators leads to different dialogue system behavior, and dialogue systems that leverage uncertainty estimates in the state prediction request information from users more frequently in order to resolve uncertainty.
\begin{lstlisting}[language=Python, numbers=none, caption={Example usage of unified datasets.}]
from convlab.util import *
dataset_name = "multiwoz21"
# load dataset: a dict maps data_split to dialogues
dataset = load_dataset(dataset_name)
# load dataset in a predefined order with a custom
# split ratio for reproducible few-shot experiments
dataset = load_dataset(dataset_name, \
dial_ids_order=0, split2ratio={"train": 0.01})
# load ontology and database similarly
ontology = load_ontology(dataset_name)
database = load_database(dataset_name)
# query the database with domain and state
state = {"hotel": {"area": "east", \
"price range": "moderate"}}
res = database.query("hotel", state, topk=3)
# Example functions based on the unified format
# load the user turns in the test set for NLU task
nlu_data = load_nlu_data(dataset, "test", "user")
# dataset-agnostic delexicalization
dataset, delex_vocab = create_delex_data(dataset)
\end{lstlisting}
\label{listing:util}
\section{Unified Data Format} \label{unified-data-format-section}
Our goal is to unify the format of annotations included in many datasets and commonly used by dialogue models (e.g., dialogue acts, state), while keeping the original format of annotations that only appear in specific datasets (e.g., emotion).
As we integrate more datasets in the future, we will transform more kinds of common annotations into the unified format.
In our unified data format, a dataset consists of (1) an \textbf{ontology} that defines the annotation schema, (2) \textbf{dialogues} with transformed annotations, and (3) a \textbf{database or API interface} that links to external knowledge sources.
Further, the metadata of the dataset such as the format transformation process and data statistics are described in a dataset card.
As shown in Listing \ref{listing:util}, we provide utility functions to process the unified datasets, such as delexicalization, splitting data for few-shot learning, and loading data for specific tasks.
Based on the unified format, evaluations of common tasks are standardized.
We list datasets and models supporting the unified data format in Table \ref{tab:datasets} and \ref{tab:tasks} respectively.
\begin{table*}[t]
\small
\centering
\setlength{\tabcolsep}{0.9mm}{
\begin{tabular}{c|ccc|cccccc}
\toprule
\multirow{2}{*}{Dataset} & \multicolumn{3}{c|}{Statistics} & \multicolumn{6}{c}{Dataset Annotations} \\
& \#Dialogues & Avg. Turns & Domains & Goal & DA-U & DA-S & State & API Result & Database \\
\midrule
Camrest \cite{wen-etal-2016-conditional} & 676 & 10.8 & 1 & \checkmark & \checkmark & \checkmark & \checkmark & & \checkmark \\
WOZ 2.0 \cite{mrksic-etal-2017-neural} & 1200 & 7.4 & 1 & & \checkmark & & \checkmark & & \\
KVRET \cite{eric-etal-2017-key} & 3030 & 5.3 & 3 & & \checkmark & & \checkmark & \checkmark \\
DailyDialog \cite{li-etal-2017-dailydialog} & 13118 & 7.9 & 10 & & \checkmark & & & & \\
Taskmaster-1 \cite{byrne-etal-2019-taskmaster} & 13175 & 21.2 & 6 & & \checkmark & \checkmark & \checkmark & & \\
Taskmaster-2 \cite{byrne-etal-2019-taskmaster} & 17303 & 16.9 & 7 & & \checkmark & \checkmark & \checkmark & & \\
MultiWOZ 2.1 \cite{eric-etal-2020-multiwoz} & 10438 & 13.7 & 8 & \checkmark & \checkmark & \checkmark & \checkmark & & \checkmark \\
Schema-Guided \cite{rastogi2020sgd} & 22825 & 20.3 & 45 & & \checkmark & \checkmark & \checkmark & \checkmark & \\
MetaLWOZ \cite{li2020metalwoz} & 40203 & 10.4 & 51 & \checkmark & & & & & \\
CrossWOZ \cite{zhu-etal-2020-crosswoz} & 6012 & 16.9 & 6 & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark & \checkmark \\
Taskmaster-3 \cite{byrne-etal-2021-tickettalk} & 23757 & 20.1 & 1 & & \checkmark & \checkmark & \checkmark & \checkmark & \\
\bottomrule
\end{tabular}
}
\caption{Statistics and annotations of current unified datasets. DA-U/DA-S is dialogue acts annotation of user/system.}
\label{tab:datasets}
\end{table*}
\begin{table*}[t]
\small
\centering
\setlength{\tabcolsep}{0.8mm}{
\begin{tabular}{c|c|c|c|cccc|c}
\toprule
\multirow{2}{*}{Task} & \multirow{2}{*}{Input} & \multirow{2}{*}{Output} & \multirow{2}{*}{Models} & \multicolumn{4}{c|}{Annotations} & \multirow{2}{*}{Database}\\
&&&& Goal & DA-U & DA-S & State & \\
\midrule
RG & Context & Response & T5 &&&&&\\
Goal2Dial & Goal & Dialogue & T5 & \checkmark &&&& \\
NLU & Context & DA-U & T5, BERTNLU, MILU && \checkmark &&& \\
DST & Context & State & T5, (Set)SUMBT, TripPy &&&& \checkmark & \\
Policy & State, DA-U, Database & DA-S & DDPT, PPO, PG && \checkmark & \checkmark & \checkmark & \checkmark \\
Word-Policy & Context, State, Database & Response & LAVA &&&& \checkmark & \checkmark \\
NLG & DA-S & Response & T5, SC-GPT &&& \checkmark && \\
End2End & Context, Database & State, Response & SOLOIST &&&& \checkmark & \checkmark \\
User Simulator & Goal, DA-S & DA-U, (Response) & TUS, GenTUS &\checkmark & \checkmark & \checkmark && \\
\bottomrule
\end{tabular}
}
\caption{Tasks and models supported by the unified data format. RG is response generation without database support. Goal2Dial is generating a dialogue from a user goal. NLU is natural language understanding. BERTNLU, MILU, PPO, PG are from ConvLab-2 \cite{zhu-etal-2020-convlab}.}
\label{tab:tasks}
\end{table*}
\subsection{Ontology}
Following \citet{rastogi2020sgd}, an ontology consists of:
(1) Domains and their slots in a hierarchical format. Each slot has a Boolean flag indicating whether it is a categorical slot (whose value set is small and fixed).
(2) All possible intents in dialogue acts.
(3) Possible dialogue acts appeared in the dialogues. Each act is comprised of intent, domain, slot, and originator (i.e., system or user).
(4) Template dialogue state.
We also provide a natural language description, if any, for each domain, slot, and intent to facilitate few-shot learning \cite{mifei2022cins} and domain transfer \cite{lin-etal-2021-leveraging}.
\subsection{Dialogues}
For dialogue in the unified format, dialogue-level information includes the dataset name, data split, unique dialogue ID, involved domains, user goal, etc.
Following MultiWOZ \cite{budzianowski-etal-2018-multiwoz}, a user goal has informable slot-value pairs, requestable slots, and a natural language instruction summarizing the goal.
Turn-level information includes speaker, utterance, dialogue acts, state, API result, etc.
Each dialogue act is a tuple consisting of intent, domain, slot, and value.
According to the value, we divide dialogue acts into three groups:
(1) \textbf{categorical} for categorical slots whose value set is predefined in the ontology (e.g., inform the weekday of a flight).
(2) \textbf{non-categorical} for non-categorical slots whose values can not be enumerated (e.g., inform the address of a hotel).
(3) \textbf{binary} for intents without actual values (e.g., request the address of a hotel).
The state is initialized by the template state as defined by the ontology and updated during the conversation, containing slot-value pairs of involved domains.
An API result is a list of entities retrieved from the database or other knowledge sources.
We list common annotations included in the unified data format and the tasks they support in Table \ref{tab:tasks}.
Other dataset-specific annotations are retained in their original formats.
\subsection{Database/API Interface}
To unify the interaction with different types of databases, we define a base class \texttt{BaseDatabase} that has an abstract \texttt{query} function to be customized.
The \texttt{query} function takes the current domain, dialogue state, and other custom arguments as input and returns a list of top-k candidate entities which is consistent with the format of the API result in dialogues.
By inheriting \texttt{BaseDatabase} and overriding the \texttt{query} function, we can access different databases/APIs in a similar fashion.
\section{New Models}
Besides models already included in ConvLab-2, we integrate new transformer-based models supporting the unified data format as shown in Table \ref{tab:tasks}: SUMBT \cite{lee-etal-2019-sumbt}, SetSUMBT \cite{van-niekerk-etal-2021-uncertainty} and TripPy \cite{heck-etal-2020-trippy} for dialogue state tracking (DST), DDPT \cite{geishauser-etal-2022-dynamic} and LAVA \cite{lubis-etal-2020-lava} for policy learning, SC-GPT \cite{peng-etal-2020-shot} for natural language generation (NLG), SOLOIST \cite{peng-etal-2021-soloist} with T5 as backbone model
\cite{peng2022godel}
for end-to-end modeling (End2End), as well as TUS \cite{lin-etal-2021-domain} that outputs user dialogue acts and GenTUS \cite{lin-etal-2022-gentus} that outputs both user dialogue acts and response for user simulation (US).
\begin{table}[t]
\centering
\small
\begin{tabular}{@{}p{7.7cm}@{}}
\toprule
\textbf{User}: I am looking for a \textbf{\textit{cheap}} restaurant. \\
\textbf{System}: Is there a particular area of town you prefer? \\
\textbf{User}: In the \textbf{\textit{centre}} of town. \\ \midrule
\textbf{DA-U}:[inform][restaurant]([area][centre]) \\
\textbf{State}: [restaurant]([area][centre],[price range][cheap]) \\
\textbf{DA-S}: [recommend][restaurant]([name][Zizzi Cambridge]) \\ \midrule
\textbf{System}: I would recommend \textbf{\textit{Zizzi Cambridge}}. \\
\bottomrule
\end{tabular}
\caption{Example serialized dialogue acts and state.
Dialogue acts are in the form of ``[intent] [domain] ([slot] [value],...);...''. State is in the form of ``[domain] ([slot] [value],...);...''. Multiple items are separated by a semicolon.}
\label{tab:serialization}
\end{table}
Inspired by \citet{raffel2020t5} that converts all NLP tasks into a text-to-text format, we provide serialization and deserialization methods for annotations in the unified data format, as shown in Table \ref{tab:serialization}.
In this way, we can apply a text-to-text model to solve any task in Table \ref{tab:tasks}.
As an example, we provide a unified training script for T5 \cite{raffel2020t5}, producing a family of models including T5-NLU, T5-DST, T5-NLG, etc.
Other pre-trained language models such as GPT-2 \cite{radford2019language} could similarly be used as backbone models.
We regard these models as base models to solve a task since they are not involved with dataset/task-specific model design and are simple to use.
Developers that are unfamiliar with dialogue models could conveniently use the base models for their custom datasets.
\section{Reinforcement Learning Toolkit}
Compared to ConvLab-2, we improve the reinforcement learning toolkit for the dialogue policy module in ConvLab-3.
We simplify the process of building the dialogue system and its RL environment, extend the modularity of the vectorizer codebase, incorporate multiple US, and offer a wide range of evaluation metrics.
\subsection{Pipeline Setup}
A dialogue system agent can be comprised of a wide range of sub-modules as mentioned in Table \ref{tab:tasks}. ConvLab-3 fully supports the straightforward building of any combination and allows easy substitution of components. This also includes the definition of the agent environment given by the choice of user policy and its components. In ConvLab-3 various components can be easily combined using an easy-to-use configuration file.
\subsection{Vectorizer Class}
\label{subsection:vectoriser_class}
The dialogue policy module trained using RL obtains the output of the DST as input and typically outputs a semantic action. Just as ConvLab-2, ConvLab-3 uses a vectorizer class as a communication module that translates the semantic actions and DST output into vectorized representations using the given ontology. We extend and modify that module and make the vectorizer easily interchangeable in order to use different vectorization strategies. Firstly, we add the possibility for masking certain actions as in \citet{ultes-etal-2017-pydial} to aid policy learning or to prevent the policy from taking invalid actions. Secondly, the module leverages the functionalities described in Section \ref{unified-data-format-section} to allow easy adaptation to new datasets.
As the vectorizer module takes care of producing a suitable input representation, it is possible to use any off-the-shelf neural network architecture for the policy module and only modify the vectorizer to fit the required input. As an example, \citet{van-niekerk-etal-2021-uncertainty} defines a belief tracking module that outputs a semantic state accompanied by relevant uncertainty scores, which are used as input to the policy. In order to implement the change, the policy module can remain untouched while only a new vectorizer (inheriting from the base class) needs to be implemented with one required class method. This simplifies the integration of new policy modules and vectorization strategies.
\subsection{Evaluation Tools}
The core metrics for a dialogue policy trained using RL are \emph{success} and \emph{return} \cite{gasic-committee-2015}. Nevertheless, as these policies are built for interacting with humans, it is necessary to provide an in-depth analysis of their behavior. For instance, is the policy providing too many actions in a turn, which a simulator can handle well but lead to an information overload for real humans? Does the policy have a tendency to only use some specific intents but neglect others? How are the actions taken by the system distributed in general? In order to easily answer these questions, we provide plotting tools to conveniently compare algorithms with each other, both in terms of performances and action distributions. Moreover, ConvLab-3 provides an evaluation function to inspect generated dialogues, thereby enabling full understanding of the dialogue policy behavior. We will showcase the additional analysis tools in Section \ref{rl-analysis}. Lastly, we use a stricter form of task success that we call \textit{strict success}, which extends the previous success definition. While the previous version checked whether the necessary information was provided and an entity was booked if required, it did not check whether the entity fulfills the booking constraints. As a consequence, it was possible to book an entity for a wrong day, with a wrong number of people but still be successful.
In summary, these changes allow easy building, extension, and evaluation of dialogue policies, making them more accessible to researchers.
\section{Experimental Setup}
To show how the new features of our platform may promote TOD research, we conduct comprehensive experiments, which can be categorized into reinforcement learning for the dialogue policy module and supervised learning for other modules.
\subsection{Supervised Learning}
Based on the unified data format, conducting experiments on multiple TOD datasets is convenient.
We believe this feature will encourage researchers to build general dialogue models that perform well on different datasets and investigate knowledge transfer between them.
To provide insight into how to transfer knowledge from other datasets, we explore three typical transfer learning settings on various tasks, namely (1) pre-train on other datasets and then fine-tune on the target dataset, (2) joint training on the target dataset and other datasets, and (3) retrieve samples that are similar to the samples of the target dataset from other datasets as additional training data or as in-context learning examples.
\paragraph{Datasets}
We use MultiWOZ 2.1 \cite{eric-etal-2021-multi}, the Schema-Guided Dialogue (SGD) dataset \cite{rastogi2020sgd}, and Taskmaster-1/2/3 \cite{byrne-etal-2019-taskmaster,byrne-etal-2021-tickettalk} for our experiments since they are large and have rich annotations.
We regard MultiWOZ 2.1 as the target dataset.
\paragraph{Metrics}
We evaluate our newly integrated models covering various tasks with classic metrics:
turn accuracy (ACC) and dialogue act F1 score for NLU \cite{zhu-etal-2020-convlab}, joint goal accuracy (JGA) and slot F1 score for DST \cite{li2021dstc9}, BLEU and slot error rate (SER) for NLG \cite{wen-etal-2015-semantically}, BLEU and Combined score (Comb.) for End2End \cite{mehri-etal-2019-structured}, turn accuracy and slot-value F1 score \cite{lin-etal-2021-domain} for user simulators that output user dialogue acts only (US-DA), and slot-value F1 score and SER for user simulators that output both user dialogue acts and response (US-NL) \cite{lin-etal-2022-gentus}.
Note that the calculation of Combined score for End2End is not the exactly same as those in previous works \cite{peng-etal-2021-soloist} because we use our own dataset-agnostic delexicalization instead of the MultiWOZ-specific one \cite{budzianowski-etal-2018-multiwoz}.
Since SGD and Taskmaster do not have goal annotations, we calculate the turn-level slot-value F1 score between original responses and generated responses instead of Combined score on these datasets.
For NLG, we ignore utterances with empty dialogue acts.
\subsubsection{Pre-training then Fine-tuning}
In this experiment, we explore knowledge transfer through pre-training on other TOD datasets before fine-tuning.
We pre-trained models on SGD and Taskmaster datasets and then fine-tuned the models on MultiWOZ in full-data or low-resource (1\%, 10\% of the entire training set) settings.
As shown in Listing \ref{listing:util}, it is easy to control the data to use in few-shot learning experiments through the data loading function.
For low-resource fine-tuning, we set the data ratios of both training and validation set to 1\%/10\% and run the training 3 times with different subsets of samples.
If not mentioned otherwise, for existing models we follow the settings of their original papers.
We use \texttt{T5-Small} for T5-NLU, T5-DST, and T5-NLG.
We initialize SC-GPT and SOLOIST with \texttt{GPT2-Medium} and \texttt{T5-Base} respectively instead of their checkpoints pre-trained on many TOD datasets.
For pre-training, we merge SGD and Taskmaster datasets.
Training details and hyper-parameters can be found in our GitHub repository.
\subsubsection{Joint Training}
In this experiment, we investigate the effect of training a model on multiple datasets jointly instead of separately.
For joint training, we merge MultiWOZ, SGD, and Taskmaster datasets into one and train a single model, which requires the model to handle datasets with different ontologies.
Intuitively, the advantage of joint training is that knowledge transfer is bi-directional and persists for the whole training period, while the disadvantage is that there may be inconsistent labels for similar inputs on different datasets, potentially confusing the models.
To avoid confusion, for T5-NLU, T5-DST, and T5-NLG, we prepend the dataset name to the original input to distinguish data from different datasets.
For SetSUMBT, we only predict the state of the target dataset.
Since SGD may have several services for one domain, we normalize the service name to the domain name (e.g., \texttt{Restaurant\_1} to \texttt{Restaurant}) when evaluating NLU and DST.
However, similar slots of different services (e.g., \texttt{city} and \texttt{location}) will still confuse the model.
While further normalization may help, we are aiming to compare independent training and joint training instead of achieving SOTA performance.
For Taskmaster-1/2/3, we evaluate each sample with the corresponding ontology and then calculate the metrics on all test samples of three datasets.
In addition, on SGD and Taskmaster, we build pseudo user goals for TUS and GenTUS by accumulating constraints and requirements in user dialogue acts during conversations.
\subsubsection{Retrieval Augmentation}
We further explore transferring knowledge from other datasets through retrieval-based data augmentation.
Here we only consider the single-turn NLU task where the input is an utterance, since utterance-level similarity is easier to model than dialogue-level similarity.
For each utterance in the target dataset, we retrieve the top-k (k $\in \{1,3\}$) most similar utterances from other datasets measured by the MiniLMv2 model \cite{wang-etal-2021-minilmv2} using Sentence Transformers \cite{reimers-gurevych-2019-sentence}
We then use retrieved samples in two ways:
\begin{enumerate}
\item Augment training data. Models are trained on both original training data and retrieved data.
\item Additionally input the retrieved samples as in-context examples, including retrieved utterances and their dialogue acts, as shown in Table \ref{tab:in-context}. Different from \citet{liu-etal-2022-makes}, the retrieved samples are from other datasets instead of the target dataset and we will train models on augmented samples.
\end{enumerate}
Since different datasets have different ontologies (i.e., definitions of intent, domain, slot), we prepend the corresponding dataset name to an input utterance as in the joint training experiment.
We use the T5-NLU model and try two model sizes \texttt{T5-Small} and \texttt{T5-Large}.
We fine-tune the models on MultiWOZ using the same settings as in the pre-training-then-fine-tuning experiment.
\begin{table}[t]
\centering
\small
\begin{tabular}{@{}p{7.7cm}@{}}
\toprule
\textbf{Original input}: user: Yes please, for 8 people at 18:30 on thursday. \\ \midrule
\textbf{Augmented input}: \colorbox{yellow}{\textbf{tm3}} user: Yes, please, four for 8:10pm. \\=> [inform] [movie]([num.tickets][four],[time.showing][8:10 pm]) \colorbox{brown}{\textbf{tm1}} user: Yes, 8PM, please. => [inform][restaurant \_reservation]([time.reservation][8PM]) \colorbox{cyan}{\textbf{sgd}} user: Yes please, for 3 people on March 8th at 12:30 pm. => [affirm\_intent] [Restaurants\_1]([][]);[inform][Restaurants\_1] ([party\_size][3]\\
{[date][March 8th],[time][12:30 pm])} \colorbox{green}{\textbf{multiwoz21}} user: Yes please, for 8 people at 18:30 on thursday. \\ \midrule
\textbf{Output}: [inform][restaurant]([book day][thursday],[book time][18:30],[book people][8]) \\
\bottomrule
\end{tabular}
\caption{An example of input augmented by retrieved top-3 samples from other TOD datasets for in-context learning. Dataset names are highlighted.}
\vspace{-1em}
\label{tab:in-context}
\end{table}
\subsection{Reinforcement Learning}
In order to showcase our RL toolkit, we conduct several experiments. The first set of experiments leverages the convenient unified format for pre-training policies before starting the RL training. The second set of experiments regards training with multiple user simulators as well as incorporating uncertainty estimates in state representation.
\subsubsection{Pre-training then RL Training}
In this experiment, we simulate different data scenarios before starting the RL training. We leverage the implemented DDPT policy model for training as its flexibility allows transfer from one ontology to another. We test four different scenarios:
\begin{enumerate}
\item \textbf{Scratch}: the policy starts the RL training with random initialization. This simulates the zero data scenario.
\item \textbf{SGD}: the policy is pre-trained on the full SGD data before the RL training starts. This simulates having related data.
\item \textbf{1\%MWOZ}: the policy is pre-trained on 1\% of MultiWOZ 2.1 data. This simulates having scarce in-domain data.
\item \textbf{SGD->1\%MWOZ}: the policy is pre-trained on the full SGD data, then fine-tuned on 1\% of MultiWOZ 2.1 data before the RL training starts. This simulates having related data as well as scarce in-domain data.
\end{enumerate}
The unified format conveniently allows us to pre-train on different datasets by only specifying the dataset name. The experiments are conducted on the semantic level, leveraging the rule-based dialogue state tracker and the rule-based user simulator \cite{schatzmann-etal-2007-agenda} of ConvLab-3.
\subsubsection{Training with Different User Simulators}
To ensure a policy learns a general skill that can solve the task with diverse users instead of overfitting to a certain user simulator, it is important to test the policy with various user simulators. ConvLab-3 provides the SOTA user simulators TUS and GenTUS and allows easy usage through the simplified pipeline setup. In this set of experiments, we compare TUS, GenTUS and the rule-based simulator ABUS by training a dialogue policy in interaction with each of them and performing cross-model evaluation afterwards. The dialogue policy used is a simple multilayer perceptron and optimized using PPO \cite{ppo}. The simulators and policy are pre-trained on MultiWOZ 2.1 and experiments are run on the semantic level using the rule-based dialogue state tracker.
\subsubsection{Training with Uncertainty Features}
The simplified vectorizer module in ConvLab-3 makes it possible to easily include dialogue related features that might benefit dialogue policy learning. One such example is given due to the problem of resolving ambiguities in conversations. Humans naturally identify these ambiguities and resolve the uncertainty resulting from them. For a dialogue system to be robust to ambiguity, it is crucial to identify and resolve these uncertainties \cite{van-niekerk-etal-2021-uncertainty}.
ConvLab-3 provides the SetSUMBT dialogue belief tracker which achieves SOTA performance in terms of the accuracy of its uncertainty estimates. Using the vectorizer class to incorporate these features we can train a policy using the uncertainty features obtained from SetSUMBT. To illustrate the effectiveness of uncertainty features during RL, we train a PPO policy using these features. The template-based NLG in ConvLab-3 also allows for the inclusion of noise~\cite{van-niekerk-etal-2021-uncertainty} in generated responses which allows for uncertainties to arise during the conversation, simulating a more realistic conversation.
\section{Result Analysis}
\subsection{Supervised Learning}
\subsubsection{Pre-training then Fine-tuning}
\begin{table}[t]
\small
\centering
\setlength{\tabcolsep}{0.5mm}{
\begin{tabular}{@{}lcc|cc|cc@{}}
\toprule
& \multicolumn{6}{c}{MultiWOZ 2.1} \\
& \multicolumn{2}{c}{1\%} & \multicolumn{2}{c}{10\%} & \multicolumn{2}{c}{100\%}\\ \cmidrule{2-7}
\textbf{NLU} & ACC & F1 & ACC & F1 & ACC & F1 \\ \midrule
\multirow{2}{*}{T5-NLU} & 48.1 & 64.6 & 68.8 & 80.6 & 77.8 & 86.5 \\
& 55.5 & 70.1 & 69.8 & 81.0 & 77.9 & 86.5 \\ \midrule \midrule
\textbf{DST} & JGA & Slot F1 & JGA & Slot F1 & JGA & Slot F1 \\ \midrule
\multirow{2}{*}{T5-DST} & 14.5 & 68.5 & 35.5 & 84.8 & 52.6 & 91.9 \\
& 22.9 & 74.9 & 41.2 & 87.1 & 53.1 & 92.0 \\ \midrule
\multirow{2}{*}{SetSUMBT}& 7.8 & 41.8 & 37.0 & 84.4 & 50.3 & 90.8 \\
& 22.7 & 77.2 & 43.8 & 88.2 & 50.7 & 91.2 \\ \midrule \midrule
\textbf{NLG} & SER $\downarrow$ & BLEU & SER $\downarrow$ & BLEU & SER $\downarrow$ & BLEU \\ \midrule
\multirow{2}{*}{T5-NLG} & 19.0 & 20.2 & 6.9 & 31.3 & 3.7 & 35.8 \\
& 9.8 & 25.8 & 5.5 & 32.9 & 3.5 & 35.8 \\ \midrule
\multirow{2}{*}{SC-GPT} & 27.3 & 14.1 & 11.2 & 28.4 & 4.8 & 33.6 \\
& 9.5 & 26.3 & 6.9 & 28.6 & 5.3 & 32.1 \\ \midrule \midrule
\textbf{End2End} & Comb. & BLEU & Comb. & BLEU & Comb. & BLEU \\ \midrule
\multirow{2}{*}{SOLOIST}& 19.8 & 0.4 & 48.0 & 10.0 & 67.0 & 16.8 \\
& 42.2 & 10.4 & 62.0 & 15.9 & 71.4 & 17.5 \\ \midrule \midrule
\textbf{US-DA} & ACC & F1 & ACC & F1 & ACC & F1 \\ \midrule
\multirow{2}{*}{TUS} & 4.4 & 29.0 & 12.1 & 53.1 & 15.0 & 53.2 \\
& 22.3 & 56.2 & 26.8 & 59.9 & 33.3 & 67.9 \\ \midrule
\textbf{US-NL} & SER $\downarrow$ & F1 & SER $\downarrow$ & F1 & SER $\downarrow$ & F1 \\ \midrule
\multirow{2}{*}{GenTUS} & 24.2 & 43.6 & 8.2 & 57.0 & 4.2 & 62.5 \\
& 8.3 & 46.0 & 4.2 & 48.7 & 3.5 & 49.4 \\ \bottomrule
\end{tabular}
}
\caption{Comparison of direct fine-tuning and pre-training-then-fine-tuning (1st row vs. 2nd row of each model) in the low-resource and full data settings. Except for SER, higher scores are better.}
\vspace{-1em}
\label{tab:transfer}
\end{table}
We compare direct fine-tuning and pre-training-then-fine-tuning in Table \ref{tab:transfer}.
Generally, pre-training is beneficial, especially in the low-resource setting.
However, as the fine-tuning data size increases, the benefit gradually decreases in most cases.
When fine-tuning on the full MultiWOZ, whether or not pre-training is conducted does not matter for NLU, DST, and NLG models, while for the End2End model SOLOIST, pre-training can still improve performance.
The reason might be that end-to-end modeling is a more complex task, such that the full MultiWOZ data is still not enough to reach saturated performance.
Compared with other models, the user simulators TUS and GenTUS behave differently. Pre-training largely boosts the performance of TUS because it uses domain-agnostic features for semantic actions, thus it can focus on the cross-domain user behavior on the semantic level.
Pre-training-then-fine-tuning on 1\% MultiWOZ data is even better than directly fine-tuning on the full MultiWOZ data.
For GenTUS, the observation is quite different.
With pre-training, the F1 score is improved in the 1\% data fine-tuning setting but is largely restricted when more fine-tuning data is available, while the SER is consistently improved.
Note that SER is calculated using self-generated dialogue acts instead of the golden ones, measuring the faithfulness of utterance generation.
This indicates that pre-training biases GenTUS towards a user behavior that differs from users in MultiWOZ but makes utterance generation more accurate.
\begin{table}[t]
\small
\centering
\setlength{\tabcolsep}{0.5mm}{
\begin{tabular}{@{}lcc|cc|cc@{}}
\toprule
& \multicolumn{2}{c}{MultiWOZ 2.1} & \multicolumn{2}{c}{SGD} & \multicolumn{2}{c}{Taskmaster}\\ \cmidrule{2-7}
\textbf{NLU} & ACC & F1 & ACC & F1 & ACC & F1 \\ \midrule
\multirow{2}{*}{T5-NLU} & 77.8 & 86.5 & 45.0 & 58.6 & 81.8 & 73.0 \\
& 77.5 & 86.4 & 45.2 & 58.6 & 81.8 & 73.0 \\ \midrule \midrule
\textbf{DST} & JGA & Slot F1 & JGA & Slot F1 & JGA & Slot F1 \\ \midrule
\multirow{2}{*}{T5-DST} & 52.6 & 91.9 & 20.1 & 58.5 & 48.5 & 81.1 \\
& 53.1 & 91.9 & 20.6 & 60.0 & 48.6 & 81.0 \\ \midrule
\multirow{2}{*}{SetSUMBT}& 50.3 & 90.8 & 20.0 & 58.8 & 24.9 & 65.5 \\
& 50.8 & 91.0 & 21.1 & 59.2 & 25.3 & 67.0 \\ \midrule \midrule
\textbf{NLG} & SER $\downarrow$ & BLEU & SER $\downarrow$ & BLEU & SER $\downarrow$ & BLEU \\ \midrule
\multirow{2}{*}{T5-NLG} & 3.7 & 35.8 & 11.9 & 29.6 & 2.1 & 51.5 \\
& 3.2 & 35.6 & 8.3 & 29.9 & 2.0 & 51.3 \\ \midrule
\multirow{2}{*}{SC-GPT} & 4.8 & 33.6 & 9.6 & 28.2 & 2.2 & 47.9 \\
& 3.3 & 33.5 & 6.8 & 29.8 & 1.6 & 47.3 \\ \midrule \midrule
\textbf{End2End} & Comb. & BLEU & Slot F1 & BLEU & Slot F1 & BLEU \\ \midrule
\multirow{2}{*}{SOLOIST}& 67.0 & 16.8 & 56.9 & 11.2 & 8.5 & 28.0 \\
& 71.4 & 17.1 & 69.7 & 23.1 & 9.2 & 29.2 \\ \midrule \midrule
\textbf{US-DA} & ACC & F1 & ACC & F1 & ACC & F1 \\ \midrule
\multirow{2}{*}{TUS} & 15.0 & 53.2 & 10.2 & 11.6 & 23.0 & 23.0 \\
& 32.0 & 62.3 & 13.8 & 15.6 & 22.5 & 22.0 \\ \midrule
\textbf{US-NL} & SER $\downarrow$ & F1 & SER $\downarrow$ & F1 & SER $\downarrow$ & F1 \\ \midrule
\multirow{2}{*}{GenTUS} & 4.2 & 62.5 & 8.4 & 48.8 & 4.2 & 43.8 \\
& 3.3 & 49.5 & 8.0 & 48.7 & 3.5 & 43.9 \\ \bottomrule
\end{tabular}
}
\caption{Comparison of independent training and joint training (1st row vs. 2nd row of each model) on 3 datasets. We normalize the service name to the domain name when evaluating NLU and DST on SGD.}
\vspace{-1em}
\label{tab:multitask}
\end{table}
\subsubsection{Joint Training}
We compare independent training and joint training in Table \ref{tab:multitask}.
MultiWOZ, SGD, and Taskmaster have 8K, 16K, and 43K dialogues for training respectively.
Joint training on these datasets does not lead to substantial performance drops in most cases, indicating that models have sufficient capacity to encode knowledge of different datasets simultaneously.
However, joint training does not always improve performance either.
It consistently improves the End2End model SOLOIST but makes no difference to T5-NLU.
For other models, the gains vary with the dataset.
Associating with the previous pre-training-then-fine-tuning experiment, we think the difference may be attributed to the varying task complexity on different datasets.
When the original data of a certain dataset are sufficient for a model to solve the task, including other datasets via joint training may not bring further benefit.
\subsubsection{Retrieval Augmentation}
\begin{table}[t]
\small
\centering
\begin{tabular}{@{}lcc|cc|cc@{}}
\toprule
\multirow{2}{*}{\textbf{T5-NLU}} & \multicolumn{6}{c}{\qquad \ MultiWOZ 2.1} \\
& \multicolumn{2}{c}{1\%} & \multicolumn{2}{c}{10\%} & \multicolumn{2}{c}{100\%} \\ \cmidrule{2-7}
\textbf{T5-small} & ACC & F1 & ACC & F1 & ACC & F1 \\ \midrule
Baseline & 48.1 & 64.6 & 68.8 & 80.6 & 77.8 & 86.5\\
Pre-trained & 55.5 & 70.1 & 69.8 & 81.0 & 77.9 & 86.5\\ \midrule
\textit{Data Aug.} & & & & & & \\
\quad - top1 & 51.4 & 66.8 & 69.0 & 80.6 & 77.5 & 86.5\\
\quad - top3 & 51.3 & 66.4 & 68.8 & 80.6 & 77.0 & 86.2\\ \midrule
\textit{In-context} & & & & & & \\
\quad - top1 & 44.5 & 61.3 & 68.5 & 80.1 & 77.7 & 86.4\\
\quad - top3 & 43.6 & 60.8 & 68.1 & 79.8 & 77.5 & 86.4\\ \midrule \midrule
\textbf{T5-large} & ACC & F1 & ACC & F1 & ACC & F1 \\ \midrule
Baseline & 51.2 & 67.9 & 67.8 & 80.0 & 76.8 & 86.4\\
Pre-trained & 56.7 & 71.7 & 69.5 & 81.0 & 76.8 & 86.1\\ \midrule
\textit{Data Aug.} & & & & & & \\
\quad - top1 & 49.7 & 66.8 & 68.7 & 80.6 & 76.9 & 86.1\\
\quad - top3 & 48.5 & 66.2 & 68.5 & 80.5 & 76.3 & 85.8\\ \midrule
\textit{In-context} & & & & & & \\
\quad - top1 & 43.4 & 61.3 & 69.1 & 81.0 & 76.5 & 85.9\\
\quad - top3 & 43.9 & 63.0 & 68.7 & 80.8 & 76.9 & 86.2\\ \bottomrule
\end{tabular}
\caption{Comparison of different ways to use other TOD datasets: (1) pre-training, (2) retrieving similar samples for data augmentation or (3) in-context learning.}
\vspace{-1em}
\label{tab:retrieval}
\end{table}
\begin{figure*}[t!]
\begin{subfigure}[t]{0.32\textwidth}
\includegraphics[scale=0.35]{figures/RL_transfer/_success_rate_strict.pdf}
\caption{Strict success rate}
\end{subfigure}
\hspace{0.01\textwidth}%
\begin{subfigure}[t]{0.32\textwidth}
\includegraphics[scale=0.35]{figures/RL_transfer/_turns.pdf}
\caption{Number of turns}
\end{subfigure}
\hspace{0.01\textwidth}%
\begin{subfigure}[t]{0.32\textwidth}
\includegraphics[scale=0.35]{figures/RL_transfer/_avg_actions.pdf}
\caption{Average number of actions per turn}
\end{subfigure}
\caption{Pre-training then RL training experiments with the DDPT model in interaction with the rule-based simulator. Shaded regions show standard error. Each model is evaluated on 9 different seeds.}
\label{pretrain-rl}
\end{figure*}
\begin{figure*}[t!]
\begin{subfigure}[t]{0.32\textwidth}
\includegraphics[scale=0.35]{figures/RL_transfer/request_probability.pdf}
\caption{Probability of taking \textit{request} intent in a turn}
\end{subfigure}
\hspace{0.01\textwidth}%
\begin{subfigure}[t]{0.32\textwidth}
\includegraphics[scale=0.35]{figures/RL_transfer/offer_probability.pdf}
\caption{Probability of taking \textit{offer} intent in a turn}
\end{subfigure}
\hspace{0.01\textwidth}%
\begin{subfigure}[t]{0.32\textwidth}
\includegraphics[scale=0.35]{figures/RL_transfer/inform_probability.pdf}
\caption{Probability of taking \textit{inform} intent in a turn}
\end{subfigure}
\caption{Intent distributions observed during the training process of DDPT while interacting with the rule-based user simulator. }
\label{pretrain-rl-distributions}
\end{figure*}
We compare retrieval augmentation methods with direct fine-tuning (Baseline) and pre-training-then-fine-tuning as shown in Table \ref{tab:retrieval}.
We can see that the performances of different models mainly differ in the 1\% data setting, and retrieving top-1 or top-3 samples does not have a large effect.
In the 1\% data setting, using retrieved samples to augment inputs for training is even worse, while augmenting the training set with retrieved samples is beneficial for \texttt{T5-Small} but disadvantageous for \texttt{T5-Large}.
Using other TOD datasets for pre-training is better than or on par with using them for two retrieval augmentation methods and direct fine-tuning.
The reason may be that different datasets' ontologies for similar utterances consistently confuse the models when training on retrieved samples or augmented input, while pre-trained models will no longer be distracted by other datasets' ontologies during fine-tuning.
From the example in Table \ref{tab:in-context}, although retrieved samples may extract important values, they assign different intent, domain, and slot names to these values, which are not transferable to the target dataset, calling for a better way to use other TOD datasets.
\subsection{Reinforcement Learning} \label{rl-analysis}
\subsubsection{Pre-training Then RL Training}
Let us first take a look at the metrics \emph{strict success rate} and \emph{number of turns}, plotted in Figure \ref{pretrain-rl}(a) and (b). We can observe that pre-training on SGD does not yield an advantage for the starting performance, compared to training from scratch. Nevertheless, looking at the final performance, we can see that the model pre-trained on SGD is different from the scratch model and reaches the same final performance as when MultiWOZ data is used. We hypothesize that pre-training on SGD effectively puts the initial policy parameters in an appropriate parameter space for dialogue learning. We can also observe that it does not seem to make a difference whether or not the policy is pre-trained on SGD before being fine-tuned on MultiWOZ, which suggests that the SGD information has been overwritten. Figure \ref{pretrain-rl}(c) shows the average number of actions taken in a turn, which is an important evaluation measure, as exposing a user to too much information can lead to information overload. Interestingly, the model only pre-trained on SGD initially takes much fewer actions in a turn, which exactly reflects what can be observed in the SGD data.
\begin{figure*}[t]
\begin{subfigure}[t]{0.32\textwidth}
\centering
\includegraphics[scale=0.35]{figures/Uncertainty/_success_rate_strict.pdf}
\caption{Strict success rate}
\end{subfigure}
\hspace{0.01\textwidth}%
\begin{subfigure}[t]{0.32\textwidth}
\centering
\includegraphics[scale=0.35]{figures/Uncertainty/request_probability.pdf}
\caption{Probability of utilising the \textit{Request} intent in a turn.}
\end{subfigure}
\hspace{0.01\textwidth}%
\begin{subfigure}[t]{0.32\textwidth}
\centering
\includegraphics[scale=0.35]{figures/Uncertainty/final_action_probabilities.pdf}
\caption{Distribution of intents for the final policies.}
\end{subfigure}
\caption{Evaluation of the PPO policy trained combined with a SetSUMBT DST model with and without uncertainty features respectively. The policy is trained in an environment that contains $5\%$ user NLG noise to illustrate the impact of uncertainty.}
\label{rl-uncertainty}
\end{figure*}
In addition to the plots depicted in Figure \ref{pretrain-rl}, the new toolkit allows us to have a look at the average intent distribution within a turn. Figure \ref{pretrain-rl-distributions} (a), (b) and (c) depict the average probability of taking a request, offer, or inform intent in a turn, respectively. We can see that SGD pre-training initially leads to many offer intents, while mostly ignoring request intents compared to pre-training on MultiWOZ. The number of inform intents is in a similar range for all models apart from the scratch model. Nevertheless, the probabilities eventually converge to the same level, which generally holds for all intents.
\begin{table}[t]
\centering
\begin{tabular}{@{}lccc@{}}
\toprule
\multirow{2}{*}{\begin{tabular}[c]{@{}l@{}}US for \\ training\end{tabular}} & \multicolumn{3}{c}{US for testing} \\
& ABUS & TUS & GenTUS \\ \midrule
ABUS & \textbf{0.93} & 0.71 & 0.56 \\
TUS & 0.87 & 0.79 & 0.59 \\
GenTUS & 0.89 & \textbf{0.86} & \textbf{0.63} \\ \bottomrule
\end{tabular}
\caption{The strict success rates of PPO policies trained on ABUS, TUS, and GenTUS when evaluated with various user simulators.}
\vspace{-1em}
\label{tab:cross-model}
\end{table}
\subsubsection{Training with Different User Simulators}
The result of strict success rates of PPO policies trained with ABUS, TUS, or GenTUS is shown in Table \ref{tab:cross-model}. The policy trained with ABUS only outperforms policies trained with the other USs when evaluated with ABUS. On the other hand, the policy trained with GenTUS outperforms the other policies when evaluated not only with GenTUS, but also with TUS. It also gets comparable performance with policies trained with ABUS when evaluated with ABUS, indicating that GenTUS trains the most robust policy.
According to the result, a policy that performs well when evaluated with the US it is trained on does not necessarily perform well on other USs.
\citet{shi-etal-2019-build} suggest evaluating a policy with different types of USs to provide a more holistic view and show the average performance correlates well with human evaluation.
In ConvLab-3, we provide not only the rule-based US, i.e., ABUS, but also data-driven USs, e.g., TUS and GenTUS, to build a richer environment for training and evaluation.
Moreover, with the two transferable USs TUS and GenTUS, researchers can easily evaluate their policy on custom datasets.
\subsubsection{Training with Uncertainty Features}
Figure \ref{rl-uncertainty} (a) reveals that the policy trained using uncertainty features performs at least as well as the policy trained without these features. \citet{van-niekerk-etal-2021-uncertainty} further showed that the policy trained with uncertainty features performs significantly better in conversation with humans than the policy trained without. This is an indication that the policy using uncertainty features can handle ambiguities in conversation better than the policy without uncertainty modeling. To investigate how this policy resolves uncertainty we analyze the action distributions of the policy using the new RL toolkit evaluation tools, which provide new insights into the behavior of dialogue policy modules. Figure \ref{rl-uncertainty} (b) and (c) show that the policy trained using uncertainty features utilizes significantly more request actions than the policy without these features. This indicates that the policy aims to resolve uncertainty by requesting information from the user. For instance, if the policy recognizes uncertainty regarding the price range a user has requested, it can resolve this through the use of a request. See \citet{van-niekerk-etal-2021-uncertainty} for example dialogues with humans where this can be observed.
\section{Conclusion}
In this paper, we present the dialogue system toolkit ConvLab-3, which puts a large number of datasets under one umbrella through our proposed unified data format. The usage of the unified format facilitates comparability and significantly reduces the implementation cost required for conducting experiments on multiple datasets. In addition, we provide recent powerful models for all components of a dialogue system and improve the RL toolkit which enables researchers to easily build, train and evaluate dialogue systems.
We showcase the advantages of the unified format and RL toolkit in a large number of experiments, ranging from pre-training, joint training, and retrieval augmentation to RL training with different user simulators and state uncertainty estimation.
We hope that ConvLab-3 can aid and accelerate the development of models that can be trained with different datasets and learning paradigms, empowering the community to develop the next generation of task-oriented dialogue systems.
\section*{Contributions}
\label{sec:contributions}
Qi Zhu, Christian Geishauser, Carel van Niekerk, Hsien-chin Lin, Baolin Peng, and Zheng Zhang are the main developers of the project. Jianfeng Gao, Milica Ga\v{s}i\'c, and Minlie Huang provided full support and gave valuable advice on project design. Qi Zhu led the project.
\paragraph{Code implementation}
Qi Zhu proposed and implemented the unified data format, transformed all datasets, adapted BERTNLU and MILU, and implemented T5 series models.
Christian Geishauser was the main contributor to the RL toolkit and adapted DDPT, PPO, PG, and MLE models.
Hsien-chin Lin adapted TUS and GenTUS, allowing training policy with different user simulators.
Carel van Niekerk adapted SUMBT and SetSUMBT, contributed to the RL toolkit, and incorporated uncertainty estimates with policy learning.
Baolin Peng adapted SOLOIST and implemented End2End evaluation metrics.
Zheng Zhang adapted SC-GPT and implemented NLG evaluation metrics.
Michael Heck adapted TripPy.
Nurul Lubis adapted LAVA.
Dazhen Wan contributed to user simulators and SC-GPT.
Xiaochen Zhu contributed to the RL toolkit and SC-GPT.
Experiments of each model were performed by the corresponding author.
\paragraph{Paper writing}
Qi Zhu, Christian Geishauser, Hsien-chin Lin, and Carel van Niekerk finished most part of the paper. Baolin Peng and Zheng Zhang added the necessary details.
Michael Heck, Nurul Lubis, and Jianfeng Gao proofread and polished the paper.
\section*{Acknowledgements}
This work was supported by the National Key Research and Development Program of China (No. 2021ZD0113304), the National Science Foundation for Distinguished Young Scholars (with No. 62125604), the NSFC projects (Key project with No. 61936010 and regular project with No. 61876096), and sponsored by Tsinghua-Toyota Joint Research Fund.
This work was also supported by the DYMO project which has received funding from the European Research Council (ERC) provided under the Horizon 2020 research and innovation programme (Grant agreement No. STG2018 804636). In addition, it was supported by an Alexander von Humboldt Sofja Kovalevskaja Award endowed by the German Federal Ministry of Education and Research. Computational infrastructure and support were provided by the Centre for Information and Media Technology at Heinrich Heine University Düsseldorf and the Google Cloud Platform.
| {'timestamp': '2022-12-01T02:19:07', 'yymm': '2211', 'arxiv_id': '2211.17148', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17148'} | arxiv |
\section{Introduction}\label{chap:intro}
The ability to determine upper bounds for the number of execution steps of a program in compilation time is a relevant problem, since it allows us to know in advance the computational resources needed to run the program.
Type systems are a powerful and successful tool of static program analysis that are used, for example, to detect errors in programs before running them. Quantitative type systems, besides helping on the detection of errors, can also provide quantitative information related to computational properties.
Intersection types, defined by the grammar $\sigma \Coloneqq \alpha \mid \sigma_1 \cap \cdots \cap \sigma_n \rightarrow \sigma$ (where $\alpha$ is a type variable and $n \geq 1$), are used in several type systems for the $\lambda$-calculus \cite{coppo1980extension, DBLP:conf/mfcs/Coppo80, jim1995rank, DBLP:journals/fuin/Bakel96} and allow $\lambda$-terms to have more than one type.
Non-idempotent intersection types \cite{Gardner94, Kfoury2000, Carvalho07, BucciarelliKV17}, also known as \emph{quantitative types}, are a flavour of intersection types in which the type constructor $\cap$ is non-idempotent, and provide more than just qualitative information about programs. They are particularly useful in contexts where we are interested in measuring the use of resources, as they are related to the consumption of time and space in programs.
Type systems based on non-idempotent intersection types, use non-idempotence to count the number of evaluation steps and the size of the result. For instance, in \cite{accattoli2018tight}, the authors define several quantitative type systems, corresponding to different evaluation strategies, for which they are able to measure the number of steps taken by that strategy to reduce a term to its normal form, and the size of the term's normal form.
Typability is undecidable for intersection type systems. One way to get around this is to restrict intersection types to finite ranks, a notion defined by Daniel Leivant in \cite{leivant1983polymorphic} that makes typability decidable - Kfoury and Wells \cite{KfouryW99} define an intersection type system that, when restricted to any finite-rank, has principal typings and decidable type inference. Type systems that use finite-rank intersection types are still very powerful and useful. For instance, rank~2 intersection type systems \cite{jim1995rank, van1993intersection, damiani2007rank} are more powerful, in the sense that they can type strictly more terms, than popular systems like the ML type system \cite{damasmilner}.
In this paper we present a new definition of rank for the quantitative types, which we call \emph{linear rank} and differs from the classical one in the base case -- instead of simple types, linear rank~$0$ intersection types are the linear types. In a non-idempotent intersection type system, every linear term is typable with a simple type (in fact, in many of those systems, only the linear terms are), which is the motivation to use linear types for the base case. The relation between non-idempotent intersection types and linearity has already been studied by Kfoury \cite{Kfoury2000}, de Carvalho \cite{Carvalho07}, Gardner \cite{Gardner94} and Florido and Damas \cite{FloridoD04}.
Our motivation to redefine rank in the first place, has to do with our interest in using non-idempotent intersection types to estimate the number of evaluation steps of a $\lambda$-term to normal form while inferring its type, and the realization that there is a way to define rank that is more suitable for the quantitative types.
We define a new intersection type system for the $\lambda$-calculus, restricted to linear rank~2 non-idempotent intersection types, and a new type inference algorithm that we prove to be sound and complete with respect to the type system.
Finally we extend our type system and inference algorithm to use the quantitative properties of the linear rank~2 non-idempotent intersection types to infer not only the type of a $\lambda$-term, but also the number of evaluation steps of the term to its normal form.
The new type system is the result of a merge between our Linear Rank~2 Intersection Type System and the system for the leftmost-outermost evaluation strategy presented in \cite{accattoli2018tight}. The type system in~\cite{accattoli2018tight} is a quantitative typing system extended with the notion of tight types that provides an effective characterisation of minimal typings, which is crucial to extract exact bounds for reduction. We prove that the system gives the correct number of evaluation steps for a kind of derivation.
As for the new type inference algorithm, we show that it is sound and complete with respect to the type system for the inferred types, and conjecture that the inferred measures correspond to the ones given by the type system (i.e., correspond to the number of evaluation steps of the term to its normal form, when using the leftmost-outermost evaluation strategy).
Thus, the main contributions of this paper are the following:
\begin{itemize}
\item A new definition of rank for non-idempotent intersection types, which we call \emph{linear rank} (\autoref{chap:linearrank});
\item A Linear Rank~2 Intersection Type System for the $\lambda$-calculus (\autoref{chap:linearrank});
\item A type inference algorithm that is sound and complete with respect to the Linear Rank~2 Intersection Type System (\autoref{chap:linearrank});
\item A Linear Rank~2 Quantitative Type System for the $\lambda$-calculus that derives a measure related to the number of evaluation steps for the leftmost-outermost strategy (\autoref{chap:resource});
\item A type inference algorithm that is sound and complete with respect to the Linear Rank~2 Quantitative Type System, for the inferred types, and gives a measure that we conjecture to correspond to the number of evaluation steps of the typed term for the leftmost-outermost strategy (\autoref{chap:resource}).
\end{itemize}
In this paper we assume that the reader is familiar with the $\lambda$-calculus \cite{Barendregt85}.
From now on, in the rest of the paper, terms of the $\lambda$-calculus are considered module $\alpha$-equivalence and we assume that in a term $M$ no variable is bound more than once and no variable occurs both free and bound in $M$.
\section{Intersection Types}\label{chap:background}
The simply typed $\lambda$-calculus is a typed interpretation of the $\lambda$-calculus, introduced by Alonzo Church in \cite{church1940simple} and by Haskell Curry and Robert Feys in \cite{curry1958combinatory}. One system that uses simple types is the Curry Type System, which was first introduced in \cite{curry1934functionality} for the theory of combinators, and then modified for the $\lambda$-calculus in \cite{curry1958combinatory}. Typability in this system is decidable and there is an algorithm that given a term, returns its principal pair. However, the system presents some disadvantages when comparing to others, one of them being the large number of terms that cannot be typed. For example, in the Curry Type System we cannot assign a type to the $\lambda$-term $\lambda x.x x$. This term, on the other hand, can be typed in systems that use intersection types, which allow terms to have more than one type. Such a system is the Coppo-Dezani Type System \cite{coppo1980extension}, which was one of the first to use intersection types, and a basis for subsequent systems.
\begin{definition}[Intersection types]\label{intertypes}
Intersection types $\sigma,\sigma_1,\sigma_2, \ldots \in \mathbb{T}$ are defined by the following grammar, where $n \geq 1$:
\begin{grammar}\centering
<$\sigma$> $\Coloneqq$ $\alpha \mid \sigma_1 \cap \cdots \cap \sigma_n \rightarrow \sigma$.
\end{grammar}
and $\sigma_1 \cap \cdots \cap \sigma_n$ is called a \emph{sequence} of types.
Note that intersections arise in different systems in different scopes. Here we follow several previous presentations where intersections are only allowed directly on the left-hand side of arrow types and sequences are non-empty \cite{coppo1980extension, DBLP:conf/mfcs/Coppo80, jim1995rank, DBLP:journals/fuin/Bakel96}.
\end{definition}
\begin{notation}
The intersection type constructor $\cap$ binds stronger than $\rightarrow$: $\alpha_1 \cap \alpha_2 \rightarrow \alpha_3$ stands for $(\alpha_1 \cap \alpha_2) \rightarrow \alpha_3$.
\end{notation}
\begin{example}
Some examples of intersection types are:
\begin{center}
$\alpha$;\\
$\alpha_1 \rightarrow \alpha_2$;\\
$\alpha_1 \cap \alpha_2 \rightarrow \alpha_3$;\\
$(\alpha_1 \cap \alpha_2 \rightarrow \alpha_3) \rightarrow \alpha_4$;\\
$\alpha_1 \cap (\alpha_1 \rightarrow \alpha_2) \rightarrow \alpha_3$.
\end{center}
\end{example}
\begin{definition}[Coppo-Dezani Type System]
In the Coppo-Dezani Type System, we say that $M$ has type $\sigma$ given the environment $\Gamma$ (where the predicates of declarations are sequences), and write
\[
\Gamma \vdash_\mathcal{CD} M:\sigma,
\]
if $\Gamma \vdash_\mathcal{CD} M:\sigma$ can be obtained from the following \emph{derivation rules}, where $1 \leq i \leq n$:
\begin{equation}\tag{Axiom}
\begin{mathprooftree}
\AxiomC{$\Gamma \cup \{x:\sigma_1 \cap \cdots \cap \sigma_n\} \vdash_\mathcal{CD} x:\sigma_i$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\rightarrow$ Intro}
\begin{mathprooftree}
\AxiomC{$\Gamma \cup \{x:\sigma_1 \cap \cdots \cap \sigma_n\} \vdash_\mathcal{CD} M:\sigma$}
\UnaryInfC{$\Gamma \vdash_\mathcal{CD} \lambda x.M:\sigma_1 \cap \cdots \cap \sigma_n \rightarrow \sigma$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\rightarrow$ Elim}
\begin{mathprooftree}
\AxiomC{$\Gamma \vdash_\mathcal{CD} M_1:\sigma_1 \cap \cdots \cap \sigma_n \rightarrow \sigma$}
\AxiomC{$\Gamma \vdash_\mathcal{CD} M_2:\sigma_1 \; \cdots \; \Gamma \vdash_\mathcal{CD} M_2:\sigma_n$}
\BinaryInfC{$\Gamma \vdash_\mathcal{CD} M_1 M_2:\sigma$}
\end{mathprooftree}
\end{equation}
\end{definition}
\begin{example} For the $\lambda$-term $\lambda x.x x$ the following derivation is obtained:
\begin{equation*}
\begin{mathprooftree}
\AxiomC{$\{x:\sigma_1 \cap (\sigma_1 \rightarrow \sigma_2)\} \vdash_\mathcal{CD} x:\sigma_1 \rightarrow \sigma_2$}
\AxiomC{$\{x:\sigma_1 \cap (\sigma_1 \rightarrow \sigma_2)\} \vdash_\mathcal{CD} x:\sigma_1$}
\BinaryInfC{$\{x:\sigma_1 \cap (\sigma_1 \rightarrow \sigma_2)\} \vdash_\mathcal{CD} x x:\sigma_2$}
\UnaryInfC{$\vdash_\mathcal{CD} \lambda x.x x:\sigma_1 \cap (\sigma_1 \rightarrow \sigma_2) \rightarrow \sigma_2$}
\end{mathprooftree}
\end{equation*}
\end{example}
This system is a true extension of the Curry Type System, allowing term variables to have more than one type in the ($\rightarrow$ Intro) derivation rule and the right-hand term to also have more than one type in the ($\rightarrow$ Elim) derivation rule.
\subsection{Finite Rank}\label{subsec:rank}
Intersection type systems, like the Coppo-Dezani Type System, characterize termination, in the sense that a $\lambda$-term is strongly-normalizable if and only if it is typable in an intersection type system. Thus, typability is undecidable for these systems.
To get around this, some current intersection type systems are restricted to types of finite rank \cite{jim1995rank, van1993intersection, KfouryW99, damiani2007rank} using a notion of rank first defined by Daniel Leivant in \cite{leivant1983polymorphic}. This restriction makes typability decidable \cite{KfouryW99}. Despite using finite-rank intersection types, these systems are still very powerful and useful. For instance, rank~2 intersection type systems \cite{jim1995rank, van1993intersection, damiani2007rank} are more powerful, in the sense that they can type strictly more terms, than popular systems like the ML type system \cite{damasmilner}.
The \emph{rank} of an intersection type is related to the depth of the nested intersections and it can be easily determined by examining the type in tree form: a type is of rank~$k$ if no path from the root of the type to an intersection type constructor $\cap$ passes to the left of $k$ arrows.
\begin{example}
The intersection type $\alpha_1 \cap (\alpha_1 \rightarrow \alpha_2) \rightarrow \alpha_2$ (tree on the left) is a rank~2 type and $(\alpha_1 \cap \alpha_2 \rightarrow \alpha_3) \rightarrow \alpha_4$ (tree on the right) is a rank~3 type:
\forestset{
sn edges/.style={for tree={parent anchor=south, child anchor=north, s sep=2mm}},
azulciencias subtree/.style={for tree={text=azulciencias},for descendants={edge=azulciencias}}
}
\begin{center}
\begin{forest}
sn edges
[$\rightarrow$, s sep=11mm, draw=azulciencias
[$\cap$, s sep=5mm, edge=azulciencias, draw=azulciencias
[$\alpha_1$]
[$\rightarrow$
[$\alpha_1$]
[$\alpha_2$]
]
]
[$\alpha_2$]
]
\end{forest}
\qquad\qquad\qquad\qquad\quad
\begin{forest}
sn edges
[$\rightarrow$, s sep=8mm, draw=azulciencias
[$\rightarrow$, s sep=5mm, edge=azulciencias, draw=azulciencias
[$\cap$, edge=azulciencias, draw=azulciencias
[$\alpha_1$]
[$\alpha_2$]
]
[$\alpha_3$]
]
[$\alpha_4$]
]
\end{forest}
\end{center}
\end{example}
\begin{definition}[Rank of intersection types]\label{rank}
Let $\mathbb{T}_0$ be the set of simple types and $\mathbb{T}_1 = \{ \tau_1 \cap \dots \cap \tau_m \mid \tau_1, \dots, \tau_m \in \mathbb{T}_0, m \geq 1 \}$ the set of sequences of simple types (written as $\vec{\tau},\vec{\tau}_1,\vec{\tau}_2, \ldots$). The set $\mathbb{T}_k$, of rank $k$ intersection types (for $k \geq 2$), can be defined recursively in the following way ($n \geq 3$, $m \geq 1$):
\begin{alignat*}{3}
&\mathbb{T}_2 &&= &&\; \mathbb{T}_{0}
\cup \{ \vec{\tau} \rightarrow \sigma \mid \vec{\tau} \in \mathbb{T}_{1}, \sigma \in \mathbb{T}_2 \}\\
&\mathbb{T}_n &&= &&\; \mathbb{T}_{n-1}
\cup \{ \vec{\tau}_1 \cap \dots \cap \vec{\tau}_m \rightarrow \sigma \mid \vec{\tau}_1, \dots, \vec{\tau}_m \in \mathbb{T}_{n-1}, \sigma \in \mathbb{T}_n \}
\end{alignat*}
\end{definition}
\begin{notation}
We consider the intersection type constructor $\cap$ to be associative, commutative and non-idempotent (meaning that $\alpha \cap \alpha$ is not equivalent to $\alpha$).
\end{notation}
We are particularly interested in non-idempotent intersection types, also known as quantitative types, because they provide more quantitative information than the idempotent ones.
\section{Linear Rank Intersection Types}\label{chap:linearrank}
In the previous chapter, we mentioned several intersection type systems in which intersection is idempotent and types are rank-restricted. There are also many quantitative type systems \cite{Gardner94, Kfoury2000, Carvalho07, BucciarelliKV17} that, on the other hand, make use of non-idempotent intersection types, for which there is no specific definition of rank.
The generalization of ranking for non-idempotent intersection types is not trivial and raises interesting questions that we will address in this chapter, along with a definition of a new non-idempotent intersection type system and a type inference algorithm.
This and the following sections cover original work that we presented at the TYPES~2022 conference \cite{typesabstract}.
\subsection{Linear Rank}\label{sec:linearrank}
The set of terms typed using idempotent rank~2 intersection types and non-idempotent rank~2 intersection types is not the same. For instance, the term $(\lambda x.x x) (\lambda f x. f (f x))$ is typable with a simple type when using idempotent intersection types, but not when using non-idempotent intersection types. This comes from the two different occurrences of $f$ in $\lambda f x. f (f x)$, which even if typed with the same type, are not contractible because intersection is non-idempotent. Note that this is strongly related to the linearity features of terms. A $\lambda$-term $M$ is called a \emph{linear term} if and only if, for each subterm of the form $\lambda x.N$ in $M$, $x$ occurs free in $N$ exactly once, and if each free variable of $M$ has just one occurrence free in $M$. So the term $(\lambda x.x x) (\lambda f x. f (f x))$ is not typable with a non-idempotent rank~2 intersection type precisely because the term $\lambda f x. f (f x)$ is not linear.
Note that in a non-idempotent intersection type system, every linear term is typable with a simple type (in fact, in many of those systems, only the linear terms are). This motivated us to come up with a new notion of rank for non-idempotent intersection types, based on linear types (the ones derived in a linear type system -- a substructural type system in which each assumption must be used exactly once, corresponding to the implicational fragment of linear logic \cite{Girard87}).
The relation between non-idempotent intersection types and linearity was first introduced by Kfoury \cite{Kfoury2000} and further explored by de Carvalho \cite{Carvalho07}, who established its relation with linear logic.
Here we propose a new definition of rank for intersection types, which we call \emph{linear rank} and differs from the classical one in the base case -- instead of simple types, linear rank~$0$ intersection types are the linear types -- and in the introduction of the functional type constructor `linear arrow' $\multimap$.
\begin{definition}[Linear rank of intersection types]\label{linearrank}
Let $\tl{0} = \mathbb{V} \cup \{ \tau_1 \multimap \tau_2 \mid \tau_1, \tau_2 \in \tl{0} \}$ be the set of {\color{azulciencias} linear types} and $\tl{1} = \{ \tau_1 \cap \dots \cap \tau_m \mid \tau_1, \dots, \tau_m \in \tl{0}, m \geq 1 \}$ the set of sequences of linear types. The set $\tl{k}$, of \emph{linear rank}~$k$ intersection types (for $k \geq 2$), can be defined recursively in the following way ($n \geq 3$, $m \geq 2$):
\begin{alignat*}{3}
&\tl{2} &&= &&\; \tl{0}
\cup \{ \tau \multimap \sigma \mid \tau \in \tl{0}, \sigma \in \tl{2} \}\\
& && &&\; \cup \{ \tau_1 \cap \dots \cap \tau_m \rightarrow \sigma \mid \tau_1, \dots, \tau_m \in \tl{0}, \sigma \in \tl{2} \}\\
&\tl{n} &&= &&\; \tl{n-1}
\cup \{ \vec{\tau} \multimap \sigma \mid \vec{\tau} \in \tl{n-1}, \sigma \in \tl{n} \}\\
& && &&\; \cup \{ \vec{\tau}_1 \cap \dots \cap \vec{\tau}_m \rightarrow \sigma \mid \vec{\tau}_1, \dots, \vec{\tau}_m \in \tl{n-1}, \sigma \in \tl{n} \}
\end{alignat*}
\end{definition}
Initially, the idea for the change arose from our interest in using rank-restricted intersection types to estimate the number of evaluation steps of a $\lambda$-term while inferring its type. While defining the intersection type system to obtain quantitative information, we realized that the ranks could be potentially more useful for that purpose if the base case was changed to types that give more quantitative information in comparison to simple types, which is the case for linear types -- for instance, if a term is typed with a linear rank~2 intersection type, one knows that its arguments are linear, meaning that they will be used exactly once.
It is not clear, and most likely non-trivial, the relation between the standard definition of rank and our definition of linear rank. Note that the set of terms typed using standard rank~2 intersection types \cite{jim1995rank, van1993intersection} and linear rank~2 intersection types is not the same. For instance, again, the term $(\lambda x.x x) (\lambda f x. f (f x))$, typable with a simple type in the standard Rank~2 Intersection Type System, is not typable in the Linear Rank~2 Intersection Type System, because, as the term $(\lambda f x. f (f x))$ is not linear and intersection is not idempotent, by \autoref{linearrank}, the type of $(\lambda x.x x) (\lambda f x. f (f x))$ is now (linear) rank~3. This relation between rank and linear rank is an interesting question that will not be covered here, but one that we would like to explore in the future.
\subsection{Type System}\label{sec:typesystem}
We now define a new type system for the $\lambda$-calculus with linear rank~2 non-idempotent intersection types.
\begin{definition}[Substitution]
We call \emph{substitution} to
\[
\mathcal{S} = \subst{N/x}.
\]
$\mathcal{S}(M) = \sub{M}{N/x}$ is the result of substituting the term $N$ for each free occurrence of $x$ in the term $M$ and can be inductively defined as follows:
\begin{align*}
\sub{x}{N/x} &= N;\\
\sub{x_1}{N/x_2} &= x_1, \text{ if } x_1 \neq x_2;\\
\sub{(M_1 M_2)}{N/x} &= (\sub{M_1}{N/x}) (\sub{M_2}{N/x});\\
\sub{(\lambda x.M)}{N/x} &= \lambda x.M;\\
\sub{(\lambda x_1.M)}{N/x_2} &= \lambda x_1.(\sub{M}{N/x_2}), \text{ if } x_1 \neq x_2.
\end{align*}
\end{definition}
\begin{notation}
We write $\sub{M}{M_1/x_1, M_2/x_2, \dots, M_n/x_n}$ for $\sub{(\dots (\sub{(\sub{M}{M_1/x_1})}{M_2/x_2}) \dots)}{M_n/x_n}$.
\end{notation}
Composing two substitutions $\mathcal{S}_1$ and $\mathcal{S}_2$ results in a substitution $\mathcal{S}_2 \circ \mathcal{S}_1$ that when applied, has the same effect as applying $\mathcal{S}_1$ followed by $\mathcal{S}_2$.
\begin{definition}[Substitution composition]
The \emph{composition} of two substitutions $\mathcal{S}_1 = \subst{N_1/x_1}$ and $\mathcal{S}_2 = \subst{N_2/x_2}$, denoted by $\mathcal{S}_2 \circ \mathcal{S}_1$, is defined as:
\[
\mathcal{S}_2 \circ \mathcal{S}_1 (M) = \sub{M}{N_1/x_1, N_2/x_2}.
\]
Also, we assume that the operation is right-associative:
\[
\mathcal{S}_1 \circ \mathcal{S}_2 \circ \cdots \circ \mathcal{S}_{n-1} \circ \mathcal{S}_n = \mathcal{S}_1 \circ (\mathcal{S}_2 \circ \cdots \circ (\mathcal{S}_{n-1} \circ \mathcal{S}_n) \dots).
\]
\end{definition}
\begin{notation}
From now on, we will use $\alpha$ to range over a countable infinite set $\mathbb{V}$ of type variables, $\tau$ to range over the set $\tl{0}$ of linear types, $\vec{\tau}$ to range over the set $\tl{1}$ of linear type sequences and $\sigma$ to range over the set $\tl{2}$ of linear rank~2 intersection types. In all cases, we may use or not single quotes and/or number subscripts.
\end{notation}
\begin{convention}
We consider types equal up to renaming of variables.
\end{convention}
\begin{definition}
~\begin{itemize}
\item A \emph{statement} is an expression of the form $M:\vec{\tau}$, where $\vec{\tau}$ is called the \emph{predicate}, and the term $M$ is called the \emph{subject} of the statement.
\item A \emph{declaration} is a statement where the subject is a term variable.
\item The comma operator (,) appends a declaration to the end of a list (of declarations). The list $(\Gamma_1, \Gamma_2)$ is the list that results from appending the list $\Gamma_2$ to the end of the list $\Gamma_1$.
\item A finite list of declarations is \emph{consistent} if and only if the term variables are all distinct.
\item We call \emph{environment} to a consistent finite list of declarations which predicates are sequences of linear types (i.e., elements of $\tl{1}$) and we use $\Gamma$ (possibly with single quotes and/or number subscripts) to range over environments.
\item If $\Gamma = [x_1:\vec{\tau}_1, \dots, x_n:\vec{\tau}_n]$ is an environment, then $\Gamma$ is a partial function, with domain $\mathsf{dom}(\Gamma) = \{x_1, \dots, x_n\}$, and $\Gamma(x_i) = \vec{\tau}_i$.
\item We write $\Gamma_x$ for the resulting environment of eliminating the declaration of $x$ from $\Gamma$ (if there is no declaration of $x$ in $\Gamma$, then $\Gamma_x = \Gamma$).
\item We write $\Gamma_1 \equiv \Gamma_2$ if the environments $\Gamma_1$ and $\Gamma_2$ are equal up to the order of the declarations.
\item If $\Gamma_1$ and $\Gamma_2$ are environments, the environment $\Gamma_1 + \Gamma_2$ is defined as follows:
for each $x \in \mathsf{dom}(\Gamma_1) \cup \mathsf{dom}(\Gamma_2)$,
\[
(\Gamma_1 + \Gamma_2)(x) = \left\{
\begin{array}{ll}
\Gamma_1(x) &\text{if } x \notin \mathsf{dom}(\Gamma_2)\\
\Gamma_2(x) &\text{if } x \notin \mathsf{dom}(\Gamma_1)\\
\Gamma_1(x) \cap \Gamma_2(x) &\text{otherwise}
\end{array}
\right.
\]
with the declarations of the variables in $\mathsf{dom}(\Gamma_1)$ in the beginning of the list, by the same order they appear in $\Gamma_1$, followed by the declarations of the variables in $\mathsf{dom}(\Gamma_2) \setminus \mathsf{dom}(\Gamma_1)$, by the order they appear in $\Gamma_2$.
\end{itemize}
\end{definition}
\begin{definition}[Linear Rank~2 Intersection Type System]\label{lineartypesystem}
In the Linear Rank~2 Intersection Type System, we say that $M$ has type $\sigma$ given the environment $\Gamma$, and write
\[
\inftwo{\Gamma}{M}{\sigma}
\]
if it can be obtained from the following \emph{derivation rules}:
\begin{equation}\tag{Axiom}
\begin{mathprooftree}
\AxiomC{$\inftwo{ [x:\tau] }{ x }{ \tau }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{Exchange}
\begin{mathprooftree}
\AxiomC{$\inftwo{ \Gamma_1, x:\vec{\tau}_1, y:\vec{\tau}_2, \Gamma_2 }{ M }{ \sigma }$}
\UnaryInfC{$\inftwo{ \Gamma_1, y:\vec{\tau}_2, x:\vec{\tau}_1, \Gamma_2 }{ M }{ \sigma }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{Contraction}
\begin{mathprooftree}
\AxiomC{$\inftwo{ \Gamma_1, x_1:\vec{\tau}_1, x_2:\vec{\tau}_2, \Gamma_2 }{ M }{ \sigma }$}
\UnaryInfC{$\inftwo{ \Gamma_1, x:\vec{\tau}_1 \cap \vec{\tau}_2, \Gamma_2 }{ \sub{M}{x/x_1, x/x_2} }{ \sigma }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\rightarrow$ Intro}
\begin{mathprooftree}
\AxiomC{$\inftwo{ \Gamma, x:\tau_1 \cap \cdots \cap \tau_n }{ M }{ \sigma }$}
\AxiomC{$n \geq 2$}
\BinaryInfC{$\inftwo{ \Gamma }{ \lambda x.M }{ \tau_1 \cap \cdots \cap \tau_n \rightarrow \sigma}$}
\end{mathprooftree}
\end{equation}
\begin{Dequation}
\begin{equation}\tag{$\rightarrow$ Elim}
\begin{mathprooftree}
\AxiomC{$\inftwo{ \Gamma }{ M_1 }{ \tau_1 \cap \cdots \cap \tau_n \rightarrow \sigma }$}
\AxiomC{$\inftwo{ \Gamma_1 }{ M_2 }{ \tau_1 } \; \cdots \; \inftwo{ \Gamma_n }{ M_2 }{ \tau_n }$}
\AxiomC{$n \geq 2$}
\TrinaryInfC{$\inftwo{ \Gamma, \sum_{i=1}^n \Gamma_i }{ M_1 M_2 }{ \sigma }$}
\end{mathprooftree}
\end{equation}
\end{Dequation}
\begin{equation}\tag{$\multimap$ Intro}
\begin{mathprooftree}
\AxiomC{$\inftwo{ \Gamma, x:\tau }{ M }{ \sigma }$}
\UnaryInfC{$\inftwo{ \Gamma }{ \lambda x.M }{ \tau \multimap \sigma }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\multimap$ Elim}
\begin{mathprooftree}
\AxiomC{$\inftwo{ \Gamma_1 }{ M_1 }{ \tau \multimap \sigma }$}
\AxiomC{$\inftwo{ \Gamma_2 }{ M_2 }{ \tau }$}
\BinaryInfC{$\inftwo{ \Gamma_1, \Gamma_2 }{ M_1 M_2 }{ \sigma }$}
\end{mathprooftree}
\end{equation}
\end{definition}
\begin{example}
Let us write $\overmultimap{\alpha}$ for the type $(\alpha \multimap \alpha)$. For the $\lambda$-term $(\lambda x.x x)(\lambda y.y)$, the following derivation is obtained:
\scalebox{0.92}{
\begin{mathprooftree}
\AxiomC{$\inftwo{ [x_1: \; \overmultimap{\alpha} \multimap \overmultimap{\alpha}] }{ x_1 }{ \; \overmultimap{\alpha} \multimap \overmultimap{\alpha} }$}
\AxiomC{$\inftwo{ [x_2:\; \overmultimap{\alpha}] }{ x_2 }{ \; \overmultimap{\alpha} }$}
\BinaryInfC{$\inftwo{ [x_1:\; \overmultimap{\alpha} \multimap \overmultimap{\alpha}, x_2:\; \overmultimap{\alpha}] }{ x_1 x_2 }{ \; \overmultimap{\alpha} }$}
\UnaryInfC{$\inftwo{ [x:(\overmultimap{\alpha} \multimap \overmultimap{\alpha}) \; \cap \overmultimap{\alpha}] }{ x x }{ \; \overmultimap{\alpha} }$}
\UnaryInfC{$\inftwo{ [\;] }{ \lambda x.x x }{ (\overmultimap{\alpha} \multimap \overmultimap{\alpha}) \; \cap \overmultimap{\alpha} \rightarrow \overmultimap{\alpha} }$}
\AxiomC{$\inftwo{ [y:\; \overmultimap{\alpha}] }{ y }{ \; \overmultimap{\alpha} }$}
\UnaryInfC{$\inftwo{ [\;] }{ \lambda y.y }{ \; \overmultimap{\alpha} \multimap \overmultimap{\alpha} }$}
\AxiomC{$\inftwo{ [y:\alpha] }{ y }{ \alpha }$}
\UnaryInfC{$\inftwo{ [\;] }{ \lambda y.y }{ \; \overmultimap{\alpha} }$}
\TrinaryInfC{$\inftwo{ [\;] }{ (\lambda x.x x)(\lambda y.y) }{ \; \overmultimap{\alpha} }$}
\end{mathprooftree}
}
\end{example}
\subsection{Type Inference Algorithm}\label{sec:inference}
In this section we define a new type inference algorithm for the $\lambda$-calculus (\autoref{ti2}), which is sound (\autoref{soundness}) and complete (\autoref{completeness}) with respect to the Linear Rank~2 Intersection Type System.
Our algorithm is based on Trevor Jim's type inference algorithm \cite{jim1995rank} for a Rank~2 Intersection Type System that was introduced by Daniel Leivant in \cite{leivant1983polymorphic}, where the algorithm was briefly covered. Different versions of the algorithm were later defined by Steffen van Bakel in \cite{van1993intersection} and by Trevor Jim in \cite{jim1995rank}.
Part of the definitions, properties and proofs here presented are also adapted from \cite{jim1995rank}.
\begin{definition}[Type-substitution]
We call \emph{type-substitution} to
\[
\mathbb{S} = \tsubst{\tau_1/\alpha_1, \dots, \tau_n/\alpha_n}
\]
where $\alpha_1,\dots,\alpha_n$ are distinct type variables in $\mathbb{V}$ and $\tau_1,\dots,\tau_n$ are types in $\tl{0}$. For any $\tau$ in $\tl{0}$, $\mathbb{S}(\tau) = \tsub{\tau}{\tau_1/\alpha_1, \dots, \tau_n/\alpha_n}$ is the type obtained by simultaneously substituting $\alpha_i$ by $\tau_i$ in $\tau$, with $1 \leq i \leq n$.
The type $\mathbb{S}(\tau)$ is called an \emph{instance} of the type $\tau$.
The notion of type-substitution can be extended to environments in the following way:
\[
\mathbb{S}(\Gamma) = [x_1:\mathbb{S}(\vec{\tau}_1),\dots,x_n:\mathbb{S}(\vec{\tau}_n)] \qquad \text{if } \Gamma = [x_1:\vec{\tau}_1,\dots,x_n:\vec{\tau}_n]
\]
The environment $\mathbb{S}(\Gamma)$ is called an \emph{instance} of the environment $\Gamma$.
If $\mathbb{S}_1 = \tsubst{\tau_1/\alpha_1, \dots, \tau_n/\alpha_n}$ and $\mathbb{S}_2 = \tsubst{\tau_1'/\alpha_1', \dots, \tau_n'/\alpha_n'}$ are type-substitutions such that the variables $\alpha_1, \dots, \alpha_n, \alpha_1', \dots, \alpha_n'$ are all distinct, then the type-substitution $\mathbb{S}_1 \cup \mathbb{S}_2$ is defined as $\mathbb{S}_1 \cup \mathbb{S}_2 = \tsubst{\tau_1/\alpha_1, \dots, \tau_n/\alpha_n, \tau_1'/\alpha_1', \dots, \tau_n'/\alpha_n'}$.
\end{definition}
Composing two type-substitutions $\mathbb{S}_1$ and $\mathbb{S}_2$ results in a type-substitution $\mathbb{S}_2 \circ \mathbb{S}_1$ that when applied, has the same effect as applying $\mathbb{S}_1$ followed by $\mathbb{S}_2$.
\begin{definition}[Type-substitution composition]
The \emph{composition} of two type-substitutions $\mathbb{S}_1 = \tsubst{\tau_1/\alpha_1, \dots, \tau_n/\alpha_n}$ and $\mathbb{S}_2 = \tsubst{\tau_1'/\alpha_1', \dots, \tau_m'/\alpha_m'}$, denoted by $\mathbb{S}_2 \circ \mathbb{S}_1$, is defined as:
\[
\mathbb{S}_2 \circ \mathbb{S}_1 = \tsubst{\tau_{i_1}'/\alpha_{i_1}', \dots, \tau_{i_k}'/\alpha_{i_k}', \mathbb{S}_2(\tau_1)/\alpha_1, \dots, \mathbb{S}_2(\tau_n)/\alpha_n},
\]
where $\{\alpha_{i_1}', \dots, \alpha_{i_k}'\} = \{\alpha_1', \dots, \alpha_m'\} \setminus \{\alpha_1, \dots, \alpha_n\}$.
Also, we assume that the operation is right-associative:
\[
\mathbb{S}_1 \circ \mathbb{S}_2 \circ \cdots \circ \mathbb{S}_{n-1} \circ \mathbb{S}_n = \mathbb{S}_1 \circ (\mathbb{S}_2 \circ \cdots \circ (\mathbb{S}_{n-1} \circ \mathbb{S}_n) \dots).
\]
\end{definition}
\subsubsection{Unification}\label{subsec:unification}
\begin{definition} [Unification problem]
A \emph{unification problem} is a finite set of equations $P = \{\tau_1 = \tau_1', \dots, \tau_n=\tau_n'\}$.
A \emph{unifier} (or \emph{solution}) is a substitution $\mathbb{S}$, such that $\mathbb{S}(\tau_i) = \mathbb{S}(\tau_i')$, for $1 \leq i \leq n$.
We call $\mathbb{S}(\tau_i)$ (or $\mathbb{S}(\tau_i')$) a \emph{common instance} of $\tau_i$ and $\tau_i'$.
$P$ is \emph{unifiable} if it has at least one unifier. $\mathcal{U}(P)$ is the set of unifiers of $P$.
\end{definition}
\begin{example}
The types $\alpha_1 \multimap \alpha_2 \multimap \alpha_1$ and $(\alpha_3 \multimap \alpha_3) \multimap \alpha_4$ are \emph{unifiable}. For the type-substitution $\mathbb{S} = \tsubst{(\alpha_3 \multimap \alpha_3)/\alpha_1, (\alpha_2 \multimap (\alpha_3 \multimap \alpha_3))/\alpha_4}$, the \emph{common instance} is $(\alpha_3 \multimap \alpha_3) \multimap \alpha_2 \multimap (\alpha_3 \multimap \alpha_3)$.
\end{example}
\begin{definition} [Most general unifier]\label{mgu}
A substitution $\mathbb{S}$ is a \emph{most general unifier} (MGU) of $P$ if $\mathbb{S}$ is a least element of $\mathcal{U}(P)$. That is,
\[
\mathbb{S} \in \mathcal{U}(P) \text{ and } \forall \mathbb{S}_1 \in \mathcal{U}(P) \ldotp \exists \mathbb{S}_2 \ldotp \mathbb{S}_1 = \mathbb{S}_2 \circ \mathbb{S}.
\]
\end{definition}
\begin{example}\label{eg:mgu}
Consider the types $\tau_1 = (\alpha_1 \multimap \alpha_1)$ and $\tau_2 = (\alpha_2 \multimap \alpha_3)$.
The type-substitution $\mathbb{S}' = \tsubst{(\alpha_4 \multimap \alpha_5)/\alpha_1, (\alpha_4 \multimap \alpha_5)/\alpha_2, (\alpha_4 \multimap \alpha_5)/\alpha_3}$ is a unifier of $\tau_1$ and $\tau_2$, but it is not the MGU.
The MGU of $\tau_1$ and $\tau_2$ is $\mathbb{S} = \tsubst{\alpha_3/\alpha_1, \alpha_3/\alpha_2}$. The common instance of $\tau_1$ and $\tau_2$ by $\mathbb{S}'$, $(\alpha_4 \multimap \alpha_5) \multimap (\alpha_4 \multimap \alpha_5)$, is an instance of $(\alpha_3 \multimap \alpha_3)$, the common instance by $\mathbb{S}$.
\end{example}
\begin{definition}[Solved form]
A unification problem $P = \{\alpha_1=\tau_1,\dots,\alpha_n=\tau_n\}$ is in \emph{solved form} if $\alpha_1,\dots,\alpha_n$ are all pairwise distinct variables that do not occur in any of the $\tau_i$. In this case, we define $\mathbb{S}_P = \tsubst{\tau_1/\alpha_1,\dots,\tau_n/\alpha_n}$.
\end{definition}
\begin{definition}[Type unification]\label{transformuni}
We define the following relation $\Rightarrow$ on type unification problems (for types in $\tl{0}$):
\begin{alignat*}{3}
&\{\tau = \tau\} \cup P \quad && \Rightarrow \quad P &&\\
&\{\tau_1 \multimap \tau_2 = \tau_3 \multimap \tau_4\} \cup P \quad && \Rightarrow \quad \{\tau_1 = \tau_3, \tau_2 = \tau_4\} \cup P &&\\
&\{\tau_1 \multimap \tau_2 = \alpha\} \cup P \quad && \Rightarrow \quad \{\alpha = \tau_1 \multimap \tau_2\} \cup P &&\\
&\{\alpha = \tau\} \cup P \quad && \Rightarrow \quad \{\alpha = \tau\} \cup \tsub{P}{\tau/\alpha} &&\quad \text{if } \alpha \in \msf{fv}(P) \setminus \msf{fv}(\tau)\\
&\{\alpha = \tau\} \cup P \quad && \Rightarrow \quad \msf{FAIL} &&\quad \text{if } \alpha \in \msf{fv}(\tau) \text{ and } \alpha \neq \tau
\end{alignat*}
where $\tsub{P}{\tau/\alpha}$ corresponds to the notion of type-substitution extended to type unification problems. If $P = \{\tau_1 = \tau_1', \dots, \tau_n=\tau_n'\}$, then $\tsub{P}{\tau/\alpha} = \{\tsub{\tau_1}{\tau/\alpha} = \tsub{\tau_1'}{\tau/\alpha}, \dots, \tsub{\tau_n}{\tau/\alpha} = \tsub{\tau_n'}{\tau/\alpha}\}$.
And $ \msf{fv}(P)$ and $ \msf{fv}(\tau)$ are the sets of free type variables in $P$ and $\tau$, respectively. Since in our system all occurrences of type variables are free, $ \msf{fv}(P)$ and $ \msf{fv}(\tau)$ are the sets of type variables in $P$ and $\tau$, respectively.
\end{definition}
\begin{definition}[Unification algorithm]\label{unify}
Let $P$ be a unification problem (with types in $\tl{0}$). The unification function $\msf{UNIFY}(P)$ that decides whether $P$ has a solution and, if so, returns the MGU of $P$ (see \cite{robinson1965machine}), is defined as:
\begin{algorithmic}
\Function{$\msf{UNIFY}$}{$P$}
\While{$P \Rightarrow P'$}
\State $P \coloneqq P'$;
\EndWhile
\If{$P$ is in solved form}
\State \Return $\mathbb{S}_P$;
\Else
\State $\msf{FAIL}$;
\EndIf
\EndFunction
\end{algorithmic}
\end{definition}
\begin{example}\label{eg:unify}
Consider again the types $\alpha_1 \multimap \alpha_1$ and $\alpha_2 \multimap \alpha_3$ in \autoref{eg:mgu}. For the unification problem $P = \{ \alpha_1 \multimap \alpha_1 = \alpha_2 \multimap \alpha_3 \}$, $\msf{UNIFY}(P)$ performs the following transformations over $P$:
\begin{align*}
\{ \alpha_1 \multimap \alpha_1 = \alpha_2 \multimap \alpha_3 \}
&\Rightarrow \{ \alpha_1 = \alpha_2, \alpha_1 = \alpha_3 \} \cup \{\;\} &=&& \{ \alpha_1 = \alpha_2, \alpha_1 = \alpha_3 \}\\
&\Rightarrow \{ \alpha_1 = \alpha_2\} \cup \tsub{\{\alpha_1 = \alpha_3\}}{\alpha_2/\alpha_1} &=&& \{ \alpha_1 = \alpha_2, \alpha_2 = \alpha_3 \}\\
&\Rightarrow \{ \alpha_2 = \alpha_3\} \cup \tsub{\{\alpha_1 = \alpha_2\}}{\alpha_3/\alpha_2} &=&& \{ \alpha_1 = \alpha_3, \alpha_2 = \alpha_3 \}
\end{align*}
and, since $\{ \alpha_1 = \alpha_3, \alpha_2 = \alpha_3 \}$ is in solved form, it returns the type-substitution $\tsubst{\alpha_3/\alpha_1, \alpha_3/\alpha_2}$.
\end{example}
\subsubsection{Type Inference}\label{subsec:inference}
\begin{definition}[Type inference algorithm]\label{ti2}
Let $\Gamma$ be an environment, $M$ a $\lambda$-term, $\sigma$ a linear rank~2 intersection type and $\msf{UNIFY}$ the function in \autoref{unify}. The function $\msf{T}(M) = (\Gamma, \sigma)$ defines a type inference algorithm for the $\lambda$-calculus in the Linear Rank~2 Intersection Type System, in the following way:
\begin{enumerate}
\item \tul{If} $M=x$, \tul{then} $\Gamma = [x:\alpha]$ and $\sigma = \alpha$, where $\alpha$ is a new variable;
\item \tul{If} $M=\lambda x.M_1$ and $\msf{T}(M_1) = (\Gamma_1, \sigma_1)$ \tul{then}:
\begin{enumerate}
\item \tul{if} $x \notin \mathsf{dom}(\Gamma_1)$, \tul{then} $\msf{FAIL}$;
\item \tul{if} $(x:\tau) \in \Gamma_1$, \tul{then} $\msf{T}(M) = ({\Gamma_1}_x, \tau \multimap \sigma_1)$;
\item \tul{if} $(x:\tau_1 \cap \cdots \cap \tau_n) \in \Gamma_1$ (with $n \geq 2$), \tul{then} $\msf{T}(M) = ({\Gamma_1}_x, \tau_1 \cap \cdots \cap \tau_n \rightarrow \sigma_1)$.
\end{enumerate}
\item \tul{If} $M=M_1 M_2$, \tul{then}:
\begin{enumerate}
\item \tul{if} $\msf{T}(M_1) = (\Gamma_1, \alpha_1)$ and $\msf{T}(M_2) = (\Gamma_2, \tau_2)$,\\
\tul{then} $\msf{T}(M) = (\mathbb{S}(\Gamma_1 + \Gamma_2), \mathbb{S}(\alpha_3))$,\\
where $\mathbb{S} = \msf{UNIFY}(\{\alpha_1 = \alpha_2 \multimap \alpha_3, \tau_2 = \alpha_2\})$ and $\alpha_2,\alpha_3$ are new variables;
\item \tul{if} $\msf{T}(M_1) = (\Gamma_1', \tau_1' \cap \cdots \cap \tau_n' \rightarrow \sigma_1')$ (with $n \geq 2$) and, for each $1 \leq i \leq n$,\\
$\msf{T}(M_2) = (\Gamma_i, \tau_i)$,\\
\tul{then} $\msf{T}(M) = (\mathbb{S}(\Gamma_1' + \sum_{i=1}^n \Gamma_i), \mathbb{S}(\sigma_1'))$,\\
where $\mathbb{S} = \msf{UNIFY}(\{\tau_i = \tau_i' \mid 1 \leq i \leq n\})$;
\item \tul{if} $\msf{T}(M_1) = (\Gamma_1, \tau \multimap \sigma_1)$ and $\msf{T}(M_2) = (\Gamma_2, \tau_2)$,\\
\tul{then} $\msf{T}(M) = (\mathbb{S}(\Gamma_1 + \Gamma_2), \mathbb{S}(\sigma_1))$,\\
where $\mathbb{S} = \msf{UNIFY}(\{\tau_2 = \tau\})$;
\item \tul{otherwise} $\msf{FAIL}$.\\
\end{enumerate}
\end{enumerate}
\end{definition}
\begin{example}
Let us show the type inference process for the $\lambda$-term $\lambda x.x x$.
\begin{itemize}
\item By rule 1., $\msf{T}(x) = ([x:\alpha_1], \alpha_1)$.
\item By rule 1., again, $\msf{T}(x) = ([x:\alpha_2], \alpha_2)$.
\item Then by rule 3.(a), $\msf{T}(x x) = (\mathbb{S}([x:\alpha_1] + [x:\alpha_2]), \mathbb{S}(\alpha_4)) = (\mathbb{S}([x:\alpha_1 \cap \alpha_2]), \mathbb{S}(\alpha_4))$,
where $\mathbb{S} = \msf{UNIFY}(\{\alpha_1 = \alpha_3 \multimap \alpha_4, \alpha_2 = \alpha_3\}) = \tsubst{\alpha_3 \multimap \alpha_4/\alpha_1, \alpha_3/\alpha_2}$.
So $\msf{T}(x x) = ([x:(\alpha_3 \multimap \alpha_4) \cap \alpha_3], \alpha_4)$.
\item Finally, by rule 2.(c), $\msf{T}(\lambda x.x x) = ([\;], (\alpha_3 \multimap \alpha_4) \cap \alpha_3 \rightarrow \alpha_4)$.
\end{itemize}
\end{example}
\begin{example}
Let us now show the type inference process for the $\lambda$-term $(\lambda x.x x) (\lambda y.y)$.
\begin{itemize}
\item From the previous example, we have $\msf{T}(\lambda x.x x) = ([\;], (\alpha_3 \multimap \alpha_4) \cap \alpha_3 \rightarrow \alpha_4)$.
\item By rules 1. and 2.(b), for the identity, the algorithm gives $\msf{T}(\lambda y.y) = ([\;], \alpha_1 \multimap \alpha_1)$.
\item By rules 1. and 2.(b), again, for the identity, $\msf{T}(\lambda y.y) = ([\;], \alpha_2 \multimap \alpha_2)$.
\item Then by rule 3.(b), $\msf{T}((\lambda x.x x) (\lambda y.y)) = (\mathbb{S}([\;] + [\;] + [\;]), \mathbb{S}(\alpha_4)) = ([\;], \mathbb{S}(\alpha_4))$,
where $\mathbb{S} = \msf{UNIFY}(\{\alpha_1 \multimap \alpha_1 = \alpha_3 \multimap \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_3\})$, calculated by performing the following transformations:
\begin{align*}
\{ \alpha_1 \multimap \alpha_1 = \alpha_3 \multimap \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_3 \}
&\Rightarrow \{ \alpha_1 = \alpha_3, \alpha_1 = \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_3 \}\\
&\Rightarrow \{ \alpha_1 = \alpha_3, \alpha_3 = \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_3 \}\\
&\Rightarrow \{ \alpha_1 = \alpha_4, \alpha_3 = \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_4 \}\\
&\Rightarrow \{ \alpha_1 = \alpha_4, \alpha_3 = \alpha_4, \alpha_4 = \alpha_2 \multimap \alpha_2 \}\\
&\Rightarrow \{ \alpha_1 = \alpha_2 \multimap \alpha_2, \alpha_3 = \alpha_2 \multimap \alpha_2, \alpha_4 = \alpha_2 \multimap \alpha_2 \}
\end{align*}
So $\mathbb{S} = \tsubst{(\alpha_2 \multimap \alpha_2) / \alpha_1, (\alpha_2 \multimap \alpha_2) / \alpha_3, (\alpha_2 \multimap \alpha_2) / \alpha_4}$
and $\msf{T}((\lambda x.x x) (\lambda y.y)) = ([\;], \alpha_2 \multimap \alpha_2)$.
\end{itemize}
\end{example}
Now we show several properties of our type system and type inference algorithm, in order to prove the soundness and completeness of the algorithm with respect to the system.
\begin{notation}
We write $\Phi \rhd \inftwo{ \Gamma }{ M }{ \sigma }$ if $\Phi$ is a derivation tree ending with $\inftwo{ \Gamma }{ M }{ \sigma }$. In this case, $|\Phi|$ is the length of the derivation tree $\Phi$.
\end{notation}
\begin{lemma}[Substitution]\label{lemSubstitutivity}
If $\Phi \rhd \inftwo{ \Gamma }{ M }{ \sigma }$, then $\inftwo{ \mathbb{S}(\Gamma) }{ M }{ \mathbb{S}(\sigma) }$ for any substitution $\mathbb{S}$.
\input{proofs/proof1}
\end{lemma}
\begin{lemma}[Relevance]\label{xfreesys}
If $\Phi \rhd \inftwo{ \Gamma }{ M }{ \sigma }$, then $x \in \mathsf{dom}(\Gamma)$ if and only if $x \in \fv{M}$.
\input{proofs/proof2}
\end{lemma}
\begin{lemma}\label{xfreealg}
If $\msf{T}(M) = (\Gamma, \sigma)$, then $x \in \mathsf{dom}(\Gamma)$ if and only if $x \in \fv{M}$.
\input{proofs/proof3}
\end{lemma}
\begin{corollary}\label{equaldom}
From \autoref{xfreesys} and \autoref{xfreealg}, it follows that if $\msf{T}(M) = (\Gamma, \sigma)$ and $\inftwo{ \Gamma' }{ M }{ \sigma' }$, then $\mathsf{dom}(\Gamma) = \mathsf{dom}(\Gamma')$.
\end{corollary}
\begin{lemma}\label{eqsubstsystem}
If $\Phi_1 \rhd \inftwo{ \Gamma }{ M }{ \sigma }$, $x \in \fv{M}$ and $y$ does not occur in $M$, then $\Phi_2 \rhd \inftwo{ \sub{\Gamma}{y/x} }{ \sub{M}{y/x} }{ \sigma }$ and $|\Phi_1| = |\Phi_2|$.
\input{proofs/proof4}
\end{lemma}
\begin{corollary}\label{eqsubstsystemcol}
From \autoref{eqsubstsystem}, it follows that if $\inftwo{ \Gamma }{ M }{ \sigma }$, $\{x_1, \dots, x_n\} \subseteq \fv{M}$ and $y_1, \dots, y_n$ are all different variables not occurring in $M$, then $\inftwo{ \Gamma[y_1/x_1, \dots, y_n/x_n] }{ M[y_1/x_1, \dots, y_n/x_n] }{ \sigma }$.
\end{corollary}
\begin{theorem}[Soundness]\label{soundness}
If $\msf{T}(M) = (\Gamma, \sigma)$, then $\inftwo{ \Gamma }{ M }{ \sigma }$.
\input{proofs/proof5}
\end{theorem}
\begin{lemma}\label{eqsubst1}
If $\msf{T}(M) = (\Gamma, \sigma)$, $x \in \fv{M}$ and $y$ does not occur in $M$, then $\msf{T}(M[y/x]) = (\Gamma[y/x], \sigma)$.
\input{proofs/proof6}
\end{lemma}
\begin{lemma}\label{eqsubst2}
If $\msf{T}(M) = (\Gamma, \sigma)$, with $\Gamma \equiv (\Gamma', y_1:\vec{\tau}_1, y_2:\vec{\tau}_2)$, and $y$ does not occur in $M$, then $\msf{T}(M[y/y_1, y/y_2]) = (\Gamma'', \sigma)$, with $\Gamma'' \equiv (\Gamma', y:\vec{\tau}_1 \cap \vec{\tau}_2)$.
\input{proofs/proof7}
\end{lemma}
\begin{theorem}[Completeness]\label{completeness}
If $\Phi \rhd \inftwo{ \Gamma }{ M }{ \sigma }$, then $\msf{T}(M) = (\Gamma', \sigma')$ (for some environment $\Gamma'$ and type $\sigma'$) and there is a substitution $\mathbb{S}$ such that $\mathbb{S}(\sigma') = \sigma$ and $\mathbb{S}(\Gamma') \equiv \Gamma$.
\input{proofs/proof8}
\end{theorem}
Hence, we end up with a sound and complete type inference algorithm for the Linear Rank~2 Intersection Type System.
\subsection{Remarks}\label{sec:linearfinalremarks}
A $\lambda$-term $M$ is called a $\lambda I$-term if and only if, for each subterm of the form $\lambda x.N$ in $M$, $x$ occurs free in $N$ at least once. Note that our type system and type inference algorithm only type $\lambda I$-terms, but we could have extended them for the \emph{affine terms} -- a $\lambda$-term $M$ is affine if and only if, for each subterm of the form $\lambda x.N$ in $M$, $x$ occurs free in $N$ at most once, and if each free variable of $M$ has just one occurrence free in $M$.
There is no unique and final way of typing affine terms. For instance, in the systems in \cite{accattoli2018tight}, arguments that do not occur in the body of the function get the empty type $[\;]$. Since we do not allow the empty sequence in our definition and adding it would make the system more complex, we decided to only work with $\lambda I$-terms.\\
Regarding our choice of defining environments as lists and having the rules (Exchange) and (Contraction) in the type system, instead of defining environments as sets and using the $(+)$ operation for concatenation, that decision had to do with the fact that, this way, the system is closer to a linear type system. In the Linear Rank~2 Intersection Type System, a term is linear until we need to contract variables, so using these definitions makes us have more control over linearity and non-linearity. Also, it makes the system more easily extensible for other algebraic properties of intersection. We could also have rewritten the rule ($\rightarrow$ Elim) in order not to use the $(+)$ operation, which is something we might do in the future.
The downside of choosing these definitions is that it makes the proofs (in \autoref{chap:linearrank} and \autoref{chap:resource}) more complex, as they are not syntax directed because of the rules (Exchange) and (Contraction).
\section{Resource Inference}\label{chap:resource}
Given the quantitative properties of the linear rank~2 intersection types, we now aim to redefine the type system and the type inference algorithm, in order to infer not only the type of a $\lambda$-term, but also parameters related to resource usage. In this case, we are interested in obtaining the number of evaluation steps of the $\lambda$-term to its normal form, for the leftmost-outermost strategy.
\subsection{Type System}\label{sec:tighttypesystem}
The new type system defined in this chapter results from an adaptation and merge between our Linear Rank~2 Intersection Type System (\autoref{lineartypesystem}) and the system for the leftmost-outermost evaluation strategy presented in \cite{accattoli2018tight}, as that system is able to derive a measure related to the number of evaluation steps for the leftmost-outermost strategy. We then begin by adapting some definitions from \cite{accattoli2018tight} and others that were already introduced in \autoref{chap:linearrank}.
The predicates $\msf{normal}$ and $\msf{neutral}$ defining, respectively, the leftmost-outermost normal terms and neutral terms, are in \autoref{normalneutral2}. The predicate $\msf{abs}(M)$ is true if and only if $M$ is an abstraction; $\msf{normal(M)}$ means that $M$ is in normal form; and $\msf{neutral}(M)$ means that $M$ is in normal form and can never behave as an abstraction, i.e., it does not create a redex when applied to an argument.
\begin{definition}[Leftmost-outermost normal forms]\label{normalneutral2}
\hfill
\begin{center}
\AxiomC{}
\UnaryInfC{$\msf{neutral}(x)$}
\DisplayProof
%
\quad
%
\AxiomC{$\msf{neutral}(M)$}
\AxiomC{$\msf{normal}(N)$}
\BinaryInfC{$\msf{neutral}(M N)$}
\DisplayProof
%
\quad
%
\AxiomC{$\msf{neutral}(M)$}
\UnaryInfC{$\msf{normal}(M)$}
\DisplayProof
%
\quad
%
\AxiomC{$\msf{normal}(M)$}
\UnaryInfC{$\msf{normal}(\lambda x.M)$}
\DisplayProof
\end{center}
\end{definition}
\begin{definition} [Leftmost-outermost evaluation strategy]
\hfill
\begin{center}
\AxiomC{}
\UnaryInfC{$(\lambda x.M) N \longrightarrow \sub{M}{N/x}$}
\DisplayProof
%
\quad
%
\AxiomC{$M \longrightarrow M'$}
\UnaryInfC{$\lambda x.M \longrightarrow \lambda x.M'$}
\DisplayProof
%
\quad
%
\AxiomC{$M \longrightarrow M'$}
\AxiomC{$\neg \msf{abs}(M)$}
\BinaryInfC{$M N \longrightarrow M' N$}
\DisplayProof
\hfill
\AxiomC{$\msf{neutral}(N)$}
\AxiomC{$M \longrightarrow M'$}
\BinaryInfC{$N M \longrightarrow N M'$}
\DisplayProof
\end{center}
\end{definition}
\begin{definition}[Finite rank multi-types]
We define the finite rank multi-types by the following grammar:
\begin{Dequation}
\begin{align*}
\msf{tight} &\Coloneqq \msf{Neutral} \mid \msf{Abs} \tag{Tight constants}\\
t &\Coloneqq \msf{tight} \mid \alpha \mid t \multimap t \tag{Rank 0 multi-types}\\
\vec{t} &\Coloneqq t \mid \vec{t} \cap \vec{t} \tag{Rank 1 multi-types}\\
s &\Coloneqq t \mid \vec{t} \rightarrow s \tag{Rank 2 multi-types}
\end{align*}
\end{Dequation}
\end{definition}
\hfil
\begin{definition}
~\begin{itemize}
\item Here, a \emph{statement} is an expression of the form $M:(\vec{\tau}, \vec{t})$, where the pair $(\vec{\tau}, \vec{t})$ is called the \emph{predicate}, and the term $M$ is called the \emph{subject} of the statement.
\item A \emph{declaration} is a statement where the subject is a term variable.
\item The comma operator (,) appends a declaration to the end of a list (of declarations). The list $(\Gamma_1, \Gamma_2)$ is the list that results from appending the list $\Gamma_2$ to the end of the list $\Gamma_1$.
\item A finite list of declarations is \emph{consistent} if and only if the term variables are all distinct.
\item We call \emph{environment} to a consistent finite list of declarations which predicates are pairs with a sequence from $\tl{1}$ as the first element and a rank 1 multi-type as the second element of the pair (i.e., the declarations are of the form $x:(\vec{\tau}, \vec{t})$), and we use $\Gamma$ (possibly with single quotes and/or number subscripts) to range over environments.
\item If $\Gamma = [x_1:(\vec{\tau}_1, \vec{t}_1), \dots, x_n:(\vec{\tau}_n, \vec{t}_n)]$ is an environment, then $\Gamma$ is a partial function, with domain $\mathsf{dom}(\Gamma) = \{x_1, \dots, x_n\}$, and $\Gamma(x_i) = (\vec{\tau}_i, \vec{t}_i)$.
\item We write $\Gamma_x$ for the resulting environment of eliminating the declaration of $x$ from $\Gamma$ (if there is no declaration of $x$ in $\Gamma$, then $\Gamma_x = \Gamma$).
\item We write $\Gamma_1 \equiv \Gamma_2$ if the environments $\Gamma_1$ and $\Gamma_2$ are equal up to the order of the declarations.
\item If $\Gamma_1$ and $\Gamma_2$ are environments, the environment $\Gamma_1 + \Gamma_2$ is defined as follows:
for each $x \in \mathsf{dom}(\Gamma_1) \cup \mathsf{dom}(\Gamma_2)$,
\[
(\Gamma_1 + \Gamma_2)(x) = \left\{
\begin{array}{ll}
\Gamma_1(x) &\text{if } x \notin \mathsf{dom}(\Gamma_2)\\
\Gamma_2(x) &\text{if } x \notin \mathsf{dom}(\Gamma_1)\\
(\vec{\tau}_1 \cap \vec{\tau}_2, \vec{t}_1 \cap \vec{t}_2) &\text{if } \Gamma_1(x) = (\vec{\tau}_1, \vec{t}_1) \text{ and } \Gamma_2(x) = (\vec{\tau}_2, \vec{t}_2)
\end{array}
\right.
\]
with the declarations of the variables in $\mathsf{dom}(\Gamma_1)$ in the beginning of the list, by the same order they appear in $\Gamma_1$, followed by the declarations of the variables in $\mathsf{dom}(\Gamma_2) \setminus \mathsf{dom}(\Gamma_1)$, by the order they appear in $\Gamma_2$.
\item We write $\msf{tight}(s)$ if $s$ is of the form $\msf{tight}$ and $\msf{tight}(t_1 \cap \cdots \cap t_n)$ if $\msf{tight}(t_i)$ for all $1 \leq i \leq n$.
For $\Gamma = [x_1:(\vec{\tau}_1, \vec{t}_1), \dots, x_n:(\vec{\tau}_n, \vec{t}_n)]$, we write $\msf{tight}(\Gamma)$ if $\msf{tight}(\vec{t}_i)$ for all $1 \leq i \leq n$, in which case we also say that $\Gamma$ is tight.
\end{itemize}
\end{definition}
\begin{definition}[Linear Rank~2 Quantitative Type System]\label{tightlinearsystem}
In the Linear Rank~2 Quantitative Type System, we say that $M$ has type $\sigma$ and multi-type $s$ given the environment $\Gamma$, with index $b$, and write
\[
\infertight{ \Gamma }{ b }{ M }{ \sigma }{ s }
\]
if it can be obtained from the following \emph{derivation rules}:
\begin{equation}\tag{Axiom}
\begin{mathprooftree}
\AxiomC{$\infertight{ [x:(\tau, t)] }{ 0 }{ x }{ \tau }{ t }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{Exchange}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma_1, x:(\vec{\tau}_1, \vec{t}_1), y:(\vec{\tau}_2, \vec{t}_2), \Gamma_2 }{ b }{ M }{ \sigma }{ s }$}
\UnaryInfC{$\infertight{ \Gamma_1, y:(\vec{\tau}_2, \vec{t}_2), x:(\vec{\tau}_1, \vec{t}_1), \Gamma_2 }{ b }{ M }{ \sigma }{ s }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{Contraction}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma_1, x_1:(\vec{\tau}_1, \vec{t}_1), x_2:(\vec{\tau}_2, \vec{t}_2), \Gamma_2 }{ b }{ M }{ \sigma }{ s }$}
\UnaryInfC{$\infertight{ \Gamma_1, x:(\vec{\tau}_1 \cap \vec{\tau}_2, \vec{t}_1 \cap \vec{t}_2), \Gamma_2 }{ b }{ M [x/x_1, x/x_2] }{ \sigma }{ s }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\multimap$ Intro}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma, x:(\tau, t) }{ \color{azulciencias} b }{ M }{ \sigma }{ s }$}
\UnaryInfC{$\infertight{ \Gamma }{ \color{azulciencias} b+1 }{ \lambda x.M }{ \tau \multimap \sigma }{ t \multimap s }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\multimap$ Intro\textsubscript{t}}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma, x:(\tau, \msf{tight}) }{ b }{ M }{ \sigma }{ \msf{tight} }$}
\UnaryInfC{$\infertight{ \Gamma }{ b }{ \lambda x.M }{ \tau \multimap \sigma }{ \msf{Abs} }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\rightarrow$ Intro}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma, x:(\tau_1 \cap \cdots \cap \tau_n, t_1 \cap \cdots \cap t_n) }{ \color{azulciencias} b }{ M }{ \sigma }{ s }$}
\AxiomC{$n \geq 2$}
\BinaryInfC{$\infertight{ \Gamma }{ \color{azulciencias} b+1 }{ \lambda x.M }{ \tau_1 \cap \cdots \cap \tau_n \rightarrow \sigma }{ t_1 \cap \cdots \cap t_n \rightarrow s }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\rightarrow$ Intro\textsubscript{t}}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma, x:(\tau_1 \cap \cdots \cap \tau_n, \vec{t}) }{ b }{ M }{ \sigma }{ \msf{tight} }$}
\AxiomC{$\msf{tight}(\vec{t})$}
\AxiomC{$n \geq 2$}
\TrinaryInfC{$\infertight{ \Gamma }{ b }{ \lambda x.M }{ \tau_1 \cap \cdots \cap \tau_n \rightarrow \sigma }{ \msf{Abs} }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\multimap$ Elim}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma_1 }{ b_1 }{ M_1 }{ \tau \multimap \sigma }{ t \multimap s }$}
\AxiomC{$\infertight{ \Gamma_2 }{ b_2 }{ M_2 } { \tau }{ t }$}
\BinaryInfC{$\infertight{ \Gamma_1, \Gamma_2 }{ b_1 + b_2 }{ M_1 M_2 }{ \sigma }{ s }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\multimap$ Elim\textsubscript{t}}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma_1 }{ b_1 }{ M_1 }{ \tau \multimap \sigma }{ \msf{Neutral} }$}
\AxiomC{$\infertight{ \Gamma_2 }{ b_2 }{ M_2 } { \tau }{ \msf{tight} }$}
\BinaryInfC{$\infertight{ \Gamma_1, \Gamma_2 }{ b_1 + b_2 }{ M_1 M_2 }{ \sigma }{ \msf{Neutral} }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\rightarrow$ Elim}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma }{ b }{ M_1 }{ \tau_1 \cap \cdots \cap \tau_n \rightarrow \sigma }{ t_1 \cap \cdots \cap t_n \rightarrow s }$}
\noLine
\UnaryInfC{$\infertight{ \Gamma_1 }{ b_1 }{ M_2 } { \tau_1 }{ t_1 } \text { } \cdots \text{ } \infertight{ \Gamma_n }{ b_n }{ M_2 } { \tau_n }{ t_n }$}
\AxiomC{$n \geq 2$}
\BinaryInfC{$\infertight{ \Gamma, \sum_{i=1}^n \Gamma_i }{ b + b_1 + \dots + b_n }{ M_1 M_2 }{ \sigma }{ s }$}
\end{mathprooftree}
\end{equation}
\begin{equation}\tag{$\rightarrow$ Elim\textsubscript{t}}
\begin{mathprooftree}
\AxiomC{$\infertight{ \Gamma }{ b }{ M_1 }{ \tau_1 \cap \cdots \cap \tau_n \rightarrow \sigma }{ \msf{Neutral} }$}
\noLine
\UnaryInfC{$\infertight{ \Gamma_1 }{ b_1 }{ M_2 } { \tau_1 }{ \msf{tight} } \text { } \cdots \text{ } \infertight{ \Gamma_n }{ {b_n} }{ M_2 } { \tau_n }{ \msf{tight} }$}
\AxiomC{$n \geq 2$}
\BinaryInfC{$\infertight{ \Gamma, \sum_{i=1}^n \Gamma_i }{ b + b_1 + \dots + b_n }{ M_1 M_2 }{ \sigma }{ \msf{Neutral} }$}
\end{mathprooftree}
\end{equation}
\end{definition}
The tight rules (the t-indexed ones) are used to introduce the tight constants $\msf{Neutral}$ and $\msf{Abs}$, and they are related to minimal typings. Note that the index is only incremented in rules ($\multimap$ Intro) and ($\rightarrow$ Intro), as these are used to type abstractions that will be applied, contrary to the abstractions typed with the constant $\msf{Abs}$.
\begin{notation}
We write $\Phi \rhd \infertight{ \Gamma }{ b }{ M }{ \sigma }{ s }$ if $\Phi$ is a derivation tree ending with $\infertight{ \Gamma }{ b }{ M }{ \sigma }{ s }$. In this case, $|\Phi|$ is the length of the derivation tree $\Phi$.
\end{notation}
\begin{definition}[Tight derivations]
A derivation $\Phi \rhd \infertight{ \Gamma }{ b }{ M }{ \sigma }{ s }$ is tight if $\msf{tight}(s)$ and $\msf{tight}(\Gamma)$.
\end{definition}
Similarly to what has been done in \cite{accattoli2018tight}, in this section we prove that, in the Linear Rank~2 Quantitative Type System, whenever a term is tightly typable with index $b$, then $b$ is exactly the number of evaluations steps to leftmost-outermost normal form.
\begin{example}
Let $M = (\lambda x_1.(\lambda x_2.x_2 x_1) x_1) I$, where $I$ is the identity function $\lambda y.y$.
Let us first consider the leftmost-outermost evaluation of $M$ to normal form:
\[
(\lambda x_1.(\lambda x_2.x_2 x_1) x_1) I \longrightarrow (\lambda x_2.x_2 I) I \longrightarrow I I \longrightarrow I
\]
\indent So the evaluation sequence has length $3$.
Let us write $\overmultimap{\alpha}$ for the type $(\alpha \multimap \alpha)$ and $\overlongmultimap{\msf{Abs}}$ for the type $\msf{Abs} \multimap \msf{Abs}$.
To make the derivation tree easier to read, let us first get the following derivation $\Phi$ for the term $\lambda x_1.(\lambda x_2.x_2 x_1) x_1$:
\scalebox{0.7}{
\begin{mathprooftree}
\AxiomC{$\infertight{ [x_2:(\overmultimap{\alpha} \multimap \overmultimap{\alpha}, \overlongmultimap{\msf{Abs}})] }{ 0 }{ x_2 }{ \overmultimap{\alpha} \multimap \overmultimap{\alpha} }{ \overlongmultimap{\msf{Abs}} }$}
\AxiomC{$\infertight{ [x_3:(\overmultimap{\alpha}, \msf{Abs})] }{ 0 }{ x_3 }{ \overmultimap{\alpha} }{ \msf{Abs} }$}
\BinaryInfC{$\infertight{ [x_2:(\overmultimap{\alpha} \multimap \overmultimap{\alpha}, \overlongmultimap{\msf{Abs}}), x_3:(\overmultimap{\alpha}, \msf{Abs})] }{ 0 }{ x_2 x_3 }{ \overmultimap{\alpha} }{ \msf{Abs} }$}
\UnaryInfC{$\infertight{ [x_3:(\overmultimap{\alpha}, \msf{Abs})] }{ 1 }{ \lambda x_2.x_2 x_3 }{ (\overmultimap{\alpha} \multimap \overmultimap{\alpha}) \multimap \; \overmultimap{\alpha} }{ \overlongmultimap{\msf{Abs}} \multimap \msf{Abs} }$}
\AxiomC{$\infertight{ [x_4:(\overmultimap{\alpha} \multimap \overmultimap{\alpha}, \overlongmultimap{\msf{Abs}})] }{ 0 }{ x_4 }{ \overmultimap{\alpha} \multimap \overmultimap{\alpha} }{ \overlongmultimap{\msf{Abs}}) }$}
\BinaryInfC{$\infertight{ [x_3:(\overmultimap{\alpha}, \msf{Abs}), x_4:(\overmultimap{\alpha} \multimap \overmultimap{\alpha}, \overlongmultimap{\msf{Abs}})] }{ 1 }{ (\lambda x_2.x_2 x_3) x_4 }{ \overmultimap{\alpha} }{ \msf{Abs} }$}
\UnaryInfC{$\infertight{ [x_1:(\overmultimap{\alpha} \cap \; (\overmultimap{\alpha} \multimap \overmultimap{\alpha}), \msf{Abs} \; \cap \overlongmultimap{\msf{Abs}})] }{ 1 }{ (\lambda x_2.x_2 x_1) x_1 }{ \overmultimap{\alpha} }{ \msf{Abs} }$}
\UnaryInfC{$\infertight{ [\;] }{ 2 }{ \lambda x_1.(\lambda x_2.x_2 x_1) x_1 }{ (\overmultimap{\alpha} \cap \; (\overmultimap{\alpha} \multimap \overmultimap{\alpha})) \rightarrow \; \overmultimap{\alpha} }{ (\msf{Abs} \; \cap \overlongmultimap{\msf{Abs}}) \rightarrow \msf{Abs} }$}
\end{mathprooftree}
}\\
Then for the $\lambda$-term $M$, the following tight derivation is obtained:
\begin{center}
\begin{mathprooftree}
\AxiomC{$\Phi$}
\AxiomC{$\infertight{ [y:(\alpha, \msf{Neutral})] }{ 0 }{ y }{ \alpha }{ \msf{Neutral} }$}
\UnaryInfC{$\infertight{ [\;] }{ 0 }{ I }{ \overmultimap{\alpha} }{ \msf{Abs} }$}
\AxiomC{$\infertight{ [y:(\overmultimap{\alpha}, \msf{Abs})] }{ 0 }{ y }{ \overmultimap{\alpha} }{ \msf{Abs} }$}
\UnaryInfC{$\infertight{ [\;] }{ 1 }{ I }{ \overmultimap{\alpha} \multimap \overmultimap{\alpha} }{ \overlongmultimap{\msf{Abs}} }$}
\TrinaryInfC{$\infertight{ [\;] }{ 3 }{ (\lambda x_1.(\lambda x_2.x_2 x_1) x_1) I }{ \overmultimap{\alpha} }{ \msf{Abs} }$}
\end{mathprooftree}
\end{center}
So indeed, the index $3$ represents the number of evaluation steps to leftmost-outermost normal form.
\end{example}
We now show several properties of the type system, adapted from \cite{accattoli2018tight}, in order to prove the \emph{tight correctness} (\autoref{tightcorrect}).
\begin{lemma}[Tight spreading on neutral terms]\label{spreading}
If $M$ is a term such that $\msf{neutral}(M)$ and $\Phi \rhd \infertight{ \Gamma }{ b }{ M } { \sigma }{ s }$ is a typing derivation such that $\msf{tight}(\Gamma)$, then $\msf{tight}(s)$.
\input{proofs/proof9}
\end{lemma}
\begin{lemma}[Properties of tight typings for normal forms]\label{tightproperties}
Let $M$ be such that $\msf{normal}(M)$ and $\Phi \rhd \infertight{ \Gamma }{ b }{ M } { \sigma }{ s }$ be a typing derivation.
\begin{enumerate}[(i)]
\item \emph{Tightness}: if $\Phi$ is tight, then $b = 0$.
\item \emph{Neutrality}: if $s = \msf{Neutral}$ then $\msf{neutral}(M)$.
\end{enumerate}
\input{proofs/proof10}
\end{lemma}
\begin{lemma}[Relevance]\label{xfreesys2}
If $\Phi \rhd \infertight{ \Gamma }{ b }{ M }{ \sigma }{ s }$, then $x \in \mathsf{dom}(\Gamma)$ if and only if $x \in \fv{M}$.
\input{proofs/proof11}
\end{lemma}
\begin{lemma}[Substitution and typings]\label{substlema}
Let $\Phi \rhd \infertight{ \Gamma }{ b }{ M_1 }{ \sigma }{ s }$ be a derivation with $x \in \mathsf{dom}(\Gamma)$ and $\Gamma(x) = (\tau_1 \cap \cdots \cap \tau_n, t_1 \cap \cdots \cap t_n)$, for $n \geq 1$. And, for each $1 \leq i \leq n$, let $\Phi_i \rhd \infertight{ \Gamma_i }{ b_i }{ M_2 } { \tau_i }{ t_i }$.
Then there exists a derivation $\Phi' \rhd \infertight{ \Gamma_x, \sum_{i=1}^n \Gamma_i }{ b + b_1 + \dots + b_n }{ \sub{M_1}{M_2/x} }{ \sigma }{ s }$. Moreover, if the derivations $\Phi, \Phi_1, \dots, \Phi_n$ are tight, then so is the derivation $\Phi'$.
\input{proofs/proof12}
\end{lemma}
We now show an important property that relates contracted terms with their linear counterpart. Basically, it says that the following diagram commutes (under the described conditions):
\begin{center}
\begin{tikzpicture}[line width=1pt,shorten >=2pt,shorten <=2pt]
\node (m) at (0,0) {$M$};
\node (n) at (2,0) {$N$};
\node (m') at (0,2) {$M'$};
\node (n') at (2,2) {$N'$};
\draw[-To] (m) to node[auto, swap] {$\beta$} (n);
\draw[->] (m') to node[auto, swap] {$\mathcal{S}(M')$} (m);
\draw[-To] (m') to node[auto] {$\beta$} (n');
\draw[->] (n') to node[auto] {$\mathcal{S}(N')$} (n);
\end{tikzpicture}
\end{center}
\begin{lemma}\label{substreduction}
Let $M \longrightarrow N$ and $M = \mathcal{S}(M')$ for some substitution $\mathcal{S} = \subst{x/x_1, x/x_2}$ where $x_1, x_2$ occur free in $M'$ and $x$ does not occur in $M'$. Then there exists a term $N'$ such that $N = \mathcal{S}(N')$ and $M' \longrightarrow N'$.
\input{proofs/proof13}
\end{lemma}
\begin{convention}\label{contractedvars}
Without loss of generality, we assume that, in a derivation tree, all contracted variables (i.e., variables that, at some point in the derivation tree, disappear from the term and environment by an application of the (Contraction) rule) are different from any other variable in the derivation tree.\\
We also assume that when applying (Contraction), the new variables that substitute the contracted ones are also different from any other variable in the derivation tree.
\end{convention}
\begin{lemma}[Quantitative subject reduction]\label{subjectreduction}
If $\Phi \rhd \infertight{ \Gamma }{ b }{ M } { \sigma }{ s }$ is tight and $M \longrightarrow N$, then $b \geq 1$ and there exists a tight derivation $\Phi'$ such that $\Phi' \rhd \infertight{ \Gamma }{ b-1 }{ N } { \sigma }{ s }$.
\input{proofs/proof14}
\end{lemma}
\begin{theorem}[Tight correctness]\label{tightcorrect}
If $\Phi \rhd \infertight{ \Gamma }{ b }{ M } { \sigma }{ s }$ is a tight derivation, then there exists $N$ such that $M \longrightarrow^b N$ and $\msf{normal}(N)$. Moreover, if $s = \msf{Neutral}$ then $\msf{neutral}(N)$.
\input{proofs/proof15}
\end{theorem}
\subsection{Type Inference Algorithm}\label{sec:tightinference}
We now extend the type inference algorithm defined in \autoref{chap:linearrank} (\autoref{ti2}) to also infer the number of reduction steps of the typed term to its normal form, when using the leftmost-outermost evaluation strategy.
This is done by slightly modifying the unification algorithm in \autoref{unify} and the algorithm in \autoref{ti2}, which will now carry and update a measure $b$ that relates to the number of reduction steps.
First, recall the following definition, presented in \autoref{chap:linearrank}:
\begin{definition}[Type unification]\label{transformuni2}
We define the following relation $\Rightarrow$ on type unification problems (for types in $\tl{0}$):
\begin{alignat*}{3}
&\{\tau = \tau\} \cup P \quad && \Rightarrow \quad P &&\\
&\{\tau_1 \multimap \tau_2 = \tau_3 \multimap \tau_4\} \cup P \quad && \Rightarrow \quad \{\tau_1 = \tau_3, \tau_2 = \tau_4\} \cup P &&\\
&\{\tau_1 \multimap \tau_2 = \alpha\} \cup P \quad && \Rightarrow \quad \{\alpha = \tau_1 \multimap \tau_2\} \cup P &&\\
&\{\alpha = \tau\} \cup P \quad && \Rightarrow \quad \{\alpha = \tau\} \cup \tsub{P}{\tau/\alpha} &&\quad \text{if } \alpha \in \msf{fv}(P) \setminus \msf{fv}(\tau)\\
&\{\alpha = \tau\} \cup P \quad && \Rightarrow \quad \msf{FAIL} &&\quad \text{if } \alpha \in \msf{fv}(\tau) \text{ and } \alpha \neq \tau
\end{alignat*}
where $\tsub{P}{\tau/\alpha}$ corresponds to the notion of type-substitution extended to type unification problems. If $P = \{\tau_1 = \tau_1', \dots, \tau_n=\tau_n'\}$, then $\tsub{P}{\tau/\alpha} = \{\tsub{\tau_1}{\tau/\alpha} = \tsub{\tau_1'}{\tau/\alpha}, \dots, \tsub{\tau_n}{\tau/\alpha} = \tsub{\tau_n'}{\tau/\alpha}\}$.
And $ \msf{fv}(P)$ and $ \msf{fv}(\tau)$ are the sets of free type variables in $P$ and $\tau$, respectively. Since in our system all occurrences of type variables are free, $ \msf{fv}(P)$ and $ \msf{fv}(\tau)$ are the sets of type variables in $P$ and $\tau$, respectively.
\end{definition}
\begin{definition}[Quantitative Unification Algorithm]\label{unifyq}
Let $P$ be a unification problem (with types in $\tl{0}$). The new unification function $\msf{UNIFY_Q}(P)$, which decides whether $P$ has a solution and, if so, returns the MGU of $P$ and an integer $b$ used for counting purposes in the inference algorithm, is defined as:
\begin{algorithmic}
\Function{$\msf{UNIFY_Q}$}{$P$}
\State $b \coloneqq 0$;
\While{$P \Rightarrow P'$}
\If{$P = \{\tau_1 \multimap \tau_2 = \tau_3 \multimap \tau_4\} \cup P_1$ \textbf{and} $P' = \{\tau_1 = \tau_3, \tau_2 = \tau_4\} \cup P_1$}
\State $b \coloneqq b+1$;
\EndIf
\State $P \coloneqq P'$;
\EndWhile
\If{$P$ is in solved form}
\State \Return $(\mathbb{S}_P, b)$;
\Else
\State $\msf{FAIL}$;
\EndIf
\EndFunction
\end{algorithmic}
\end{definition}
Let us call $\tl{1}$-environment to an environment as defined in \autoref{chap:linearrank}, i.e., just like the definition we use in the current chapter, but the predicates are only the first element of the pair (i.e., a sequence from $\tl{1}$).
\begin{definition}[Quantitative Type Inference Algorithm]\label{qti2}
Let $\Gamma$ be a $\tl{1}$-environment, $M$ a $\lambda$-term, $\sigma$ a linear rank~2 intersection type, $b$ a quantitative measure and $\msf{UNIFY_Q}$ the function in \autoref{unifyq}. The function $\msf{T_Q}(M) = (\Gamma, \sigma, b)$ defines a new type inference algorithm that gives a quantitative measure for the $\lambda$-calculus in the Linear Rank~2 Quantitative Type System, in the following way:
\begin{enumerate}
\item \tul{If} $M=x$, \tul{then} $\Gamma = [x:\alpha]$, $\sigma = \alpha$ and ${\color{azulciencias} b = 0}$, where $\alpha$ is a new variable;
\item \tul{If} $M=\lambda x.M_1$ and $\msf{T_Q}(M_1) = (\Gamma_1, \sigma_1, b_1)$ \tul{then}:
\begin{enumerate}
\item \tul{if} $x \notin \mathsf{dom}(\Gamma_1)$, \tul{then} $\msf{FAIL}$;
\item \tul{if} $(x:\tau) \in \Gamma_1$, \tul{then} $\msf{T_Q}(M) = ({\Gamma_1}_x, \tau \multimap \sigma_1, {\color{azulciencias} b_1})$;
\item \tul{if} $(x:\tau_1 \cap \cdots \cap \tau_n) \in \Gamma_1$ (with $n \geq 2$), \tul{then} $\msf{T_Q}(M) = ({\Gamma_1}_x, \tau_1 \cap \cdots \cap \tau_n \rightarrow \sigma_1, {\color{azulciencias} b_1})$.
\end{enumerate}
\item \tul{If} $M=M_1 M_2$, \tul{then}:
\begin{enumerate}
\item \tul{if} $\msf{T_Q}(M_1) = (\Gamma_1, \alpha_1, b_1)$ and $\msf{T_Q}(M_2) = (\Gamma_2, \tau_2, b_2)$,\\
\tul{then} $\msf{T_Q}(M) = (\mathbb{S}(\Gamma_1 + \Gamma_2), \mathbb{S}(\alpha_3), {\color{azulciencias} b_1+b_2})$,\\
where $(\mathbb{S}, \_) = \msf{UNIFY_Q}(\{\alpha_1 = \alpha_2 \multimap \alpha_3, \tau_2 = \alpha_2\})$ and $\alpha_2,\alpha_3$ are new variables;
\item \tul{if} $\msf{T_Q}(M_1) = (\Gamma_1', \tau_1' \cap \cdots \cap \tau_n' \rightarrow \sigma_1', b_1)$ (with $n \geq 2$) and, for each $1 \leq i \leq n$, $\msf{T_Q}(M_2) = (\Gamma_i, \tau_i, b_i)$,\\
\tul{then} $\msf{T_Q}(M) = (\mathbb{S}(\Gamma_1' + \sum_{i=1}^n \Gamma_i), \mathbb{S}(\sigma_1'), {\color{azulciencias} b_1 + \sum_{i=1}^n b_i + b_3 + 1})$,\\
where $(\mathbb{S}, b_3) = \msf{UNIFY_Q}(\{\tau_i = \tau_i' \mid 1 \leq i \leq n\})$;
\item \tul{if} $\msf{T_Q}(M_1) = (\Gamma_1, \tau \multimap \sigma_1, b_1)$ and $\msf{T_Q}(M_2) = (\Gamma_2, \tau_2, b_2)$,\\
\tul{then} $\msf{T_Q}(M) = (\mathbb{S}(\Gamma_1 + \Gamma_2), \mathbb{S}(\sigma_1), {\color{azulciencias} b_1+b_2+b_3+1})$,\\
where $(\mathbb{S}, b_3) = \msf{UNIFY_Q}(\{\tau_2 = \tau\})$;
\item \tul{otherwise} $\msf{FAIL}$.
\end{enumerate}
\end{enumerate}
\end{definition}
Note that $b$ is only increased by $1$ and added the quantity given by $\msf{UNIFY_Q}$ in rules 3.(b) and 3.(c), since these are the only cases in which the term $M$ is a redex.
\begin{example}
Let us show the type inference process for the $\lambda$-term $\lambda x.x x$.
\begin{itemize}
\item By rule 1., $\msf{T_Q}(x) = ([x:\alpha_1], \alpha_1, 0)$.
\item By rule 1., again, $\msf{T_Q}(x) = ([x:\alpha_2], \alpha_2, 0)$.
\item Then by rule 3.(a), $\msf{T_Q}(x x) = (\mathbb{S}([x:\alpha_1] + [x:\alpha_2]), \mathbb{S}(\alpha_4), 0+0) = (\mathbb{S}([x:\alpha_1 \cap \alpha_2]), \mathbb{S}(\alpha_4), 0)$,
where $(\mathbb{S}, \_) = \msf{UNIFY_Q}(\{\alpha_1 = \alpha_3 \multimap \alpha_4, \alpha_2 = \alpha_3\}) = (\tsubst{\alpha_3 \multimap \alpha_4/\alpha_1, \alpha_3/\alpha_2}, 0)$.
So $\msf{T_Q}(x x) = ([x:(\alpha_3 \multimap \alpha_4) \cap \alpha_3], \alpha_4, 0)$.
\item Finally, by rule 2.(c), $\msf{T_Q}(\lambda x.x x) = ([\;], (\alpha_3 \multimap \alpha_4) \cap \alpha_3 \rightarrow \alpha_4, 0)$.
\end{itemize}
\end{example}
\begin{example}
Let us now show the type inference process for the $\lambda$-term $(\lambda x.x x) (\lambda y.y)$.
\begin{itemize}
\item From the previous example, we have $\msf{T_Q}(\lambda x.x x) = ([\;], (\alpha_3 \multimap \alpha_4) \cap \alpha_3 \rightarrow \alpha_4, 0)$.
\item By rules 1. and 2.(b), for the identity, the algorithm gives $\msf{T_Q}(\lambda y.y) = ([\;], \alpha_1 \multimap \alpha_1, 0)$.
\item By rules 1. and 2.(b), again, for the identity, $\msf{T_Q}(\lambda y.y) = ([\;], \alpha_2 \multimap \alpha_2, 0)$.
\item Then by rule 3.(b), $\msf{T_Q}((\lambda x.x x) (\lambda y.y)) = (\mathbb{S}([\;] + [\;] + [\;]), \mathbb{S}(\alpha_4), 0+0+0+b_3+1) = ([\;], \mathbb{S}(\alpha_4), b_3+1)$,
where $(\mathbb{S}, b_3) = \msf{UNIFY_Q}(\{\alpha_1 \multimap \alpha_1 = \alpha_3 \multimap \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_3\})$, calculated by performing the following transformations:
\begin{align*}
\{ \alpha_1 \multimap \alpha_1 = \alpha_3 \multimap \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_3 \}
&\Rightarrow \{ \alpha_1 = \alpha_3, \alpha_1 = \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_3 \}\\
&\Rightarrow \{ \alpha_1 = \alpha_3, \alpha_3 = \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_3 \}\\
&\Rightarrow \{ \alpha_1 = \alpha_4, \alpha_3 = \alpha_4, \alpha_2 \multimap \alpha_2 = \alpha_4 \}\\
&\Rightarrow \{ \alpha_1 = \alpha_4, \alpha_3 = \alpha_4, \alpha_4 = \alpha_2 \multimap \alpha_2 \}\\
&\Rightarrow \{ \alpha_1 = \alpha_2 \multimap \alpha_2, \alpha_3 = \alpha_2 \multimap \alpha_2, \alpha_4 = \alpha_2 \multimap \alpha_2 \}
\end{align*}
So $\mathbb{S} = \tsubst{(\alpha_2 \multimap \alpha_2) / \alpha_1, (\alpha_2 \multimap \alpha_2) / \alpha_3, (\alpha_2 \multimap \alpha_2) / \alpha_4}$
and $b_3 = 1$ because there was performed one transformation (the first) of the form $\{\tau_1 \multimap \tau_2 = \tau_3 \multimap \tau_4\} \cup P \Rightarrow \{\tau_1 = \tau_3, \tau_2 = \tau_4\} \cup P$.
And then, $\msf{T_Q}((\lambda x.x x) (\lambda y.y)) = ([\;], \alpha_2 \multimap \alpha_2, 1+1) = ([\;], \alpha_2 \multimap \alpha_2, 2)$.
\end{itemize}
\end{example}
Since the Quantitative Type Inference Algorithm only differs from the algorithm in \autoref{chap:linearrank} on the addition of the quantitative measure, and only infers a linear rank 2 intersection type and not a multi-type, the typing soundness (\autoref{soundness2}) and completeness (\autoref{completeness2}) are formalized in a similar way.
\begin{theorem}[Typing soundness]\label{soundness2}
If $\msf{T_Q}(M) = ([x_1:\vec{\tau}_1, \dots, x_n:\vec{\tau}_n], \sigma, b)$, then $\infertight{ [x_1:(\vec{\tau}_1, \vec{t}_1), \dots, x_n:(\vec{\tau}_n, \vec{t}_n)] }{ b' }{ M }{ \sigma }{ s }$ (for some measure $b'$ and multi-types $s, \vec{t}_1, \dots, \vec{t}_n$).
\input{proofs/proof16}
\end{theorem}
\begin{theorem}[Typing completeness]\label{completeness2}
If $\Phi \rhd \infertight{ [x_1:(\vec{\tau}_1, \vec{t}_1), \dots, x_n:(\vec{\tau}_n, \vec{t}_n)] }{ b }{ M }{ \sigma }{ s }$, then $\msf{T_Q}(M) = (\Gamma', \sigma', b')$ (for some $\tl{1}$-environment $\Gamma'$, type $\sigma'$ and measure $b'$) and there is a substitution $\mathbb{S}$ such that $\mathbb{S}(\sigma') = \sigma$ and $\mathbb{S}(\Gamma') \equiv [x_1:\vec{\tau}_1, \dots, x_n:\vec{\tau}_n]$.
\input{proofs/proof17}
\end{theorem}
As for the quantitative measure given by the algorithm, we conjecture that it corresponds to the number of evaluation steps of the typed term to normal form, when using the leftmost-outermost evaluation strategy. We strongly believe the conjecture holds, based on the attempted proofs so far and because it holds for every experimental results obtained by our implementation. We have not yet proven this property, which we formalize, in part, in the second point of the strong soundness:
\begin{conjecture}[Strong soundness]\label{strongsoundness}
If $\msf{T_Q}(M) = ([x_1:\vec{\tau}_1, \dots, x_n:\vec{\tau}_n], \sigma, b)$, then:
\begin{enumerate}
\item There is a derivation $\Phi \rhd \infertight{ [x_1:(\vec{\tau}_1, \vec{t}_1), \dots, x_n:(\vec{\tau}_n, \vec{t}_n)] }{ b' }{ M }{ \sigma }{ s }$ (for some measure $b'$ and multi-types $s, \vec{t}_1, \dots, \vec{t}_n$);
\item If $\Phi$ is a tight derivation, then $b = b'$.
\end{enumerate}
\end{conjecture}
Note that the second point implies, by \autoref{tightcorrect}, that there exists $N$ such that $M \longrightarrow^b N$ and $\msf{normal}(N)$, which is what we conjecture.\\
We believe that proving this conjecture is not a trivial task. A first approach could be to try to use induction on the definition of $\msf{T_Q}(M)$. However, this does not work because the subderivations within a tight derivation are not necessarily tight. For that same reason, it is also not trivial to construct a tight derivation from the result given by the algorithm or from a non-tight derivation.
Thus, in order to prove this conjecture, we believe that it will be necessary to establish a stronger relation between the algorithm and tight derivations.
\section{Conclusions and Future Work}\label{chap:conclusion}
When developing a non-idempotent intersection type system capable of obtaining quantitative information about a $\lambda$-term while inferring its type, we realized that the classical notion of rank was not a proper fit for non-idempotent intersection types, and that the ranks could be quantitatively more useful if the base case was changed to types that give more quantitative information in comparison to simple types, which is the case for linear types. We then came up with a new definition of rank for intersection types based on linear types, which we call \emph{linear rank} \cite{typesabstract}.
Based on the notion of linear rank, we defined a new intersection type system for the $\lambda$-calculus, restricted to linear rank~2 non-idempotent intersection types, and a new type inference algorithm which we proved to be sound and complete with respect to the type system.
We then merged that intersection type system with the system for the leftmost-outermost evaluation strategy presented in \cite{accattoli2018tight} in order to use the linear rank~2 non-idempotent intersection types to obtain quantitative information about the typed terms, and we proved that the resulting type system gives the correct number of evaluation steps for a kind of derivations. We also extended the type inference algorithm we had defined, in order to also give that measure, and showed that it is sound and complete with respect to the type system for the inferred types, and conjectured that the inferred measures correspond to the ones given by the type system.
In the future, we would like to:
\begin{enumerate}
\item prove \autoref{strongsoundness};
\item further explore the relation between our definition of linear rank and the classical definition of rank;
\item extend the type systems and the type inference algorithms for the affine terms;
\item adapt the Linear Rank~2 Quantitative Type System and the Quantitative Type Inference Algorithm for other evaluation strategies.
\end{enumerate}
\chapter{Introduction}\label{chap:intro}
\input{chapters/chap1-intro}
\input{chapters/chap2-background}
\input{chapters/chap3-linear}
\input{chapters/chap4-resource}
\input{chapters/chap6-conclusion}
| {'timestamp': '2022-12-01T02:19:57', 'yymm': '2211', 'arxiv_id': '2211.17186', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17186'} | arxiv |
\section{Introduction}
Reinforcement Learning (RL) is useful to solve real world problems whose models are inspired by game theory (GT). Stackelberg security games (SSGs) in GT formulate real world agents competing to control targets in domains like protecting infrastructure
\citep{9668430}, preventing drug smuggling, combating illegal fishing and
animal poaching, mitigating illegal logging, and other climate change problems \citep{9722864}.
Successful automated assessment of RL algorithms for SSGs require well-defined and interpretable target (secure resources) representations.
\begin{comment}
Reinforcement Learning (RL) has been useful to solve real world problems whose models are inspired from game theory (GT). Stackelberg security games (SSGs) in GT model agents in the real world competing to control)/controlling/(contesting over) targets in domains like protecting infrastructure such as airports, trains, and traffic. \citep{9668430}, preventing drug smuggling, combating overfishing and endangered animal poaching, mitigating illegal logging and other climate change problems \citep{9722864}. We investigate how RL algorithms model SSGs with a specific focus on understanding target representations to get better solutions.
\end{comment}
\subsection{Stackelberg Security Games}
Stackelberg security games (SSGs) are two-player games with one defender and one attacker. The defender aims to protect a set of targets $T$ by allocating limited resources to protect up to $b$ targets, where $b\subset T$. The payoff functions for the defender and attacker are $U^d(t)$ and $U^a(t)$ respectively for $t \in T$. $\bold{p}_t$ is the probability of target $t$ to be protected by the defender and $\bold{q}_t(\bold{p},\xi)$ is the probability of target $t$ being attacked by the attacker with feature $\xi$. \citep{1499829}. The two-player SSG has been extended to a coalitional security game \citep{guo2016coalitional} or single leader multiple follower SSG by using a cardinal function of agent utilities \citep{9722864}.
\subsection{Targets for Competency Self-assessment}
Traditionally, the performance of the autonomous agents in MARL can be evaluated using reward signal such as Bellman equation \citep{Uther2010}. \citet{arxiv.2101.05507} proposes a novel technique for testing the robustness of MARL agents where ``unit tests" are designed to gauge the agents' abilities to solve specific tasks. A Strong Stackelberg Equilibrium (SSE), where the attacker breaks ties in the best response set in favor of the defender, is the standard solution concept for SSGs \citep{von2004leadership} due to no guarantees about the existence of a Weak Stackelberg Equilibrium (WSE) \citep{conitzer2006computing}. Even the SSE may not be applicable for security games, as the defender may not induce the attacker to select a preferred action with an infinitesimal change in their policy due to resource assignment constraints. \citet{guo2019inducibility} proposes the inducible Stackelberg equilibrium (ISE), defining an inducible target that serves as the lower bound of the defender's utility guarantees. SSGs involve targets that the attackers attempt to gain control over and the defenders protect from the attackers \citep{kiekintveld2009computing, sinha2018stackelberg, wang2019using}. The control of targets determines the winner, consequently determining the success of policies in autonomous systems that help defenders to win. This motivates future work to develop a solution concept for SSGs with the notion of targets that can be applied to RL.
\section{Modeling SSGs in Reinforcement Learning}
\subsection{Markov Decision Process}
Markov Decision Processes (MDPs) are described by a tuple of $(S,A,P,R)$ where $S$ is the set of states, $A$ is the set of actions, $P:S \times A \rightarrow \Pi (S)$ is the state-transition function where $P(s'|s,a)$ is the probability of transitioning from state $s$ to $s'$ given action $a$, and $R:S \times A \rightarrow \mathbb{R}$ is the reward function where $R(s,a)$ is the reward of action $a$ in state $s$ \citep{Bel}.
For a sequential stochastic SSG with one leader (defender) and one follower (attacker), \citep{https://doi.org/10.48550/arxiv.2005.11853} proposes the Markov Perfect Stackelberg Equilibrium (MPSE), which computes a Markov equilibrium in linear time from a Stackelberg equilibrium in double exponential time using sequential decomposition, and applies it to a MDP. A model-free RL algorithm motivated by Expected Sarsa computes the optimal MPSE strategies for the defender and the attacker, where the defender maximizes its returns based on the knowledge that the attacker is strategizing to play the best response to the defender's strategy.
\begin{comment}
\subsubsection{Uncertainty in MDPs}
The transition probabilities in MDPs can be uncertain due to a lack of knowledge about true transition leading to uncertain rewards as formulated in Uncertain Markov Decision Process(UMDP) \citep{NIPS2012_ce5140df,Rigter_Lacerda_Hawes_2021}. \citet{pmlr-v161-xu21a} models SSGs as UMDPs using double oracle and deep deterministic policy gradient (DDPG) to find optimal defense strategy against poachers while maximizing regret.
\end{comment}
\begin{comment}
Papers modeling SSG as MDP take a simplistic view of the game without assessing observability.
NEED TO UPDATE
\citet{https://doi.org/10.48550/arxiv.2005.11853} applies the idea of computing Markov equilibrium in linear time from Stackelberg equilibrium in double exponential time to a Markov Decision Process referred to as the Markov Perfect Stackelberg Equilibrium (MPSE). \citet{Klma2016MarkovSG} applies MDP to a 2D grid game with 2 non-cooperative players.
\end{comment}
\begin{comment}
WE WILL COMMENT OUT UMDP FOR AAAI PAPER AS WE WILL INCLUDE IT UNDER MDP
\subsection{Uncertain Markov Decision Process}
Uncertain Markov Decision Processes (UMDPs) capture the uncertainty caused by the transition probabilities. It is defined as a set of tuple $(S,s_0,A,T,R)$ where $S
$ is the set of state, $s_0$ is the initial state, $A$ is the set of actions, $T={T_1,...T_{|\xi|}}$ is the set of uncertain transition functions and $R={R_1,...R_{|\xi|}}$ is the set of uncertain reward functions. A sample of model uncertainty is defined as $\xi_q=(T_q,R_q)$ where $T_q \in T$ and $R_q \in R$\cite{NIPS2012_ce5140df,Rigter_Lacerda_Hawes_2021}.
Papers model SSGs as UMDPs by introducing uncertainty in observations. \citet{pmlr-v161-xu21a} uses a double oracle and a deep deterministic policy gradient (DDPG) to find the optimal strategy to defend against poachers while maximizing regret.
\end{comment}
\subsection{Partially Observable Markov Decision Process}
Partially Observable Markov Decision Processes (POMDPs) extend the MDP's definition to $(S,A,P,R,\Omega,O)$ where $\Omega$ is the set of observations and $O:S \times A \rightarrow \Pi (\Omega)$ is the observation function where $O(o|s',a)$ is the probability of the agent observing $o$ after action $a$ landing in state $s'$ \citep{KAELBLING199899}.
\citet{ALCANTARAJIMENEZ2020106695} models SSGs as POMDPs where agents cannot access the full information regarding the state. \citet{8753973} finds the optimal defender policies with policy gradient in a partially observable cooperative RL framework. \citet{DBLP:journals/corr/abs-2012-10389} uses Double Deep Q Learning (DDQN) to compute allocation and patrolling strategies with drones for SSGs with partial observability.
\subsection{Dec-Partially Observable Markov Decision Process}
Decentralized Partially Observable Markov Decision Processes (Dec-POMDPs) generalize POMDPs as $([N],S,A_{i \in [N]},P,R,\Omega_{i \in [N]},O_{i \in [N]}))$. Considering an $m$-sized subset of $N$ agents who can only partially observe the states, Dec-POMDPs update the set of actions $A_i$ for agent $i$, the transition probabilities $P(s'|s,a_1,...,a_m)$ with $[1,m] \subset [N]$, the joint reward $R(s,a_1,...,a_m)$, the set of observations $\Omega_i$ for agent $i$, the observation function $O_i:S \times A_i \rightarrow \Pi (\Omega_i)$ with observation probabilities $O(o_1,...,o_m|a_1,...,a_m,s')$ that denotes the set of agents $i=1...m$ observing $(o_1,...,o_m)$ after a tuple of actions $(a_1,...,a_m)$ landing in $s'$. Dec-POMDPs formulate SSGs in multi-agent RL by modeling decentralized control over agents \cite{10.5555/2073946.2073951}.
\subsection{Partially Observable Stochastic Games}
Partially Observable Stochastic Games (POSGs) generalize from Dec-POMDPs to $([N],S,A_{i \in [N]},P,R_{i \in [N]},\Omega_{i \in [N]},O_{i \in [N]})$.
It defines reward functions for each agent $i$ as $R_i:S \times \prod_{i \in [N]}A_i \rightarrow \mathbb{R}$.
POSGs formulate the multi-agent environment by simultaneous stepping where all agents step, observe, and are rewarded together \citep{10.5555/1597148.1597262,https://doi.org/10.48550/arxiv.2009.14471}.
\section{Target Representation to Assess RL for SSGs}
Targets are important in SSGs, signifying the essential component of security: Attackers try to gain control from defenders while defenders protect targets from attackers. We analyze how targets are modeled in RL literature for SSGs.
\subsection{Targets as a Part of State}
\citet{8753973} defines targets to be a part of the state, while the objectives for the defenders and attackers are to protect and attack the targets respectively given a state. However, targets can be moved from one state to another \citep{wang2019using}, either as a result of agent actions or due to stochasticity. Existing research work applying repeated SSGs with imperfect information in RL \citep{ALCANTARAJIMENEZ2020106695} considers the targets to satisfy Markov and complex physical constraints where the games' strategies evolve around patrolling the targets which are fixed locations on a map. Likewise, the learning algorithms to solve security games consider the targets to be nodes or cells in a grid-world state space where vulnerable resources are located \citep{Klma2016MarkovSG, AAAIW1817362, Wang_Shi_Yu_Wu_Singh_Joppa_Fang_2019, DBLP:journals/corr/abs-2012-10389}.
These proposed algorithms do not define targets explicitly, which should be done for the solution of ISE to hold as defined before.
\subsection{Targets as a Part of Strategy}
\citet{clempner2022learning} takes a different approach to define the set of full strategy profiles as $X \times Y =(x^1,...,x^n,y^{n+1},...,y^m)$. The defenders choose a strategy $x^\delta \in X$ and attackers choose a strategy $y^\alpha \in Y$ after observing $x$, implying targets as a part of the strategy. This approach relies on the definition that the defender strategy is a probability distribution over a set of actions that protect a limited number of targets and the attacker strategy is a probability distribution over a set of actions that attack a limited number of targets. However, targets are not necessarily associated with agent strategies as they are resources in SSGs.
\begin{comment}
(INDUCIBLE STACKELBERG EQUILIBRIUM JUSTIFICATION AS A SEPARATE SECTION/PARAGRAPH HERE. WEAK DEFENSE AS OF NOW. MAY HAVE TO REWRITE).
\citet{guo2019inducibility} proposes the inducible Stackelberg equilibrium (ISE)
based on the idea of an inducible target that serves as the lower bound of the defender's utility guarantees. Stackelberg security games and security games in general involve the idea of targets which are resources that the attackers tries to gain control from the defender and the defender protects from the attacker \citep{kiekintveld2009computing, sinha2018stackelberg, wang2019using}. This motivates future work to develop a solution concept for stackelberg security games with the notion of targets in the domain of reinforcement learning as control of targets by the attacker implies that the game is lost while the opposite implies a defender's win.
\end{comment}
\begin{comment}
SECTION BELOW SHOULD BE COMMENTED ENTIRELY AS ARUNESH SINHA 2022 PAPER DOES NOT USE THE SSG DEFINITION SEPARATELY IN RL. WE ARE PROPOSING THAT AND WE SHOULD KEEP THAT IDEA TO US TILL OUR ICLR PAPER NEXT MONTH. COMMENT THIS WHEN I TELL YOU GUYS TO.
\subsection{Targets as a Separated Set}
There are RL algorithms adapted for application in SSGs where the targets are considered separately as an input \citep{kar2016comparing}. However these algorithms can only strategize for the defender's policies and will need to be extended to multi-agent RL for understanding optimal attacker policies also.
\citet{9668430} describes targets as a separated set, $N$, and an action $s$ is an allocation of resources $K$ over the set of targets $N$.
This form of definition most accurately reflects the proper definition of targets in SSG. However, targets as a separated set contradicts the existing modeling of SSG with MDP, POMDP, Dec-POMDP, and POSG where the tuple of sets do not leave room for definition of targets. If targets were to be modeled with a independent set, a new modeling of SSG is needed.
\end{comment}
\begin{comment}
\subsection{DO NOT WRITE BELOW 2 SECTIONS}
POINT OUT PAPERS 1ST THERE. THEN I'LL DECIDE.
\subsection{Targets as Actions}
I remember some papers saying that. Mention and cite and give why they cannot be actions from my weekly meeting notes.
\subsection{Targets as Rewards}
I remember some papers saying that. Mention and cite and give why they cannot be rewards (utilities are separate from targets in SSGs) from my weekly meeting notes.
\end{comment}
\subsection{Challenge of No Explicit Definition of Targets}
Existing literature in RL for SSGs has not modeled targets separately. Some papers modeling SSG as MDP \citep{https://doi.org/10.48550/arxiv.2005.11853, Klma2016MarkovSG} or POMDP \citep{ALCANTARAJIMENEZ2020106695} lack an explicit definition of targets. \citet{7799111, TREJO201835, CLEMPNER2022104703} model SSGs as controllable Markov chains without considering target resources while adapting strategies against dynamic behavioral models of attackers. Given the significance of targets, not including its explicit definition introduces obscurity in modeling the payoff function which subsequently leads to ambiguity in the RL reward function.
\begin{comment}
\section{SAPTARASHMI}
For a sequential stochastic Stackelberg security game with one leader (defender) and one follower (attacker), \citep{https://doi.org/10.48550/arxiv.2005.11853} applies the idea of computing Markov equilibrium in linear time from Stackelberg equilibrium in double exponential time to a Markov Decision Process referred to as the Markov Perfect Stackelberg Equilibrium (MPSE). A model-free RL algorithm motivated from Expected Sarsa computes the optimal MPSE strategies for the defender and the attacker with the defender maximizing its own returns based on the knowledge that the attacker is strategizing to play the best response to the defender's strategy.
However, Strong Stackelberg Equilibrium (SSE), where the attacker (follower) breaks ties in the best response set by selecting the best response to the defender, is considered to be the standard solution concept for Stackelberg security games \citep{von2004leadership} due to no guarantees about the existence of Weak Stackelberg Equilibrium (WSE) \citep{conitzer2006computing} which has not been addressed in the \citep{https://doi.org/10.48550/arxiv.2005.11853} paper.
Even the SSE may not be applicable for security games as the defender (leader) may not induce the attacker (follower) to select a preferred action with an infinitesimal change in their policy due to resource assignment
constraints. \citet{guo2019inducibility} proposes the inducible Stackelberg equilibrium (ISE)
based on the idea of an inducible target that serves as the lower bound of the defender's utility guarantees. Stackelberg security games and security games in general involve the idea of targets which are resources that the attackers tries to gain control from the defender and the defender protects from the attacker \citep{kiekintveld2009computing, sinha2018stackelberg, wang2019using}. This motivates future work to develop a solution concept for stackelberg security games with the notion of targets in the domain of reinforcement learning. Control of targets by the attacker implies that the game is lost while the opposite implies a defender's win.
Existing research work applying repeated stackelberg security games with imperfect information in reinforcement learning \citep{ALCANTARAJIMENEZ2020106695} consider the targets to satisfy Markov and complex physical constraints where the games' strategies evolve around patrolling the targets. Likewise the learning algorithms to solve security games consider the targets to be nodes in the state space \citep{Klma2016MarkovSG}. The algorithms proposed here do not define targets explicitly which should be done for the solution of ISE to hold here as defined before. Also targets can be moved from one state to another by attackers \citep{wang2019using} demonstrating the control of agents on targets which is not captured in this modeling.
There are reinforcement learning algorithms adapted for application in Stackelberg security games where the targets are considered separately as an input \citep{kar2016comparing}. However these algorithms can only strategize for the defender's policies and will need to be extended to multi-agent RL for understanding optimal attacker policies also.
\end{comment}
\subsection{Abstracting Targets}
In practice, RL algorithm would choose a policy that maximizes expected rewards over a highly randomized one. If we can model the embedded SSGs with targets set, resources constraints, and utilities, the game can be solved prior to learning policies to implement the winning strategy. Moreover, low-level decision control in MARL setting need not to be confined to GT, SSGs can be solved with better time and sample complexity by abstracting the control problem.
\section{Future Work}
Current literature in Reinforcement Learning (RL) to solve Stackelberg security games either ignores targets or considers them to be a state or strategy which does not reflect the solution concept of these games. Given the limitations, it may be beneficial to define the set of targets independent of existing parameters to learn better policies in RL. There are RL algorithms adapted for application in Stackelberg security games where the targets are considered separately as an input \citep{kar2016comparing} to strategize for the defender's policies. These algorithms will need to be extended to multi-agent RL for understanding optimal attacker policies as well.
\begin{comment}
There are reinforcement learning algorithms adapted for application in Stackelberg security games where the targets are considered separately as an input \citep{kar2016comparing}. However these algorithms can only strategize for the defender's policies and will need to be extended to multi-agent RL for understanding optimal attacker policies also.
\citet{9668430} describes targets as a separated set, $N$, and an action $s$ is an allocation of resources $K$ over the set of targets $N$.
This form of definition most accurately reflects the proper definition of targets in SSG. However, targets as a separated set contradicts the existing modeling of SSG with MDP, POMDP, Dec-POMDP, and POSG where the tuple of sets do not leave room for definition of targets. If targets were to be modeled with a independent set, a new modeling of SSG is needed.
\end{comment}
\begin{comment}
\section{Papers}
\subsubsection{12 Ethan} \citep{7799111}
The overall RL architecture includes: adaptive learning architecture and the actor critic architecture
The method used is a regularized method for proximal type for solving equilibrium problems in a Hilbert space. Main goal of the Adaptive Primary Learning architecture is to accelerate the reinforcement learning process. The Actor-Critic architecture is a temporal-difference method responsible for evaluating the new state. It also determines if rewards are better or worse than expected. Formulation of the game is considered a nonlinear programming problem for finding the Stackelberg/Nash equilibrium point based on cost-functions. Cost-functions are strictly convex and differentiable on the corresponding sets. Two-Player stackelberg game are analyzed as a class of ergodic controllable finite Markov chains using the extraproximal method.
\subsection{13 Ethan}
\cite{TREJO201835}
\begin{itemize}
\item Imitative deception, when the attacker pretends to have a different payoff
\item It is assuming his true payoff is unknown to the defender.
\item The attacker will always want to find an optimal deceptive payoff so that it maximizes the attacker’s true utility
\item The optimal strategy for the defender is to play the MaxMin regardless of the attacker’s strategy
\item Attacker deception can be viewed as a type of causative attack to the defender’s learning algorithm
\item In security games, the attacker will always pretend to be competitive, regardless of the true payoff he possesses. (special property of security games not SG)
\item Using 2 types of constraints results in a formula called Mixed Integer Linear Program
\end{itemize}
\subsection{14 Joshua}
\par
\begin{itemize}
\item A partially observable markov decision process (POMDP) is defined
\item Two oracles: agent and nature
\item Agent oracle uses deep deterministic policy gradient (DDPG) to maximize the reward for the defender
\item Nature oracle alternates between using DDPG for optimizing the defender reward, maximizing regret, and doing both
\item The mixed nash equilibrium is solved via the support enumeration algorithm
\item The oracles aren't perfect, so perturbation is used to increase the likelihood of a good strategy being formed
\item Bad strategies being added have a minimal effect on computational complexity
\item A poacher is more likely to attack an area near where there is increased patrol, and less likely to attack an area where there is increased patrol (displacement effect)
\item This was one of the first algorithms to take into account both uncertainty and robustness, and as a result, there is not much to compare it to
\end{itemize}
\subsection{15 Joshua}
\par
\begin{itemize}
\item An uncertain markov decision process (UMDP) is defined
\item Two stages: allocation and patrolling
\item In allocation stage, defender places drones and ranges to the environment, and attacker places attackers
\item In patrolling stage, defenders try to protect targets while attackers try to attack targets
\item If a drone is in same space as attacker, it can scare the attacker into fleeing or notify the park agent to apprehend
\item Uncertainty is incorporated, so the drone might not know if their reading is correct (they might have a false positive or negative)
\item Patrols apprehend attackers in their space
\item Defenders gain a reward if the attacker is caught, nothing if they flee, and a penalty based on the animal density of the target attacked
\item Drones also gain a reward for notifying or scaring in a space with an attacker and a penalty for doing so in a space without an attacker
\item Rewards and penalties are cumulative
\item CombSGPO, the algorithm, computes the strategy first, then allocates
\item The attacker tries to go near the spaces with the most animals while also trying to be far away from the defenders, giving equal priority to both
\item Double Deep Q Learning (DDQN) is used to compute the patrolling strategies
\item DDQN is trained by the Centralized Training and Decentralized Execution (CTDE) framework
\item A gradient based approximation, and the policy is split up into component acting in embeddings and one that turns these embeddings into actions is used to find the nash equilibrium for the allocation stage
\item Random allocations are generated and the autoencoder learns the embeddings
\item The strategies are parameterized by neural networks
\item CombSGPO was compared to OptGradFP and GuardSS and appeared to have lower variance and higher win rate; attackers tended to attack one corner only unlike in OptGradFP or GuardSS
\end{itemize}
\subsection{16 Philip} \citep{Wang_Shi_Yu_Wu_Singh_Joppa_Fang_2019}
\begin{itemize}
\item PSRO where NE is fixed for one agent while the best response for the other agent is calculated using deep Q-networking (DQN) to determine next iteration
\item PSRO not realistic as agents don’t always choose the best response
\item Randomized starting strategies makes PSRO not time efficient
\item Targets defined as states because they are the grid cells
\item Each grid having a different animal density
\item Rewards for attacker are catching an animal in its snare
\item Rewards for defender is removing attacker snares and catching attacker
\item DeDOL algorithm like PSRO with parameterized random walk policy, random sweeping, exploration and termination, and local modes
\item MDPs are used for defining the agents
\end{itemize}
\subsection{17 Philip} \citep{AAAIW1817362}
\begin{itemize}
\item Targets defined as grid cells, each grid having a different animal density
\item Positive reward for attacker when catching an animal
\item Negative reward for attacker when encountering a defender on patrol
\item Partial observability (agents can only see the grid they are in
\item Training best response DQN policy against a new opponent isn’t time efficient
\end{itemize}
\subsection{18 Ethan}
\begin{itemize}
\item Security game is a simplified problem of resource allocation
\item Defenders have limited amount of resources of targets to reduce the overall loss
\item A Bayesian SSG where the participants are limited to observing private information via a controlled Markov Process
\item Disparities in defender’s interest create a dilemma in decision making
\item In this model, defenders will secretly observe their current type and send an equilibrium message
\item The equilibrium message will pick an action based on an allocation rule.
\item At the same time, attackers will send a message that results in an allocation.
\item Attackers and defenders observe their behavior in a repeated game restricted to Markov Process
\item Bayesian Learning is an approach to address the exploration-exploitation trade off
\item It allows past information to be included into algorithms as probabilistic distributions.
\item Final optimal defense-attack strategies are chosen based on the Lagrange regularization model.
\item Defender’s and attackers incomplete information results in improving the defense efforts and augmenting the defense effectiveness.
\item Potential future work could include study of an extremum seeking approach
\item Proposing a new proximal algorithm could accelerate the solution of the problem.
\end{itemize}
\subsection{20 Philip} \citep{10.5555/3306127.3331719}
\begin{itemize}
\item ML Model Inputs to use historical records to create spatio-temporal data points that are used to train a machine learning model
\item MINION-sm builds its own implicit model for the attacker
\item Targets are the grid cells
\item ML Model Outputs to generate the best patrol strategy for a defender
\item MINION-sm also takes into account spatio-temporal scheduling when planning patrols for defenders
\end{itemize}
\subsection{21 Joshua}
\par
\begin{itemize}
\item Defender is the leader, attackers are the followers
\item Each individual follower does not take into account other followers' actions, only those of them and the leader
\item The leader, being individual, takes into account all players' actions
\item A Misperception Strong Stackelberg Equilibrium (MSSE) or Deception Strong Stackelberg Equilibrium (DSSE) can become a Hyper Nash Equilibrium (HNE)
\item Some examples of SLMF SSGs are counterterrorism, or defending against a denial of service (DoS) attack
\item Misperception is when wrong information is found; this is similar to the uncertainty used by the drones in CombSGPO
\item Deception is when wrong information is intentionally given by the leader to the followers
\item A second-level hypergame is a hypergame where at least one player knows that different games are being played; this would be the leader in this scenario since they can give wrong information
\item A first-level hypergame is a hypergame where no player knows that different games are being played
\item A Hyper Nash Equilibrium is a Nash Equilibrium for a hypergame, which is each player's subjective ideal strategy
\item This paper is all theory; there is no algorithm proposed to find a Hyper Nash Equilibrium or solve a second-level hypergame or SLMF SSG.
\end{itemize}
\end{comment}
| {'timestamp': '2022-12-01T02:18:38', 'yymm': '2211', 'arxiv_id': '2211.17132', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17132'} | arxiv |
\section*{Introduction}
Artificial intelligence (AI) has been gradually changing medicine throughout the last few years. As exhibited by Bohr \& Memarzadeh \cite{bohr_chapter_nodate}, it can impact all areas of healthcare by enabling more precise disease detection, image analysis, patient monitoring, more efficient self-administration medication among others\cite{fouad_analyzing_2020}. Combining AI with health monitoring devices can significantly decrease healthcare costs\cite{bohr_chapter_nodate}. In particular, deep learning (DL) can help find hidden correlations and patterns using advanced machine-learning algorithms, including artificial neural networks (ANN)\cite{rawat_optimized_2022,jha_artificial_2022}. Thereby, deep machine learning can be used to achieve earlier recognition of complex patterns in a patient's data in order to detect anomalies and correlate symptoms \& diseases. This new branch of medicine can make it more accessible and affordable \cite{uwaoma_building_2021,mohd_ariff_establish_2019}. Exploiting machine learning, we seek to demonstrate that combinations of lower-cost \& lower-precision sensors can potentially become as precise as any cutting-edge healthcare technology, reducing costs and providing a more universal access to healthcare\cite{bohr_chapter_nodate}. Building on this philosophy, this report establishes how a deep learning approach can yield more accurate data predictions from an ultra low-cost temperature sensors array.
\subsection*{Temperature Sensors}
\noindent Temperature sensors come in many designs and materials, according to their target application. Beyond cost, the key features to consider are reliability, response time, accuracy, sensitivity, temperature range and, for skin temperature, wearability.\cite{childs_review_2000} They can include thermocouples, resistance temperature detectors (RTDs), thermistors and semiconductor sensors, each with their own advantages and disadvantages. \cite{khan_wearable_2021,rai_temperature_2007,tranca_precision_2018}. Detailed specifications for these sensors are found in the literature \cite{childs_review_2000,rai_temperature_2007}. For this project, we use negative temperature coefficient (NTC) thermistors and semiconductor-based integrated circuits (ICs). The NTC sensors measure change in resistance. The temperature is then computed with the Steinhart-Hart equation given as\cite{noauthor_temperature_nodate},
\begin{equation}\hspace{6cm}\frac{1}{T} = A + B\ln{R} + C(\ln{R})^{3}\end{equation}
\noindent where T is temperature in Kelvin, R is the thermistor resistance and A,B,C are constants specific to the sensor device, usually provided by manufacturers\cite{noauthor_temperature_nodate}. These are analog sensors where the output is a continuous electric signal that is converted to temperature. In contrast, integrated circuits (IC)-based sensors use bipolar transistors to do the measurements. The specific IC sensor chosen for this work also includes an analog-to-digital converter. As such, the output signal from the sensor is a non-continuous temperature reading.\\
\subsection*{Temperature in Medicine}
\noindent Body temperature is one of the key vital signs for health assessment. The normal temperature may slightly vary between individuals, but is considered normal when at 37$\degree$C\cite{ogoina_fever_2011}. However, the temperature will be different depending on the part of the body where it is measured, the ambient temperature and the subject's activities. Extremities tend to be colder\cite{ganong_regulation_2012}. The human body has built-in temperature regulation mechanisms in order to maintain its temperature at 37$\degree$C. These mechanisms can be cold-activated like shivering, hunger and goosebumps, or they can be heat-activated like sweating and accelerated breathing\cite{ganong_regulation_2012}. As such, temperature measurements are especially useful to detect infections and inflammations, but more generally for immune response detection. Bacterial discharge and virus load cause fever and can also be detected through a temperature increase\cite{huan_wearable_2022,ogoina_fever_2011}. Using wearable devices, it is now possible to continuously monitor several health indicators and vital signs outside the clinics\cite{dunn_wearable_2021,huan_wearable_2022}. For example, temperature imaging can be used to verify blood flow in order to detect small temperature changes on patients with vascular disorders\cite{philip_infrared_2009}. Another application is to monitor disease and treatment evolution through temperature, for example in pneumonia patients\cite{qu_low-cost_2022} or high-risk diabetic patients afflicted with foot ulcerations\cite{armstrong_skin_2007}. Furthermore, temperature can be used to distinguish between superficial and deep skin burns, but also to monitor and predict the skin regeneration and healing processes\cite{ganon_contribution_2020}. It is also used for the monitoring of infected wounds\cite{pusta_wearable_2021,zhang_flexible_2021}. Currently, thermal imaging is almost exclusively used in clinical settings. Although it offers many advantages as a simple non-invasive approach, its main disadvantage is that it works better directly on the skin\cite{qu_low-cost_2022}. This can cause accessibility, comfort and privacy issues, depending on the affected area. Furthermore, it can only be done in a medical environment. In contrast, temperature sensors can be easily implemented in wearable devices such as watches\cite{huan_wearable_2022}, patches\cite{nakata_wearable_2017} and even face masks\cite{laurino_innovative_2022} to be even less intrusive and allow to monitor the patients continuously. Although this can bring calibration and accuracy issues, we intend for our DL model to improve wearable devices and learn to make-up for these intrinsic issues.
\subsection*{Machine Learning}
\noindent The lower accuracies and precisions of low-cost printed sensors usually stem from less reliable designs, coupled with cheaper materials and fabrication techniques. As such, an interesting idea would be to exploit machine learning algorithms on a statistically-significant number of those low-cost sensors (array) in order to potentially learn to compensate for those design and fabrication flaws.
\noindent So far, only a handful of research groups have reported significant progress in this exciting new approach to further enhance the performances of inkjet printed sensors beyond their physical limits. In 2019, an array of 20 printed sensors coupled with a two-stage machine learning approach produced an artificial nose used for food classification\cite{schroeder_chemiresistive_2019}. There, a featurized-random forest or k-nearest neighbor classification (with similar accuracy) is first used for classification into food categories (ex: cheese, liquor, oil). Then, a combinatorial selector scan is used to class the specific food item within its category (ex: rum, vodka, whiskey, gin, and tequila as liquors) \cite{schroeder_chemiresistive_2019}. In 2020, researchers achieved sign-to-speech translation using machine-learning-assisted stretchable sensor arrays\cite{zhou_sign--speech_2020}. Meanwhile, biomolecular \& protein sensing \cite{pandit_machine_2019,behera_machine_2021}, as well as gases \& pollutant mixtures detection \cite{khan_nanowire-based_2020,thorson_using_2019} were also demonstrated using low-cost printed sensors with machine learning treatment. In 2020, a multi-disciplinary team developed a smartphone-based DNA diagnostic tool for malaria used in rural Uganda in order to also improve connectivity between such communities and centralized medical facilities \cite{guo_smartphone-based_2021}. They used low-cost paper-based microfluidic diagnostic test and had a disease detection accuracy over 98\% \cite{guo_smartphone-based_2021}. In all those cases, the idea was ultimately to equip these low-cost sensor arrays with some intelligence in order to perform a certain \textit{classification} task\cite{schroeder_chemiresistive_2019,zhou_sign--speech_2020,pandit_machine_2019,behera_machine_2021,khan_nanowire-based_2020,thorson_using_2019,tsakanikas_machine_2020}.
\noindent This work demonstrates that low-cost and low-precision temperature sensors can be used in combination with deep machine learning frameworks to yield more precise and more accurate temperature predictions. This opens a wide range of applications in the medical field, where sensors could be placed in different body parts, but maybe still predict the body temperature.
\section*{Materials and Methods}
\subsection*{Data Collection}
\subsubsection*{Materials}
In order to create our sensor array, we chose two types of low-cost temperature sensors. We used 16 digital temperature sensors and 16 analog temperature sensors, all with accuracies between 0.5 to 2.0$^{\circ}$C.
\noindent To collect the data from our sensors, we use an Arduino Mega2650\cite{arduino_datasheet_nodate} and Arduino's IDE. The Mega2650 offers 54 digital inputs and 16 analog inputs, which is sufficient to connect all our sensors to the microcontroller. It operates at 5V and 16 MHz frequency.
\subsubsection*{Methods}
The sensors are mounted on an IKA C-MAG HS 7 control hotplate \cite{ika_datasheet_nodate} with thermal paste to ensure conductivity and fixed with thermally-conductive tape, using the configurations shown in Figures 1 \& 2. The sensors are placed in a 4x8 array, covering the center of the plate as indicated in Figure 1(a). Two (2) rows consist of the digital sensors and two (2) rows for the analog sensors. This specific configuraton is only chosen to facilitate wire-management and data-collection.
\noindent Using two types of sensors helps diversify our dataset, while providing enough data for a meaningful distribution (see Supplementary Information section to compare both sensor types). All 32 sensors are connected through wires to the Arduino microcontroller as shown in Figure 1. There, Figure 1(a) shows a representation of the experimental setup condition. The approximate placement of the 32 low-cost temperature sensors is schematically represented atop a thermal image of the hotplate when set at 50$\degree$C. From the thermal image acquired using a FLIR-One infrared camera, it is clear that the temperature is not uniform everywhere on the hotplate. This configuration was chosen on purpose to represent the human body, where the temperature can fluctuate quite a bit from one location to another. We cycled the hotplate's set-temperature from 30 to 45$\degree$C, with increments of 1$\degree$C as a staircase signal. The heating plate's accuracy is $\pm 0.15\degree$C according to specifications. As the temperature varies quite significantly over the surface, this parameter isn't really meaningful in this study. Instead, we want our model to learn to predict the hotplate's set temperature with the highest precision. Similarly, the body temperature can also vary significantly from one point to another. When measured orally, this temperature is established as true, whereas elsewhere it may be different. Thus, we want our model learn to predict the established temperature of the plate, even if it is changing wildly depending on the position of the sensors on the hotplate.
\noindent Figure 1(b) shows the circuit on the Arduino Mega2650. For each degree measurement, we waited for two minutes to make sure that the hotplate's temperature is stable before collecting the sensors' readings each 1.5 seconds for four minutes using the Arduino. Afterwards, 50 random vectors were chosen from the entire sample. Thus, our dataset consists of 50 vectors of 32 components for each temperature degree, for a total of 800 vectors. All vectors are then labeled according to the plate's set temperature and accuracy.
\begin{figure}[h]
\centering
\begin{subfigure}[b]{0.45\textwidth}
\centering
\includegraphics[width=5cm]{figures/thermalavsd.PNG}
\caption{}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.45\textwidth}
\centering
\includegraphics[width=\textwidth]{figures/schema.jpg}
\caption{}
\end{subfigure}
\caption{(a) Placement of the 32 low-cost temperature sensors schematically represented atop a thermal image of the hotplate when set at 50$\degree$C. The two rows bounded in the black box are analog sensors, where as the green box contains digital sensors. (b) Schematic of our circuit. Only four sensors of each type are shown to simplify the figure.}
\label{fig:three graphs}
\end{figure}
\subsection*{Neural Network}
\subsubsection*{Methods}
A feed-forward artificial neural network is a deep learning algorithm generally using large quantities of data to learn to recognize hidden patterns in order to make more accurate predictions\cite{li_application_2022}. In this case, we designed a regression model, which predicts an output based off the data you feed it. The architecture of an artificial neural network is composed of interconnected neuron layers. It also contains an input layer, which forwards the data to the hidden layers for computational purpose. The information is then spread to the output layer, making a final prediction.
Here, we used a supervised training method.\cite{pattanayak_pro_nodate} To do so, the data set is randomly split in two subsets. 80\% went to the training set, while the remaining 20\% composed the validation set. To design our model, we use TensorFlow's module Keras\cite{chollet_deep_2021}. We chose a three-layer deep neural network (DNN) shown in Figure 3. Its hidden layer has 20 neurons and all are activated with an hyperbolic tangent function $(\tanh(x)=\frac{e^{x} - e^{-x}}{e^{x} + e^{-x}})$. We chose the Adam optimizer with a 0.01 learning rate. The computed loss function for our regression is the mean squared error $(MSE =\frac{1}{n} \sum_{j=1}^n (Y_{j}-\hat{Y}_{j})^2 )$. We obtained a minimal loss by training the data set with 300 epochs. (See Supplementary Information for optimization details on the algorithm)
\begin{figure}[h]
\centering
\includegraphics[width=0.60\textwidth]{figures/graphe.jpg}
\caption{Optimized deep neural network (DNN) architecture used to learn to predict the (set) temperature from the read-out data of our 4 x 8 array of low-cost and low-accuracy temperature sensors.}
\label{fig:my_label}
\end{figure}
\noindent In this project, the model trains itself with 640 temperature vectors composed from the readings of the 32 sensors and labelled with the set temperature of the hotplate. Using this training set, the model learns to predict the set temperature of the hotplate (labels) from the patterns and features of the array. Once the model is trained, we evaluate its performances using the test vectors and evaluate its set-temperature predictions from the sensors' data. The predictions according to the set temperature and compared with the sensors' readings are shown in Figure 4.
\section*{Results and Discussion}
\noindent As seen in Figure 3, the recorded temperatures fluctuate wildly from one sensor to another and the averaged sensor readings tend to increasingly underestimate the actual (set) temperature as the temperature is increased. For a set temperature of 45$\degree$C, some sensors read temperatures as low as 33$\degree$C. After only a few iterations of training, we observe that the DNN model architecture shown in Figure 3 can predict the actual (set) temperature with a 0.12$\degree$C accuracy using extremely low-quality sensing devices. These results suggest that the DNN learns to compensate extremely well for the poor sensors' precision and accuracy, as well as for the non-homogeneous temperature profile of the plate.
\\
\begin{figure*}[h!]
\centering
\includegraphics[width=0.65\textwidth]{figures/predictionlignemean.png}
\caption{Individual temperature readings from each of the 32 sensors (\textcolor{red}{\textbullet}), mean value of all readings (\textcolor{teal}{\textbullet}) and the model's predictions (\textcolor{blue}{\textbullet}) as a function of the hotplate's set temperature. The dashed blue line indicates the target (set) temperature value.}
\label{fig2}
\end{figure*}
\begin{figure}[h!]
\begin{minipage}{0.45\textwidth}
\includegraphics[height=6cm]{figures/3dheatmap.png}
\end{minipage}
\begin{minipage}{0.1\textwidth}
\includegraphics[height=5cm]{figures/scale.png}
\end{minipage}
\begin{minipage}{0.45\textwidth}
\includegraphics[height=6cm]{figures/heatmapangle.png}
\end{minipage}
\caption{3D heatmaps of our individual sensors' readings with increasing temperature in the black arrow's direction from two (2) different viewpoints. Each dotted line represents the evolution of one sensor. Axes going from 1 to 4 (row) and 1-8 (column) indicate the sensors' individual placement.}
\label{fig}
\end{figure}
\noindent Results from Figure 3 clearly highlight the sensors' large margin for error. The red vertical dotted lines indicate each sensors' readings according to each set temperature. As the set temperature increases, it is clear that lower temperature readings tend to move further from the actual set temperature than the maximal one. As such, the mean value extracted from the 32 sensors increasingly underestimates the set temperature. This increasing margin of error as the temperature rises can be explained by (1) the sensors' low-precision and (2) the non-uniformity of the hotplate's thermal profile for higher temperatures. The blue data points show the model's prediction, which accurately follows the set temperature. The sensors' readings' mean rather follows a logarithmic regression.
\\
\noindent Even if the hotplate's thermal profile becomes non-uniform as the temperature rises, our algorithm still performs very well. This is because the model also learns the behavior of each sensor according to its placement. Figure 4 shows a 3D representation of our 4x8 sensor array as the temperature increases on the hotplate (heatmap) from two (2) different viewpoints. Just like the thermal image of Figure 1, it is clear that some sensors are subjected to different temperatures locally. At 30$\degree$, the whole array is red (lower temperatures), and it then becomes increasingly yellow (higher temperatures) at different rates. It is clear from these results that the temperature is not uniform everywhere on the hotplate. Indeed, this experimental system was selected on purpose in order to accurately mimic the non-uniform temperatures experienced across the human body.
\noindent \begin{minipage}{0.6\textwidth}
As mentioned earlier, the body temperature can vary significantly depending on where the measurement is taken, just like the sensors in our work. However, our model still manages to predict accurately the hotplate's reference (set) temperature, which would be the core body temperature in a clinical setting. Thus, we could place sensors over a patient's body and be able to know the core body temperature. This could also be helpful in creating a heat map of the patient's body. For instance, becomes possible to accurately predict the temperature at point A from a reading at point B, as shown in Figure 5, where the algorithm could predict the oral temperature from the wrist sensor. But most importantly, it helps to get more accurate temperature readings from low-cost sensors. Even though these timely results present an appealing proof-of-concept, this study also represents a strong foundation for future investigations. For example, one could try different types of sensors an/or modify the positioning and shape of the array. We already did a first try of data augmentation and randomized the test set to get an idea of the effect's on the prediction, as discussed in the \textit{Ablation Study} below. The chosen temperature range for this project is convenient for skin temperature measurements, but we could also try to expand it and accommodate the model's behavior in order to target other applications.
\vfill
\end{minipage}
\begin{minipage}{0.4\textwidth}
\centering
\includegraphics[width=0.60\textwidth]{figures/humanmap.png}
\centering
\captionof{figure}{Representation of our model's transition onto the human body}
\label{fig:sample_figure}
\end{minipage}
\subsection*{Ablation Study}
In order to develop the best model for this project, we tried different parameters for the algorithm. This section describes the model's optimization process.
\subsubsection*{Loss and Activation functions }
We compared the results using different loss functions for our regression model. We tried the mean absolute error (Figure 6a) and the mean squared logarithmic error and the root mean squared error (Figure 6b) resulting in loss values of 2.79x10$^{-2}$ and 4.57x10$^{-2}$ respectively. As shown in Figure 6(c), the mean squared error yields significantly better results. Furthermore, the combination of the hyperbolic tangent activation function for both layers results in the best precision.
\begin{figure}[h]
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=.9\linewidth]{figures/logscalemae.png}
\caption{}
\label{fig:sub-first}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=.9\linewidth]{figures/logscalermse.png}
\caption{}
\label{fig:sub-second}
\end{subfigure}\\[1ex]
\begin{subfigure}{\linewidth}
\centering
\includegraphics[width=.45\linewidth]{figures/logscale.png}
\caption{}
\label{fig:sub3}
\end{subfigure}
\caption{Results for different loss functions used to optimize our model in a logarithmic scale. (a) mean absolute error (MAE), (b) root mean squared error (RMSE) and (c) mean squared error (MSE), all with hyperbolic tangent activation function.}
\label{fig:test}
\end{figure}
\begin{figure}[h!]
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=.9\linewidth]{figures/logscale.png}
\caption{}
\label{fig:sub-first}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=.9\linewidth]{figures/logscalerandom.png}
\caption{}
\label{fig:sub-second}
\end{subfigure}
\caption{(a) MSE loss function on logarithmic scale for our model (b) MSE loss function on logarithmic scale for a model trained using a completely randomized data set}
\label{fig:test}
\end{figure}
\subsubsection*{Randomized vectors}
If we shuffle the components of the testing vectors, the algorithm doesn't perform as well. This is because part of the algorithm is also learning the heat profile of the hotplate, as it is intended. For instance, a shuffled test set fed into our model achieves a MSE of 6.58x10$^{-3}$, which is roughly a factor thirty (30$\times$) larger than our best MSE result. This is due to the fact that when shuffling the components of each vector, we mix the heat map of our dataset. Therefore, the model can't rely on that specific property to predict the temperature, and that's why it becomes a bit less precise.
\\
As a result, we also tried to train our model using randomly-shuffled vectors. Each one was randomly shuffled so that the mapping aspect is completely eliminated. The same model computed a 6.97x10$^{-4}$ of the test set, which is only a factor five (5$\times$) higher than our best MSE results. Comparison for both models is shown in Figure 6(c) and (d).
\section*{Conclusion}
While it is important to continue to improve materials and fabrication processes to improve sensors, the impact that artificial intelligence can also have should not be overlooked. This paper clearly demonstrates that machine learning algorithms are a powerful way to rapidly enhance readily-available low-cost sensor performances and to generate heatmaps from low-cost sensor arrays. Research is currently oriented towards implementing some intelligence onto sensor arrays in order to perform classification tasks. We show that applying such deep-learning algorithms to low-cost sensor arrays can also improve their performances. In the future, it will be interesting to try this approach to identify the best designs to measure body temperatures. To do so, researchers will need to consider the sensor's biocompatibility with skin\cite{patel_drawn--skin_2022}. This system has a great potential for medical applications for non-invasive temperature measurements. As it is currently done with biomarkers\cite{pusta_wearable_2021}, such sensor arrays could also be used to monitor inflammatory responses or recovery in burned and wounded patients. The advantage our sensors is that they require no chemical reactions and aren't disposable. Furthermore, the thermal map generated by our model could be helpful to monitor the evolution of wounds and injuries, at much lower costs than current methods.
\newpage
\section*{Materials}
\subsection*{Sensors}
\noindent The DS18B20 IC-based sensor communicates over a 1-Wire bus, which implies it only needs one data line for communication with the microprocessor. Its operating range is between -55$^{\circ}$C and 125$^{\circ}$C. Its accuracy varies between 0.5-2.0$^{\circ}$C, the best obtained for temperatures in a -10 to 85$^{\circ}$C range. The NXRT15WF104FA1B040 sensor is a NTC thermistor with a 100k$\Omega$ resistance at 25$^{\circ}$C. Its operating range is between -40$^{\circ}$C and 125$^{\circ}$C. Its precision varies but stays around 2.0$^{\circ}$C in this range.
\section*{Methods}
\subsection*{Neural Network}
As mentionned in the paper, we tried different parameters for our model in order to get an optimized version. It was clear that the hyperbolic tangent activation function for both layers worked the best. As for the number of epochs, as depicted by Figure 5 in text, the loss is already stable after 100 epochs. Therefore, adding epochs only results in overfitting after approximately 320 epochs. For 600 epochs, we get a 3.47x10$^{-2}$ loss on the test set, which is roughly a factor two hundred (200$\times$) larger than our best MSE result. The step in figure below shows the overfitting.
\begin{figure}[h!]
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=.9\linewidth]{figures/logscale.png}
\caption{}
\label{fig:sub-first}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=.9\linewidth]{figures/logscale600epochs.png}
\caption{}
\label{fig:sub-second}
\end{subfigure}
\caption{(a) MSE loss function on logarithmic scale of our model (b) MSE loss function on logarithmic scale of our model for 600 epochs}
\label{fig:three graphs}
\end{figure}
\noindent Furthermore, we tried adding an extra hidden layer to our model to study the effect. Adding a 12-neuron layer resulted in a 2.27x10$^{-4}$ loss for the test set, which is roughly twice larger than our best MSE result.
\begin{figure}[h!]
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=.9\linewidth]{figures/logscale.png}
\caption{}
\label{fig:sub-first}
\end{subfigure}
\begin{subfigure}{.5\textwidth}
\centering
\includegraphics[width=.9\linewidth]{figures/logscaleextra.png}
\caption{}
\label{fig:sub-second}
\end{subfigure}
\caption{(a) MSE loss function on logarithmic scale of our model (b) MSE loss function on logarithmic scale of our model with extra hidden layer}
\label{fig:three graphs}
\end{figure}
\section*{Results}
For the paper, we trained the model with both types of sensors jointly. Here are the prediction results for the same model, but trained only with the digital readings (yellow) and the analog readings (blue). Their respective prediction are also on the graph.
\begin{figure}[h]
\centering
\includegraphics[width=0.75\textwidth]{figures/anavsdigi.png}
\caption{Independent model's prediction according to temperature sensors' type}
\label{fig:my_label}
\end{figure}
\end{document} | {'timestamp': '2022-12-01T02:18:48', 'yymm': '2211', 'arxiv_id': '2211.17139', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17139'} | arxiv |
\section{Introduction}
Online Social Networks are platforms for people to publicize their ideas and products. This approach, called Viral Marketing, raises the problem of Influence Maximisation (IM), which requires selecting $k$ seed nodes to maximize the information spread in the network. Several approaches have been proposed for IM in recent years, based on local, semi-local, and global structures. Global structure-based approaches are efficient due to their consideration of whole network. They find out core nodes with maximum connectivity to the remaining network. However, in real-world situations, where number of seed nodes is very small, influence gets restricted to only a few sub-groups (or communities) in the network containing the selected core seed nodes. To overcome this, we instead consider community bridge nodes as influential seed nodes due to their connections to a larger number of communities, leading to simultaneous information propagation to these communities. We propose CKS centrality measure, which incorporates community structures and K-shell Decomposition to identify influential spreaders in a network. We define three novel measures: Community K-Shells, Community K-Shell Entropy, and CKS-Score, which qualitatively and quantitatively evaluate connections of a node to various communities.
\section{Proposed Methodology}
\textbf{Obtaining Community K-Shell (CKS):}
Community K-Shell concept incorporates knowledge of information flow in a network. Obtaining CKSs comprises the following steps: identifying community structures using Louvain’s algorithm \citep{louvain}; isolating communities by removing connections between different communities; and passing isolated communities through K-Shell algorithm \citep{kshell} to obtain K-Shell scores particular to the community of each node (i.e., Community K-shell score). The higher the Community K-shell score of a node, the closer it is to the core of the given community.
\textbf{Computing K-Shell Entropy (KSE):}
KSE evaluates connectivity of a node to different regions of a community. We formulate KSE for a node $v$ corresponding to each community $c$ as follows:
\begin{equation}
\label{eq:shells}
\scriptstyle KSE_{v,c} \ = \ - \ \sum_{s = 1}^{shells_{c}} \ K_{s} \ * \ \frac{\eta_{v,s}}{\eta_{v}} \ * \ log(\frac{\eta_{v,s}}{\eta_{v}})
\end{equation}
\begin{equation}
\label{eq:eta}
\scriptstyle \eta_{v} = \sum_{s'=1}^{shells_{c}}\eta_{v,s'}
\end{equation}
where, $\eta_{v,s}$ is number of connections of node $v$ with shell $s$ for a given community, $shells_{c}$ represents the unique CKS in community $c$, and $K_{s}$ represents K\_value of given shell.
Influence of an activated node lasts only till 2-3 hops. Thus, for maximum influence over a given community, connectivity of a node to the community should be well-distributed across all its regions, which also reduces the chances of overlapping influence in a community. This requires a higher KSE score.
Equation \ref{eq:shells} represents the entropy submission over shells of the respective community weighted by the K-Value of the respective shell.\\
\begin{figure*}[t!]
\centering
\includegraphics[width = 0.9\textwidth]{Results.jpg}
\hfill
\caption{Results of our experiments on datasets (a) Twitch, (b) soc-Hamsterster (c) p2p-Gnutella04 (d) email-univ. (1) FIS after IC model simulation with activation probability 0.5. (2) FIS-v-p after IC model simulation with initial spreaders fraction 0.2. (3) ASPL among initial selected seed nodes vs spreaders fraction.}
\label{Results}
\end{figure*}
\textbf{CKS-Score:}
CKS-Score evaluates the overall connectivity of a node to all adjacent communities to which it is connected. It is defined as:
\begin{equation}
\label{eq:comm}
\scriptstyle CKS-Score(v) \ = \ \sum_{c = 1}^{comm} NN_{c} \ * \ KSE_{v,c} \ * \ \eta_{v}
\end{equation}
where, $\eta_{v}$ is number of connections of node $v$ with the respective community as shown in Equation \ref{eq:eta}, $KSE_{v,c}$ represents K-Shell Entropy for node $v$ and community $c$, and $NN_{c}$ represents number of nodes in community $c$.
We compute CKS-Score for each node by considering its KSE values corresponding to each community weighted by the community's size. This ensures a higher score for community bridge nodes connected to the most significant communities.
\section{Experimental Results and Discussion}
We evaluated CKS on four metrics: Final Infected Scale (FIS), Average Shortest Path Length (ASPL), Final infected scale vs Activation Probability (FIS-v-p), and Execution Time. We compared CKS with BC \citep{BC}, CC \citep{CC}, ENC \citep{ENC}, and GLR \citep{GLR} on four real-world datasets\footnotemark[1]: Twitch, soc-Hamsterster, p2p-Gnutella04, and email-univ. We simulated each model 100 times using Independent Cascade \citep{IC}. Infection probability was set to 0.1. Table \ref{ET} and Figure \ref{Results} show our findings. We observed:
\footnotetext[1]{https://networkrepository.com , https://snap.stanford.edu/snap}
\begin{table}[t!]
\centering
\large
\resizebox{\columnwidth}{!}{
\begin{tabular}{c|ccccc}
\hline
\hline
\textbf{Dataset} & \textbf{CKS} & \textbf{ENC} & \textbf{GLR} & \textbf{BC} & \textbf{CC} \\\hline
Twitch & 28.97 & 0.176 & 37.72 & 533.63 & 159.07 \\
soc-Hamsterster & 49.21 & 0.04 & 3.44 & 40.12 & 11.84 \\
p2p-Gnutella04 & 83.21 & 0.19 & 54.41 & 1205.83 & 352.65 \\
email-univ & 0.83 & 0.01 & 0.71 & 10.09 & 1593.18 \\
\hline
\hline
\end{tabular}}
\caption{Execution time for CKS and other approaches.}
\label{ET}
\end{table}
CKS consistently outperformed other core nodes-based approaches on FIS, ASPL, and FIS-v-p, while being reasonably efficient. This confirms our hypothesis that bridge nodes are more influential core nodes.
CKS showed a higher inter-spreader distance than competing approaches, while also having a higher infection rate, leading to much lesser overlap between the influence of spreaders (or \emph{rich club effect}).
\nocite{*}
\fontsize{9pt}{10pt}\selectfont { | {'timestamp': '2022-12-01T02:20:22', 'yymm': '2211', 'arxiv_id': '2211.17200', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17200'} | arxiv |
\section{Conclusion}
We introduced \textit{NeRFInvertor} as a universal method for a single-shot inversion of real images on both static and dynamic NeRF-GAN models. We employed image space supervision to fine-tune NeRF-GANs generator for reducing identity gap, along with explicit and implicit geometrical constraints for removing artifacts from geometry and rendered images in novel views and expressions. Our experiments validate the importance of each component in our method for 3D consistent, ID-preserving, and high-fidelity animation of real face images.
{\small
\bibliographystyle{ieee_fullname}
\section{Method}\label{sec:approach}
In this paper, we present \textit{NeRFInvertor} as a universal NeRF-GAN inversion method to translate a single real image into a NeRF representation.
Given an input image $\textbf{\textit{I}}$,
the goal is to generate novel views or expressions of $\textbf{\textit{I}}$ using a pretrained Nerf-GAN $\mathcal{G}_o$.
To do this, we first find an in-domain latent code\footnote{We optimize latent codes in $\mathcal{Z}$ or $\mathcal{W}$ space ~\cite{Karras2019stylegan2} for different NeRF-GAN models.} capable of generating an image $\textbf{\textit{I}}^o$ as close as possible to the input image.
Given a NeRF-GAN generator $\mathcal{G}_{(\cdot)}$, the image $\textbf{\textit{I}}^{(\cdot)}$ can be synthesized as:
\begin{equation}
\textbf{\textit{I}}^{(\cdot)} = \mathcal{R} (\mathcal{G}_{(\cdot)}(\mathbf{z}, \mathbf{x}), \textbf{\textit{d}}) \ ,
\end{equation}
where $\mathbf{x} \in \mathbb{R}^3$ is the a 3D location, $\mathbf{z}$ denotes a latent code, $\textbf{\textit{d}}\in \mathbb{R}^3$ is the camera pose, and $\mathcal{R}$ is the volume renderer discussed in \cite{max1995optical,mildenhall2021nerf}.
Therefore, the optimized latent code $\textbf{z}_{init}$ can be computed as:
\begin{equation}
\textbf{z}_{init} = \argmin_{\textbf{{z}}} \ \ \mathcal{L}_{perc}(\textbf{\textit{I}}, \textbf{\textit{I}}^o) + \lambda_0 \mathcal{L}_{pix}(\textbf{\textit{I}}, \textbf{\textit{I}}^o) \ ,
\end{equation}
where $\mathcal{L}_{perc}$, $\mathcal{L}_{pix}$ represent perceptual and l2-norm pixel-wise loss functions, respectively.
Usually, there would be a gap between the generated and real images, since the real images are mostly the out-of-domain samples in NeRF-GANs. To solve this problem, we propose a fine-tuning process with novel regularizations in the following sections.
Specifically, we fine-tune the generator with image space loss functions (Sec. \ref{sec:2dloss}) to reduce the identity gap. We also apply an explicit geometrical constraint (Sec. \ref{sec:neiborhood_reg}) and an implicit geometrical regularization (Sec. \ref{sec:image_reg}) to maintain the model’s ability to produce high-quality and 3D-consistent images.
\subsection{Image Space Supervision}\label{sec:2dloss}
Given the optimized latent code $\textbf{z}_{init}$, we fine-tune the generator using image space supervision by pushing the generated image to match the input image in the original view $\textbf{\textit{d}}$.
Denoting the fine-tuned generator as $\mathcal{G}_f$, it takes the optimized latent code $\textbf{z}_{init}$ and a 3D location $\mathbf{x} \in \mathbb{R}^3$ as the inputs and outputs a color $c \in \mathbb{R}^3$ and a volume density $\sigma \in \mathbb{R}^1$ for each location.
For the given view $\textbf{\textit{d}}$, we can then accumulate the colors and densities into a 2D image $\textbf{\textit{I}}^f$. Formally, the image $\textbf{\textit{I}}^f$ can be expressed as:
\begin{equation}
\textbf{\textit{I}}^f = \mathcal{R} (\mathcal{G}_f(\mathbf{z}_{init}, \mathbf{x}), \textbf{\textit{d}})
\end{equation}
We employ the following loss function as the image space supervision:
\begin{equation}
\mathcal{L}_{img} = \lambda_{1} \mathcal{L}_{pix}(\textbf{\textit{I}}^{f}, \textbf{\textit{I}}) + \lambda_2 \mathcal{L}_{perc}(\textbf{\textit{I}}^{f}, \textbf{\textit{I}}) + \lambda_{3} \mathcal{L}_{id}(\textbf{\textit{I}}^{f}, \textbf{\textit{I}}) \ ,
\end{equation}
where $\mathcal{L}_{perc}$, $\mathcal{L}_{pix}$ and $\mathcal{L}_{id}$ indicate perceptual, l2-norm pixel-wise and identity losses, respectively.
$\lambda_1$, $\lambda_2$ and $\lambda_3$ are hyper-parameters of the losses.
With the image space supervision, the fine-tuned model well reconstructs the input in the original view, but is prone to overfitting on the input image, causing artifacts in novel view synthesized images and inaccurate 3D geometry of the subject.
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{figures/matting.pdf}
\caption{\textbf{Masked Geometrical Constraint.} (a) It shows the traditional rendering process for a novel view image. (b) Masked geometrical constraint takes only the foreground points into account. To render the novel view, only the red dots are used for image rendering. The two green dots are ignored, as they are definitely from a background region.
}
\label{fig:masked_matting}
\end{figure}
\subsection{Explicit Geometrical Regularization}\label{sec:neiborhood_reg}
To enrich the NeRF-GANs manifold using the input image attributes without worrying about visual artifacts in novel views, we relax the assumption of strict image space alignment described in Sec. \ref{sec:2dloss}. In order to regularize the model, we leverage the neighborhood samples around the optimized latent code to enhance the geometry, realism, and fidelity of the novel view and expression synthesis.
We first randomly sample different neighborhood latent codes $\mathbf{z}_{ng}$ surrounding the optimized latent code with various poses and expressions.
The neighborhood latent codes can be obtained by:
\begin{equation}
\textbf{z}_{ng} = \textbf{z}_{init} + \alpha \frac{\textbf{z}_{smp}-\textbf{z}_{init} }{||\textbf{z}_{smp}-\textbf{z}_{init} ||_2} \ ,
\end{equation}
where $\alpha$ is the interpolation distance between the randomly sampled $\textbf{z}_{smp} \sim \mathcal{N}(\textbf{0},\,\textbf{1})$ and optimized latent variable $\textbf{z}_{init}$.
To leverage the high-fidelity qualities of the original generator $\mathcal{G}_o$, we force the fine-tuned generator $\mathcal{G}_f$ to perform the same as $\mathcal{G}_o$ on the neighborhood latent codes, poses, and expressions. The geometrical constraint is defined based on both the color and density outputs of neighborhood samples on $\mathcal{G}_f$ and $\mathcal{G}_o$, that are expressed as:
\begin{equation}
\begin{aligned}
c_{ng}^f, \sigma_{ng}^f = & \mathcal{G}_f(\mathbf{z}_{ng}, \textbf{x}), \\
c_{ng}^o, \sigma_{ng}^o = & \mathcal{G}_o(\mathbf{z}_{ng}, \textbf{x}),
\end{aligned}
\end{equation}
By reprojecting each ray (\emph{i.e.} pixel) to 3D space according to its depth, we define two sets of point clouds $S_o$ and $S_f$ based on $\mathcal{G}_o$ and $\mathcal{G}_f$ images.
We compare the similarity of two point clouds using the Chamfer distance, and
define the geometrical constraint as follows:
\begin{equation}
\begin{aligned}
\mathcal{L}_{exp} = \frac{1}{|S_o|} \sum_{p_o \in S_o} min_{p_f \in S_f} &|| \sigma_{ng}^f(p_f) - \sigma_{ng}^o(p_o)||^2_2 + \\
&|| c_{ng}^f(p_f) - c_{ng}^o(p_o)||^2_2
\end{aligned}
\end{equation}
where $p_o$ and $p_f$ are the 3D locations in the point cloud sets $S_o$ and $S_f$.
\begin{figure}[t]
\centering
\includegraphics[trim=0.2in 0.19in 0.2in 0in,clip,width=\linewidth]{figures/forgery.pdf}
\caption{\textbf{The fogging artifacts around the hairline and/or in cheek region.}
}
\label{fig:matting}
\end{figure}
\begin{figure*}[t]
\centering
\includegraphics[width=\linewidth]{figures/show_case.pdf}
\caption{\textbf{Real image animation example on the ``Avengers''.} \textit{NeRFInvertor} synthesizes realistic faces using the pretrained AniFaceGAN with controllable pose and expression sequences given a single training image. As can be seen, \textit{NeRFInvertor} not only is capable of preserving identity attributes but also generates images with high quality and consistent appearance across different poses and expressions.
}
\label{fig:showcase}
\end{figure*}
\subsection{Implicit Geometrical Regularization}\label{sec:image_reg}
Moreover, we also add implicit geometrical regularizations on the rendering results of fine-tuned and the pretrained generator.
Given a novel view $\textbf{\textit{d}}_{s}$, the rendered image of $\mathcal{G}_f$ and $\mathcal{G}_o$ can be expressed as:
\begin{equation}
\begin{aligned}
\textbf{\textit{I}}_{ng}^f = &\mathcal{R}((c_{ng}^f, \sigma_{ng}^f), \textbf{\textit{d}}_{s}), \\
\textbf{\textit{I}}_{ng}^o = &\mathcal{R}((c_{ng}^o, \sigma_{ng}^o), \textbf{\textit{d}}_{s}).
\end{aligned}
\end{equation}
We minimize the distance between the image generated by $\mathcal{G}_f$ and $\mathcal{G}_o$ using pixel-wise, perceptual, and identity losses. Hence, the overall loss can be expressed as:
\begin{equation}
\begin{aligned}
\mathcal{L} = & \mathcal{L}_{img} + \lambda_4 \mathcal{L}_{exp} + \lambda_5 \mathcal{L}_{pix}(\textbf{\textit{I}}_{ng}^f, \textbf{\textit{I}}_{ng}^o) + \\ &\lambda_6 \mathcal{L}_{perc}(\textbf{\textit{I}}_{ng}^f, \textbf{\textit{I}}_{ng}^o) + \lambda_7 \mathcal{L}_{id}(\textbf{\textit{I}}_{ng}^f, \textbf{\textit{I}}_{ng}^o),
\end{aligned}
\end{equation}
\subsection{Masked Regularizations}
Given a single-view image, we fine-tune the model with novel regularizations to achieve better 3D geometry and higher fidelity images in novel views.
However, we still noticed some fogging parts around the hair or cheek as shown in Figure \ref{fig:matting}.
In order to remove artifacts and get more accurate geometry, We enhance our geometrical and image regularizations by a mask, which is based on matting information on the input image.
As shown in Figure \ref{fig:masked_matting}, we predict the mask for the input view image based on the foreground and background regions shown by the red and green colors.
In particular, if a shooting ray reaches the foreground region of the input image, we classify all the sample points on that ray as foreground points.
Similarly, if a shooting ray reaches the background region of the image, we classify all the data points on that ray as background points.
In the masked constraints, we take only the foreground (red) points into account for neighborhood density, color, and image rendering, and ignore the background (green) points.
\section{Related Work}\label{sec:related_work}
\begin{figure*}[t]
\centering
\includegraphics[trim=0.31in 0in 0.19in 0in,clip,width=\linewidth]{figures/framework.pdf}
\caption{\textbf{Framework of \textit{NeRFInvertor}.} Given the optimized latent code $\textbf{z}_{init}$, we fine-tune the generator and first apply image space supervision to push the generated image to match the input image in the original view $\textbf{\textit{d}}$.
To augment the NeRF-GAN manifold without worrying about visual artifacts in novel views, we then leverage the surrounding samples of the optimized latent code to regularize the realism and fidelity of the novel view and expression synthesis.
}
\label{fig:onecol}
\end{figure*}
\subsection{NeRF-GANs}
Recently, the impressive performance of NeRF-GANs has demonstrated its potential as a promising research direction.
GRAF~\cite{schwarz2020graf} and Pi-GAN~\cite{chan2021pigan} are two early attempts that proposed generative models for radiance fields for 3D-aware image synthesis from the unstructured 2D images.
Several recent studies (\eg GRAM~\cite{deng2022gram} and EG3D~\cite{chan2022eg3d}) have enhanced synthesis quality with higher resolutions, better 3D geometry, and faster rendering.
Furthermore, AniFaceGAN~\cite{wu2022anifacegan} introduced a deformable NeRF-GAN for dynamic scenes capable of synthesizing faces with controllable pose and expression.
In this paper, we demonstrate the effectiveness of our method on NeRF-GANs for both static (GRAM and EG3D) and dynamic (AniFaceGAN) scenes.
\subsection{GAN Inversion}
GAN priors can be beneficial in a variety of applications such as image editing~\cite{abdal2021styleflow,collins2020editing,richardson2021encoding} and face restoration~\cite{yang2021gan,wang2021towards}.
To utilize the priors, the input image needs to be inverted into a latent code that optimally reconstructs the given image using a pretrained generator. The process is known as GAN inversion, and it is a well-known issue in 2D GANs (\eg StyleGAN~\cite{karras2019style,Karras2019stylegan2,Karras2020ada}).
In the 2D domain, Abdal \etal~\cite{abdal2019image2stylegan,abdal2020image2stylegan++} employed direct optimization approach to invert an image
to styleGAN's latent space and demonstrated the distortion-editability trade-off between $\mathcal{W}$ and $\mathcal{W+}$ space. PTI~\cite{roich2022pti} achieved promising performance by using an initial inverted latent code as a pivot and fine-tuning the generator to mitigate the distortion-editability trade-off.
To exploit NeRF-GAN priors for 3D tasks, recent attempts inverted the real image to NeRF-GAN latent space using the traditional optimization method~\cite{zhang2022monocular}, additive encoder~\cite{cai2022pix2nerf,rebain2022lolnerf}, or PTI~\cite{chan2022eg3d,lin20223d}. However, applying these 2D-based inversion methods directly to 3D-GAN models makes them insensitive to subtle geometric alterations in 3D space.
To address this issue, we propose explicit geometrical regularization and implicit geometrical regularization to help produce better 3D geometry of the input.
\subsection{Single-shot NeRFs}
Due to the insufficient geometry and content information in a single image, single-shot NeRFs without additional supervision (\ie multi-view images or 3D objects) remain challenging. Recently, Pix2NeRF~\cite{cai2022pix2nerf} extended pi-GAN with the encoder to obtain a conditional single-shot NeRF models. HeadNeRF~\cite{hong2022headnerf} incorporated the NeRF into the parametric representation of the human head. Since the whole process is differentiable, the model can generate a NeRF representation from a single image using image fitting.
However, there remains a notable identity gap between the synthesized results and input images, indicating the inefficiency of single-shot NeRFs for real image inversion.
\section{Introduction}\label{sec:introduction}
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{figures/teaser.pdf}
\caption{\textbf{Image animation results of our method.} \textit{NeRFInvertor} achieves 3D-consistent and ID-preserving animation (\ie novel views and expressions) of real subjects given only a single image.
}
\label{fig:teaser}
\end{figure}
Animating a human with a novel view and expression sequence from a single image opens the door to a wide range of creative applications, such as talking head synthesis~\cite{wang2021one,meshry2021learned}, augmented and virtual reality (AR/VR)~\cite{li20193d}, image manipulation~\cite{tov2021designing,park2020swapping}, as well as data augmentation for training of deep models~\cite{pranjal2019palmprint,liu2018semi}.
Early works of image animation mostly employed either 2D-based image generation models~\cite{geng2018warp,wu2021f3a,pumarola2020ganimation,tewari2020pie}, or 3D parametric models~\cite{danvevcek2022emoca,ye20203d,bao2021high,ye2022high} (\eg 3DMM~\cite{blanz1999morphable}), but they mostly suffer from artifacts, 3D inconsistencies or unrealistic visuals.
Representing scenes as Neural Radiance Fields (NeRF)~\cite{mildenhall2021nerf} has recently emerged as a breakthrough approach for generating high-quality images of a scene in novel views. However, the original NeRF models ~\cite{barron2021mip,yu2021plenoctrees,wang2022fourier} only synthesize images of a static scene and require extensive multi-view data for training, restricting its application to novel view synthesis from a single image.
Several studies have shown more recent advances in NeRFs by extending it to generate multi-view face images with single-shot data even with controllable expressions \cite{cai2022pix2nerf,zhang2022monocular,rebain2022lolnerf,wu2022anifacegan,deng2022gram,chan2022eg3d}.
These Nerf-based Generative models (NeRF-GANs) are able to embed attributes of training samples into their latent variables, and synthesize new identity face images with different expressions and poses by sampling from their latent space.
While animatable synthesis of fake identity images is impressive, it is still challenging to generate 3D-consistent and identity-preserving images of real faces.
Specifically, current Nerf-GANs have difficulties to accurately translate out-of-domain images into their latent space, and consequently change identity attributes and/or introduce artifacts when applied to most real-world images.
In order to synthesize real faces, the conventional method applies optimization algorithms to invert the input image to a latent code in a smaller (\ie $\mathcal{W}$) or an extended (\ie $\mathcal{W+}$) NeRF-GAN latent space. However, they both either have ID-preserving or artifacts issues as shown in Figure~\ref{fig:id_geo_tradeoff}. The $\mathcal{W}$ space inversion, in particular, generates realistic novel views and clean 3D geometries, but suffers from the identity gap between the real and synthesized images.
In contrast, the $\mathcal{W+}$ space inversion well preserves the identity but commonly generates an inaccurate 3D geometry, resulting in visual artifacts when exhibited from new viewpoints.
Hence, it remains as a trade off to have a 3D-consistent geometry or preserve identity attributes when inverting face images out of latent space distribution.
In this paper, we present \textit{NeRFInvertor} as a universal inversion method for NeRF-GAN models to achieve high-fidelity, 3D-consistent, and identity-preserving animation of real subjects given only a single image.
Our method is applicable to most of NeRF-GANs trained for a \textit{static} or \textit{dynamic} scenes, and hence accomplish synthesis of real images with both novel views and novel expressions (see Figure~\ref{fig:teaser}).
Since the real images are mostly out of the domain of NeRF-GANs latent space, we surgically fine-tune their generator to enrich the latent space by leveraging the single input image without degrading the learned geometries.
In particular, given an optimized latent code for the input image, we first use image space supervision to narrow the identity gap between the synthesized and input images. Without a doubt, the fine-tuned model can be overfitted on the input image and well reconstruct the input in the original view. However, fine-tuning with just image space supervision produces erroneous 3D geometry due to the insufficient geometry and content information in a single image, resulting in visual artifacts in novel views. To overcome this issue, we introduce regularizations using the surrounding samples in the latent space, providing crucial guidance for the unobserved part in the image space. By sampling latent codes from the neighborhood of optimized latent variables with different poses and expressions, we enforce a novel geometric constraint on the density outputs of fine-tuned and original pretrained generators.
We also further add regularizations on the rendered images of neighborhood samples obtained from the fine-tuned and pretrained generators. These regularizations help us to leverage the geometry and content information of those in-domain neighborhood samples around the input.
Our experiments validate the effectiveness of our method in realistic, high-fidelity, and 3D consistent animating of real face images.
The main contributions of this paper are as follows:
\begin{enumerate}
\item We proposed a universal method for inverting NeRF-GANs to achieve 3D-consistent, high-fidelity, and identity-preserving animation of real subjects given only a single image.
\item We introduce a novel geometric constraint by leveraging density outputs of in-domain samples around the input to provide crucial guidance for the unobserved part in the 2D space.
\item We demonstrate the effusiveness of our method on multiple NeRF-GAN models across different datasets.
\end{enumerate}
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{figures/id_geo_tradeoff.pdf}
\caption{\textbf{Trade-off between ID-preserving and removing artifacts.} Optimizing latent variables of Nerf-GANs for synthesis of a real face leads to a trade-off between identity-preserving and geometrical and visual artifacts. Specifically, $\mathcal{W}$ space inversion results in clean geometry but identity gap between real and generated images, and $\mathcal{W+}$ space inversion causes preserving of identity attributes but inaccurate geometry and visual artifacts.
}
\label{fig:id_geo_tradeoff}
\end{figure}
\section{Experiments}\label{sec:experiments}
In this section, we compare our approach to existing inversion methods as well as single-shot NeRF models qualitatively and quantitatively.
We validate our method on multiple NeRF-GANs trained for static (\ie GRAM and EG3D) or dynamic scene (\ie AniFaceGAN). Evaluations are performed on reconstruction, novel view, and expression synthesis. Finally, we conduct ablation studies to disclose the contributions of the proposed components of our work.
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{figures/inversion_comparison_small.pdf}
\caption{\textbf{Comparison with prior inversion methods.}
I2S ($\mathcal{W}$) fails to preserve the identity of the input image, while I2S ($\mathcal{W+}$) introduces artifacts in novel views. PTI may generate texture that is inconsistent with the input image, such as fogging over a portion of the hair and ear or mismatched haircut with the input (see 2$^{nd}$ row). In comparison, our \textit{NeRFInvertor} delivers superior visual quality while preserving identity attributes.
}
\label{fig:inversion_comparison}
\end{figure}
\subsection{Implementation Details}
We use AniFaceGAN generator by default for the experiments unless otherwise specified. For face animation, we employ a generator pretrained on FFHQ dataset ~\cite{karras2019style}, and evaluate on both FFHQ and CelebA-HQ ~\cite{karras2017progressive} datasets.
We also use a generator pretrained on Cats~\cite{zhang2008cat} to synthesize cat faces in novel views.
In addition, we collect images of famous people as out-of-domain samples to emphasize the \textit{NeRFInvertor}'s identity-preserving capability (Figure~\ref{fig:showcase}).
We describe the training details of our \textit{NeRFInvertor} applied on GRAM and EG3D in the Supplementary Material.
For AniFaceGAN, the model is fine-tuned for 500 iterations. Hyper-parameters were set as follows: $\alpha=5$, $\lambda_{0}=0.1$, $\lambda_{1}=1$, $\lambda_{2}=10$, $\lambda_3=0.1$, $\lambda_4=10$, $\lambda_5=1$, $\lambda_6=10$, $\lambda_7=0.1$. The model is trained on 2 Nvidia RTX GPUs at the resolution of $128 \times 128$. We used an ADAM optimizer with a learning rate of $2e^{-5}$. Our model takes approximately 30 minutes for training.
\begin{figure}[t]
\centering
\includegraphics[width=0.85\linewidth]{figures/img2nerf_comparison_small.pdf}
\caption{\textbf{Comparison with single-shot NeRF methods.}
Existing single-shot NeRF approaches are either incapable of dealing with out-of-domain images or provide slightly artificial graphics. Our approach achieves 3D-consistent and ID-preserving animations.
}
\label{fig:img2nerf_comparison}
\end{figure}
\begin{figure*}[t]
\centering
\includegraphics[width=\linewidth]{figures/novel_views_from_multi_GAN.pdf}
\caption{\textbf{Applying \textit{NeRFInvertor} on multiple NeRF-GANs.} We show reconstruction, novel views and expressions synthesis. \textit{NeRFInvertor} achieves high-fidelity, texture and 3D consistencies and ID-preserving synthesis across poses and expressions.}
\label{fig:novel_views_from_multi_GAN}
\end{figure*}
\subsection{Qualitative Evaluation}
\noindent\textbf{Comparison with inversion methods.}
We start by qualitatively comparing our approach to prior inversion methods including I2S ($\mathcal{W}$), and I2S ($\mathcal{W+}$) and PTI. I2S~\cite{abdal2020image2stylegan++} employs the conventional optimization strategy to invert real images to either the smaller $\mathcal{W}$ space or the extended $\mathcal{W+}$ space.
PTI~\cite{roich2022pti} is an inversion method for 2D-GANs with excellent performance.
Figure~\ref{fig:inversion_comparison} shows a qualitative comparison of these methods for novel view synthesis from a single input image. I2S ($\mathcal{W}$) is able to generate images with acceptable visual quality, however there is a notable identity gap with the input image. In contrast, I2S ($\mathcal{W+}$) keeps identity attributes but introduces lots of artifacts in novel views. PTI shows better performance than I2S ($\mathcal{W}$) and I2S ($\mathcal{W+}$) by fine-tuning the model with image space supervisions. However, since it lacks explicit constraints in 3D space, it fails to generate accurate geometry of the input subject and the hidden content in the original view.
Our \textit{NeRFInvertor} outperforms these methods in terms of visual quality and identity preservation.
Furthermore, our method can generate novel view images with similar texture to the input image. For example, the visual details in Figure~\ref{fig:inversion_comparison} such as wrinkle on the forehead (1$^{st}$ row) and dimples in the cheeks (3$^{rd}$ row) are well maintained in novel views.
In the Supplementary Material, we demonstrate reconstruction results and show more novel views and expressions synthesis.
\begin{table}
\centering
\caption{\textbf{Quantitative comparisons on FFHQ and CelebA-HQ test set.} The \textbf{best}, and the {\color{blue} second best} scores are highlighted.
}
{
\begin{adjustbox}{max width=\linewidth}
\begin{tabular}{p{10mm}cccc|cccc}
\toprul
&& \multicolumn{3}{c|}{FFHQ} & \multicolumn{3}{c}{CelebA-HQ} \\
NeRF- & Inversion & \multicolumn{1}{c}{Rec.} & \multicolumn{2}{c|}{Novel View} & \multicolumn{1}{c}{Rec.} & \multicolumn{2}{c}{Novel View}\\
GANs & Methods & PSNR ($\uparrow$) & FID ($\downarrow$) & ID ($\uparrow$) & PSNR ($\uparrow$) & FID ($\downarrow$) & ID ($\uparrow$)\\\midrule
{\multirow{4}{*}{\shortstack{AniFace\\\cite{wu2022anifacegan}} }} & I2S~\cite{abdal2020image2stylegan++} ($\mathcal{W}$) & 15.62 & 58.37 & 0.33 & 16.50 & 42.53 & 0.25 \\
\multirow{4}{*}{} & I2S~\cite{abdal2020image2stylegan++} ($\mathcal{W+}$) & \textbf{25.44} & 65.36 & \textbf{0.83} & \textbf{26.86} & 45.08 & {\color{blue} 0.76} \\
\multirow{4}{*}{} & PTI~\cite{roich2022pti} & 23.89 & {\color{blue} 50.20} & 0.75 & 22.61 & {\color{blue} 37.83} & 0.73 \\ \rowcolor{lightgray}
\multirow{4}{*}{} & \textit{NeRFInvertor} & {\color{blue} 24.92} & \textbf{45.89} & {\color{blue} 0.76} & {\color{blue} 25.61} & \textbf{34.07} & \textbf{0.77} \\
\midrule
{\multirow{4}{*}{\shortstack{GRAM\\\cite{deng2022gram}}}} & I2S~\cite{abdal2020image2stylegan++} ($\mathcal{W}$) & 16.74 & 49.65 & 0.39 & 17.57 & \textbf{30.95} & 0.19 \\
\multirow{4}{*}{} & I2S~\cite{abdal2020image2stylegan++} ($\mathcal{W+}$) & 26.98 & 64.97 & 0.66 & 27.61 & 46.92 & 0.70 \\
\multirow{4}{*}{} & PTI~\cite{roich2022pti} & \textbf{28.90} & {\color{blue} 45.94} & {\color{blue} 0.79} & \textbf{29.26} & 38.01 & {\color{blue} 0.80} \\ \rowcolor{lightgray}
\multirow{4}{*}{} & \textit{NeRFInvertor} & {\color{blue} 28.46} & \textbf{43.58} & \textbf{0.80} & {\color{blue} 28.75} & {\color{blue} 31.11} & \textbf{0.81} \\
\bottomrule
\end{tabular}
\label{tab:qualitative_comparison}
\end{adjustbox}
}
\end{table}
\noindent\textbf{Comparison with single-shot NeRF methods.}
We compare our method with single-image view synthesis methods, Pix2NeRF and HeadNeRF, in Figure~\ref{fig:img2nerf_comparison}.
Pix2NeRF~\cite{cai2022pix2nerf} proposed an encoder to translate images to the Pi-GAN~\cite{chan2021pigan} latent space and jointly trained the encoder and the Pi-GAN generator. In contrast to Pix2NeRF and our \textit{NeRFInvertor}, which utilize GAN priors for novel view synthesis, HeadNeRF~\cite{hong2022headnerf} proposed a NeRF-based parametric head model to synthesize images with various poses.
The results in Figure~\ref{fig:img2nerf_comparison} show that Pix2NeRF is not a good candidate for real face synthesis, since it does not preserve the identity properly. HeadNeRF also shows a noticeable identity gap between the generated and input images. Furthermore, it also inherits the disadvantage of 3D parametric models that it produces some artificial visuals.
Our approach achieves significantly higher fidelity and better identity preservation compared to these two methods.
\noindent\textbf{Evaluation on multiple NeRF-GANs.}
We validate our pipeline on a variety of NeRF-GANs, including AniFaceGAN~\cite{wu2022anifacegan}, GRAM~\cite{deng2022gram}, and EG3D~\cite{chan2022eg3d}.
In Figure~\ref{fig:novel_views_from_multi_GAN}, we show the reconstruction, novel views, and expressions synthesis given a single input image.
AniFaceGAN uses a deformable NeRF structure and is trained for a dynamic scene. We demonstrate that \textit{NeRFInvertor} can faithfully translate a single image to a deformable NeRF representation, allowing us to generate realistic face editing with controllable poses and expressions (Figure~\ref{fig:showcase} and \ref{fig:novel_views_from_multi_GAN}).
Given a fixed latent code, GRAM and EG3D generate the NeRF representation for a static scene. We also validate our method on these two methods, demonstrating that we can invert a single image to a traditional NeRF representation for static scenes.
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{figures/ablation.pdf}
\caption{\textbf{Ablation study on different regularizations.}
}
\label{fig:ablation}
\end{figure}
\begin{table}
\centering
\caption{\textbf{Quantitative results of different regularizations.} }
{
\begin{adjustbox}{max width=\linewidth}
\begin{tabular}{cccccc
\toprul
& \multicolumn{1}{c}{Rec.} & \multicolumn{2}{c}{Novel View} & \multicolumn{2}{c}{Novel View+Exp.}\\
& PSNR/SSIM ($\uparrow$) & FID ($\downarrow$) & ID ($\uparrow$) & FID ($\downarrow$) & ID ($\uparrow$)\\\midrule
$\mathcal{L}_{img}$ & 22.48 / 0.764 & 38.61 & 0.66 & 38.82 & 0.60\\
$+\mathcal{L}_{imp}$ & 22.61 / 0.761 & 37.83 & 0.73 & 36.99 & 0.66 \\
$+\mathcal{L}_{exp}$ & \textbf{25.64} / 0.828 & 34.68 & 0.76 & 34.55 & 0.66 \\
\rowcolor{lightgray}
Full Model & 25.61 / \textbf{0.830} & \textbf{34.07} & \textbf{0.77} & \textbf{33.61} & \textbf{0.67} \\
\bottomrule
\end{tabular}
\label{tab:ablation}
\end{adjustbox}
}
\end{table}
\subsection{Quantitative Evaluation}
Quantitative experiments were performed on the first 150 samples from the CelebA-HQ test set and FFHQ dataset. For reconstruction results, we report PSNR in Table~\ref{tab:qualitative_comparison} and additional structural similarity (\ie SSIM~\cite{wang2004image}) and identity similarity in the Supplementary Material. Since we do not have multi-view ground truth images, we report Frechet Inception Distance (\ie FID) and identity similarity for novel view images following prior works~\cite{hong2022headnerf,cai2022pix2nerf}.
As can be seen, the results align with our qualitative evaluation. I2S ($\mathcal{W}$) fails to preserve the identity of the input image and has poor ID scores. I2S ($\mathcal{W+}$) introduces artifacts in novel views and results in high FID scores. Compared to PTI, our method generate comparable reconstructions, but superior novel view synthesis in terms of visual quality (\ie FID scores) and better identity preservation (\ie ID scores). We achieve the best overall performance across all metrics.
More quantitative results (\eg novel view \& expression evaluations) can be found in the Supplementary Material.
\begin{figure}[t]
\centering
\includegraphics[width=0.85\linewidth]{figures/ablation_neighbor.pdf}
\caption{\textbf{Ablation study on distance of neighborhood samples.}}
\label{fig:ablation_neighbor}
\end{figure}
\subsection{Ablation Study}
\noindent\textbf{Effectiveness of Regularization.}
We conduct an ablation study on the CelebA-HQ test set.
Compared to existing image space losses $\mathcal{L}_{img}$, we show the effects of our proposed implicit geometrical regularization (\ie $\mathcal{L}_{imp}$), explicit geometrical regularization (\ie $\mathcal{L}_{exp}$), and masked regularizations (\ie Full Model) in Figure~\ref{fig:ablation} and Table~\ref{tab:ablation}. The results in Figure~\ref{fig:ablation} indicate that the fine-tuned model with just image space losses $\mathcal{L}_{img}$ is prone to generating artifacts in novel-view images and inaccurate 3D geometry; the implicit implicit geometrical regularization $\mathcal{L}_{imp}$ helps to eliminate artifacts; the explicit geometrical regularization $\mathcal{L}_{exp}$ improves visual quality and the subject's 3D geometry; the full model with masked regularizations reduces fogging around the hair, ear, or cheek.
The quantitative results in Table~\ref{tab:ablation} are consistent with the qualitative results in Figure~\ref{fig:ablation}.
\noindent\textbf{Neighborhood Selection.}
We empirically find out that the distance between the optimized and neighborhood latent codes affects the ID-preserving ability and geometrical constraints. As shown in Figure~\ref{fig:ablation_neighbor}, if the distance is too small (\ie $\alpha<=1$), the model shows better geometrical constraints but worse identity preservation. And if the distance is too large (i.e., $\alpha>=10$), the model has better ID-preserving ability but undesired 3D geometry with visual artifacts in novel views.
Setting the distance $\alpha$ within the range $[1,10]$, we are able to well balance the image space supervision and regularization. We therefore simply set the distance to 5 for all the training samples in the experiments.
| {'timestamp': '2022-12-01T02:21:07', 'yymm': '2211', 'arxiv_id': '2211.17235', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17235'} | arxiv |
\section{Introduction}
Reinforcement learning (RL) has seen remarkable successes in recent years, many of which fall into the multi-agent setting, such as playing multi-agent games \citep{silver2016mastering,mnih2015human}, smart grid \citep{chen2022reinforcement}, queueing networks \citep{walton2021learning}, etc. In this work, we focus on a form of \emph{networked} Multi-Agent RL (MARL) where the agents interact according to a given network graph.
Compared to single-agent RL, MARL faces many additional challenges. First of all, the curse of dimensionality (which is already a major challenge in single-agent RL) becomes a more severe issue in MARL because the complexity of the problem scales exponentially with the number of agents \citep{marl_littman1994markov,marl_bu2008comprehensive,kearns1999efficient,factor_guestrin2003efficient}. This is because the size of the state and action space scales exponentially with the number of agents and, as a result, the dimension of the value/$Q$-functions and the policies all scale exponentially with the number of agents, which is hard to compute and store in moderately large networks \citep{bertsekas1996neuro}. Moreover, since the agents are coupled by the global state, the training process requires extensive communication among the agents in the entire network.
To overcome the aforementioned challenges, the existing literature considers performing MARL with only local information. For example, it has been proposed that each agent's policy depends only on the states of itself and, potentially, its neighboring agents. An example of this type is the independent learners approach \citep{tan1993multi,marl_claus1998dynamics}, where each agent learns a policy for itself while treating the states and actions of other agents as part of the environment. Another example is the recent work of \citet{qu2020scalablelocal,qu2020scalable,lin2021multi}, which focuses on learning localized policies where each agent is allowed to choose its action based on its own and neighbors' states. Beyond the localization in policy, it has also been proposed to approximate each agent's value or $Q$ functions in a way that they only depend on the local and nearby agents' states and actions \citep{factor_guestrin2003efficient,yang2018mean,qu2020scalablelocal,qu2020scalable,lin2021multi}, as opposed to the full state.
These approaches greatly relieve the computation and communication burden both empirically \citep{tan1993multi,foerster2016learning,sukhbaatar2016learning} and theoretically \citep{qu2020scalablelocal,qu2020scalable,lin2021multi}.
Despite this progress, there are still major limitations. As discussed above, in order to speed up learning, many previous works, e.g., \cite{tan1993multi,marl_claus1998dynamics,qu2020scalablelocal,qu2020scalable,lin2021multi},
restrict consideration to localized policies where each agent makes decisions only based on the local state of the agent and, potentially, neighbors, as opposed to the global state.
This leads to a fundamental performance gap between the class of localized policies considered and the optimal centralized policy. Even when the best localized policy can be found, there is a performance degradation compared to the best centralized policy, as the centralized policy class is a strict superset of the localized policy class. An important open question that remains is the following:
\begin{center}
\textit{How large is the gap between localized policies and the optimal centralized policy? \\ How much information must be available to each local agent \\in order to achieve a near-optimal performance?}
\end{center}
This question has received increasing attention in linear control settings \citep{bamieh2002distributed,motee2008optimal,shin2022near}, but is still open in MARL settings. In this work, we provide the first bounds on the gap between localized and centralized policies under a MARL model in networked systems.
Another limitation of prior work studying MARL is that, while existing results have provided convergence bounds for local policies, the convergence of their methods is typically only to a suboptimal policy in the localized policy class. For example, in \citet{qu2020scalable,lin2021multi}, the policies are shown to converge to a stationary point of the objective function defined on localized policies, as opposed to the global optimum. This is unsatisfying as converging to a stationary point does not even guarantee converging to the best localized policy. Therefore, another important and open question that remains is the following:
\begin{center}
\textit{Is it possible to design a MARL algorithm that provably \\ finds a near-globally-optimal policy using only local information?}
\end{center}
This question has received increasing attention in single-agent settings, where people have studied the convergence to the global optimum for policy-gradient methods under various policy classes \citep{bhandari2019global,agarwal2019theory}. However, it is open in the context of learning localized policies in MARL and in this work, we provide an affirmative answer to this question under an MARL model in networked systems.
\subsection{Contributions} Motivated by the open questions above, our work proposes and analyzes a new class of localized policies for networked MARL and proposes a Localized Policy Iteration (LPI) algorithm that converges to a near-globally-optimal policy. Our main contributions are summarized in the following.
\begin{itemize}[leftmargin=*]
\item \textbf{Near-Globally-Optimal $\kappa$-Hop Localized Policies.} We show that a class of $\kappa$-hop localized policies are nearly globally optimal, where a $\kappa$-hop localized policy means that each agent is allowed to choose its action based on the states of its $\kappa$-hop local neighborhood. More specifically, in \Cref{thm:subopt_dist_policy}, we show that there exists a $\kappa$-hop localized policy whose optimality gap is polynomially small in $\kappa$, where the optimality gap is with respect to the best centralized policy that is allowed to depend on the global state. As a result, even with a small $\kappa$, the class of $\kappa$-hop localized policies is near optimal despite the fact that each agent only uses information from within a small $\kappa$-hop neighborhood to make its decision. This result justifies using localized policies in networked MARL.
\item \textbf{Localized Policy Iteration.} Motivated by the result described above, we propose a localized MARL algorithm, a.k.a. $\text{LPI}$, given in \Cref{alg:SVI}. At a high level, $\text{LPI}$ iteratively performs policy improvement (and policy evaluation), but restricted to $\kappa$-hop policies.
While standard policy improvement requires using the information of global states and actions in order to conduct the policy improvement step, we develop a \textit{soft} policy improvement that approximately performs policy improvement to $\kappa$-hop localized policies using only local information. Therefore, our proposed algorithm can be implemented in a truly localized manner.
\item \textbf{Finite-Sample Analysis of $\text{LPI}$.} We provide a global convergence guarantee for $\text{LPI}$ in \Cref{thm:convergence_svi}. The guarantee holds for any policy evaluation method used as a subroutine in the evaluation step of $\text{LPI}$ (denoted as ${\texttt{PolicyEvaluation}}$) that satisfies a mild condition specified in \Cref{def:beta-hop-state-aggregation-policy-eva}.
Furthermore, in \Cref{cor:convergence_with_localized_td}, we provide the finite-sample complexity (cf. \eqref{eq:sample_complexity}) for $\text{LPI}$ when choosing a specific ${\texttt{PolicyEvaluation}}$ method proposed by \citet{lin2021multi}.
Specifically, we show that in order to achieve an $\varepsilon$ optimality (compared to the best centralized policy), one needs to use a $\kappa$-hop localized policy with $\kappa = \Theta(poly(\frac{1}{\varepsilon}))$ in $\text{LPI}$, and the sample complexity in learning such a $\kappa$-hop localized policy with $\varepsilon$ optimality gap scales polynomially with the largest state-action space size of local neighborhoods, as opposed to the global network.
\end{itemize}
The key technical novelty in this paper is a policy closure argument (\Cref{thm:convergence_prototype}), where we identify a class of policies that satisfy a form of spatial decaying properties and show that they are closed under the entropy regularized Bellman operator in MARL. This key observation implies that when starting from a policy in this class with spatial decaying properties, the policy improvement procedure will result in a new policy within this class, which further reveals that the optimal policy is also in the spatial decaying policy class. We then show that $\text{LPI}$ is an inexact version of the above policy iteration given by the regularized Bellman operator, where the learned policies and $Q$-functions are truncated to only depend on a localized neighborhood of each agent, and the exact policy evaluation and improvement steps are approximated by finite-sample estimations. Therefore, combining the policy closure argument for the exact version of $\text{LPI}$ and error bound analyses for the approximation made in $\text{LPI}$, we are able to show its convergence to a near global optimal policy, even though we only use localized information in $\text{LPI}$.
While the main contribution of this work is to theoretically show that $\text{LPI}$ can converge to the global optimal policy using only localized information, we also verify its empirical performance on a simulated networked MARL problem. In particular, we design an example of a spreading process over a network where the optimal policy depends on the global states of each agent (not just the local information). We run $\text{LPI}$ on this example and the results highlight that $\text{LPI}$ can perform well even outside the region suggested by the theory.
\subsection{Related Literature}
Reinforcement Learning (RL) studies a dynamical environment where the agent decides its current action based on the current state and the current state/action affects the distribution of its next state. This environment is usually modeled as a \textit{Markov Decision Process} (MDP) where the key assumption is the \textit{Markov Property}, which means the current state and action are statistically sufficient for deciding the next state (see, e.g., \citet{sutton2018reinforcement}). Specifically, an MDP (with discounted accumulative reward) can be characterized as a tuple $\langle \mathcal{S}, \mathcal{A}, P, \gamma, r\rangle$, where $\mathcal{S}$ and $\mathcal{A}$ denote the state/action space. The transition function $P: \mathcal{S} \times \mathcal{A}\to \Delta_\mathcal{S}$ characterizes the transition probability $\mathbf{P}(s'\mid s, a)$ from the current state/action pair to next state $s'$. $\gamma \in (0, 1)$ denotes the discount factor, and the reward function $r: \mathcal{S} \times \mathcal{A} \to [0, \bar{r}]$ is nonnegative for the agent with the state/action pair $(s, a)$.
In single-agent RL, the goal of the agent is to learn a policy $\zeta: \mathcal{S} \to \Delta(\mathcal{A})$ to maximize the expected discounted accumulative reward
$J(\zeta) := \mathbb{E}_{s(0) \sim \rho, a(t) \sim \zeta(\cdot\mid s(t))}\left[\sum_{t=0}^T \gamma^t r(s(t), a(t))\right].$ Two classic learning algorithms have been proposed to learn the optimal policy when the transition probabilities are known: value iteration and policy iteration \citep{sutton2018reinforcement}. \textit{Value Iteration} (VI) iteratively updates the estimated optimal value function by the Bellman equation and derives the final policy from the learned optimal value function. In contrast, \textit{Policy Iteration} (PI) works by evaluating the current policy and iteratively updating the policy using this policy's value function. Our algorithm, $\text{LPI}$,
can be viewed as a generalization of PI to a networked setting where the transition probabilities are unknown. Lower bound results show tabular RL algorithms inevitably suffer from \textit{the curse of dimensionality} when the transition probabilities are unknown (see, e.g., \citet{jin_is_2018}), which means the sample complexity (i.e., the number of samples to find a near-optimal policy) grows with respect to the size of state space $\mathcal{S}$ and action space $\mathcal{A}$.
Multi-Agent Reinforcement Learning (MARL) generalizes the single-agent RL setting to a situation where the global MDP evolves based on the joint action/policy of $n$ agents. The generalization to include more agents is necessary for solving practical problems that involve large-scale networks and/or games. Specifically, each agent $i$ has its local action space $\mathcal{A}_i$ and its local reward function $r_i$, and the global action space $\mathcal{A} = \mathcal{A}_1 \times \cdots \times \mathcal{A}_n$. At every time step $t$, agent $i$ receives a partial observation $o_i(s(t))$ to decide its local action $a_i(t)$. More details about this setting can be found in \Cref{sec:model_pre}. Depending on each agent's learning objective, MARL can be divided to two categories: cooperative or competitive MARL (see \cite{zhang2019multi} for a survey). In \textit{cooperative MARL}, all agents work together to optimize a shared global objective \citep{qu2020scalable, qu2020scalablelocal, lin2021multi}, which is also the setting studied in this work. In \textit{competitive MARL}, each agent optimizes its local accumulative reward, and the goal is to find an approximate Nash Equilibrium \citep{ding2022independent, leonardos2021global}.
A major challenge for cooperative MARL is that the size of the global action space $\mathcal{A}$ can grow exponentially with respect to the number of agents $n$, which makes centralized training intractable. Fully distributed training is not practical either, because its reward and transition probability depend on other agents' policies. To address this challenge and derive finite-sample complexity bounds that are not exponential in $n$, a common assumption made by previous works \citep{doan2019finite, suttle2020multi} is that the global state is observable to all agents (i.e., $o_i(s) = s$), which thus eliminates the need for communicating local states in the network. This works in special settings such as cooperative navigation and Predator-Prey where a joint state space is easy to observe or all agents share the same state space \citep{lowe2017multi, zhang2018fully}. Nevertheless, such an assumption is not practical in more general MARL settings like the one studied in our paper, where each agent has its own state space and the global state space $\mathcal{S} = \mathcal{S}_1 \times \cdots \times \mathcal{S}_n$ is exponentially large with respect to $n$. In this setting, huge communication costs are usually unavoidable and thus it is more challenging and less studied.
Our work is most related to a class of cooperative MARL problems where the agents are located in a network graph $\mathcal{G}$ \citep{qu2020scalablelocal, qu2020scalable, lin2021multi}, which makes similar structural assumptions on the MDP as this paper, i.e., each agent has its own local state/action space and the local transition probabilities depend only on the agent's neighbors. Each agent $i$ observes the local states of the agents whose graph distance to $i$ is less than or equal to $\kappa$ to decide its local action (i.e., $o_i(s) = s_{\mathcal{N}_i^\kappa}$, where $\mathcal{N}_i^\kappa := \{j \mid d_{\mathcal{G}}(i, j) \leq \kappa\}$. $d_{\mathcal{G}}(i, j)$ denotes the length of the shortest path between $i$ and $j$ on $\mathcal{G}$). As a remark, all local policies become centralized when the dependence parameter $\kappa$ exceeds the diameter of graph $\mathcal{G}$. Previous works \citep{qu2020scalablelocal, qu2020scalable, lin2021multi} propose decentralized policy iteration algorithms to learn local policies for each agent\footnote{The local policy defined in these papers focuses on a local agent that chooses local actions based only on the agent's state.} and prove finite-time convergence bounds. However, there is still an open gap between the localized policy and centralized policy where each agent makes decisions based on the global state. Specifically, before our work, there is no result on how large the gap between the optimal $\kappa$-hop localized policy and the optimal centralized policy is, nor how fast it decays with respect to $\kappa$. Besides, even if the objective is defined with respect to the $\kappa$-hop localized policy class, the algorithms proposed by \citet{qu2020scalablelocal, qu2020scalable, lin2021multi} are only guaranteed to converge to stationary points of their local objective functions rather than global optima of the objective.
Another challenge widely encountered in RL is that the policy might rapidly become deterministic during the training process, which further leads to a slow convergence. To speed up the convergence and also encourage exploration for the training algorithm to escape suboptimal points, entropy regularization has often been added to the value function. This approach has yielded both good empirical performance \citep{williams1991function,mnih2016asynchronous,vieillard2020leverage} and strong theoretical guarantees \citep{agarwal2020optimality,mei2020global,cen2021fast}. In this paper, we focus on the entropy regularized problem in multi-agent reinforcement learning.
\section{Model \& Preliminaries}\label{sec:model_pre}
In this section, we introduce the model we study and provide preliminaries that are used throughout our paper.
In particular, we introduce networked multi-agent Markov decision processes in \Cref{subsec:mamdp}. %
Then, in \Cref{subsec:entropy_reg_value_and_q}, we define the (state) value function and action-state value function (i.e., $Q$ function) in the multi-agent setting with an entropy regularization. In \Cref{subsec:spatial_decay_property}, we introduce a novel class of polices where the dependence of local policies on other agents' actions decay polynomially as the graph distance increases. This property is key to our analysis. Note that a summary table of notation is given in \Cref{tab:notation} in the appendix for the reader's reference.
\subsection{Multi-Agent Markov Decision Process}\label{subsec:mamdp}
We consider a network of $n$ agents that are associated with an undirected graph $\mathcal{G} = (\mathcal{N},\mathcal{E})$, where $\mathcal{N}=\{1,\ldots,n\}$ is the set of nodes and $\mathcal{E}\subseteq \mathcal{N}\times\mathcal{N}$ is the set of edges. We denote the state-space and the action-space of agent $i$ by $\mathcal{S}_i$ and $\mathcal{A}_i$, respectively, and they are both finite sets. %
We also denote $A_{\max}=\max_{i\in\mathcal{N}}|\mathcal{A}_i|$.
The global state is denoted as $s = (s_1,\ldots,s_n)\in \mathcal{S}:=\mathcal{S}_1\times\cdots\times \mathcal{S}_n$ and similarly the global action is denoted as $a=(a_1,\ldots,a_n)\in\mathcal{A}:=\mathcal{A}_1\times\cdots\times\mathcal{A}_n$.
At time $t\geq 0$, given current state $s(t)$ and action $a(t)$, for each $i\in\mathcal{N}$, the next individual state $s_i(t+1)$ is independently generated and is only dependent on its neighbors' states and its own action:
\begin{align}
P(s(t+1)\mid s(t),a(t)) = \prod_{i=1}^n P_i(s_i(t+1)\mid s_{\mathcal{N}_i}(t),a_i(t)), \label{eq:transition_factor}
\end{align}
where $\mathcal{N}_i=\{i\}\cup \{j\in\mathcal{N}\mid (i,j)\in\mathcal{E}\}$ denotes the neighborhood of $i$ (including $i$ itself) and $s_{\mathcal{N}_i}$ represents the states of the agents in $\mathcal{N}_i$. In addition, for integer ${\color{black}\kappa}\geq 0$, we use ${\color{black}\cN_i^{\khop}}$ to denote the ${\color{black}\kappa}$-hop neighborhood of $i$, i.e., the nodes of which the graph distance to $i$ have length less than or equal to ${\color{black}\kappa}$. We also use ${\color{black}\cN_{-i}^{\khop}}=\mathcal{N}/{\color{black}\cN_i^{\khop}}$ to denote the agents that are not in ${\color{black}\cN_i^{\khop}}$. We use $s_{\mathcal{N}_i^\kappa}$ and $a_{\mathcal{N}_i^\kappa}$ to denote the states and actions of the agents in $\mathcal{N}_i^\kappa$ respectively, use $s_{-i}, a_{-i}$ to denote the states and actions of all agents other than $i$, and we use $f(\kappa) = \sup_{i\in\mathcal{N}} |{\color{black}\cN_i^{\khop}}|$ to denote the size of the largest $\kappa$-hop neighborhood.
Each agent is associated with a policy $\zeta_i$, which maps each global state $s\in\mathcal{S}$ to a probability distribution supported on the set of local actions $\mathcal{A}_i$, and we use $\Delta_{\mathcal{A}_i|\mathcal{S}}$ to denote the space $\zeta_i$ lies in. Each agent, conditioned on observing $s(t)$, takes an action $a_i(t)$ according to $\zeta_i(\cdot|s(t))$.
We use $\zeta(a|s) = \prod_{i=1}^n\zeta_i(a_i|s)$ to denote the joint policy, which is the product of all the individual policies. Since $\zeta$ is uniquely determined by the tuple of the $\zeta_i$'s, we also slightly abuse the notation and denote $\zeta = (\zeta_1,\zeta_2,\cdots,\zeta_n)\in \Delta_{\mathcal{A}_1|\mathcal{S}} \times \Delta_{\mathcal{A}_2|\mathcal{S}} \times \cdots \times \Delta_{\mathcal{A}_n|\mathcal{S}} : =\Delta_{\mathrm{policy}}$.
\subsection{Value Function and $Q$-Function}\label{subsec:entropy_reg_value_and_q}
Each agent $i\in\mathcal{N}$ is associated with a stage reward function $r_i(s_i,a_i)$ that depends on its local state and action. The global stage reward is defined as $r(s,a) = \frac{1}{n}\sum_{i=1}^n r_i(s_i,a_i)$.
We assume that all rewards $r_i$ are bounded above by $\bar{r}$ throughout the paper.
Given any joint policy $\zeta\in\Delta_{\mathrm{policy}}$, we define the entropy regularized value function at state $s$ as
\begin{align}\label{eq:value_func}
V^\zeta (s)= \mathbb{E}_{a(t) \sim \zeta(\cdot|s(t))}\bigg[ \sum_{t=0}^\infty \gamma^t \big[r(s(t),a(t)) -\tau \log(\zeta(a(t)|s(t)))\big] \;\bigg|\; s(0) = s\bigg],
\end{align}
where $\tau> 0$ is a tunable parameter.
Based on $V^\zeta(\cdot)$, we further define the objective function as
\[J(\zeta) = \mathbb{E}_{s \sim \rho}[ V^\zeta(s) ],\]
where $\rho(\cdot)$ is a given initial state distribution.
In this work, we aim to find a global optimal policy $\zeta^*\in \Delta_{\mathrm{policy}}$ that maximizes the objective function $J(\zeta)$.
In both the definition of the value function and the objective function, there is a weighted entropy term $-\tau\log(\zeta(a(t)|s(t)))$ with positive weight $\tau$. Entropy regularization has gained popularity in the RL literature for both practical and theoretical reasons. Practically, it is known that adding regularization encourages randomness and exploration of the policy \citep{williams1991function,mnih2016asynchronous,vieillard2020leverage}, which is necessary in RL. To see this, observe that the optimal policy becomes the uniform policy as the parameter $\tau$ goes to infinity. Theoretically, due to the strong concavity of the negative entropy function, it has been shown that entropy regularization helps improving the convergence rate of several RL algorithms, e.g., natural policy gradient \citep{cen2021fast,cayci2021linear}. Moreover, we show in \Cref{sec:algo_design} that the entropy regularization term plays an important role in our multi-agent RL setting as it will affect the suboptimality gap between localized policies and the best centralized policy.
Given the definition of the value function \eqref{eq:value_func}, the $Q$ function of a joint policy $\zeta$ is defined as
\begin{align}\label{eq:q_func}
Q^\zeta(s,a) = r(s,a) + \gamma \mathbb{E}_{s'\sim P(\cdot|s,a)} V^\zeta(s').
\end{align}
The value function and the $Q$-function satisfy the following relationship
\begin{align}\label{eq:Vtau_Qtau_relation}
V^{\zeta}(s) &=\mathbb{E}_{a\sim \zeta(\cdot|s) }\left[ r(s,a) - \tau\log \zeta(a|s) + \gamma \mathbb{E}_{s'\sim P(\cdot|s,a)} V^\zeta(s')\right]\notag\\
&=\mathbb{E}_{a\sim \zeta(\cdot|s) }\left[ Q^\zeta(s,a) - \tau \log \zeta(a|s) \right],
\end{align}
where the first line follows from the Bellman equation for $V^\zeta(\cdot)$.
In view of the additive structure of the stage rewards $r(s,a)$, we also define in the following the local value function and the local $Q$ function for all $i\in\mathcal{N}$:
\begin{align}
V^\zeta_i (s) &= \mathbb{E}_{a(t) \sim \zeta(\cdot|s(t))}\bigg[\sum_{t=0}^\infty \gamma^t \left[ r_i(s_i(t),a_i(t) ) -n\tau \log(\zeta_i(a_i(t)|s(t)))\right] \bigg| s(0) = s\bigg], \label{eq:local_value_func} \\
Q^\zeta_i(s,a) &= r_i(s_i,a_i) + \gamma \mathbb{E}_{s'\sim P(\cdot|s,a)} V^\zeta_i(s'). \label{eq:local_q_func}
\end{align}
We sometimes use the vector $\mathbf{Q} = (Q_1,\ldots,Q_n)$ to denote the complete profile of all the local $Q$ functions.
It is clear from the definition that
\begin{align*}
V^\zeta(s) = \frac{1}{n} \sum_{i=1}^n V^\zeta_i(s),\quad\text{and}\quad
Q^\zeta(s,a) = \frac{1}{n} \sum_{i=1}^n Q^\zeta_i(s,a).
\end{align*}
Similar to the standard Bellman optimal operator,
we define the Bellman optimal operator with entropy regularization $\mathcal{T}: \mathbb{R}^{|\mathcal{S}|}\mapsto\mathbb{R}^{|\mathcal{S}|} $ as
\begin{align}
[\mathcal{T} V](s) = \max_{\zeta\in \Delta_{\mathrm{policy}}} \mathbb{E}_{a\sim \zeta(\cdot|s) }\left[ r(s,a) - \tau \log \zeta(a|s)+ \gamma \mathbb{E}_{s'\sim P(\cdot|s,a)} V(s') \right],\;\forall\; V\in\mathbb{R}^{|\mathcal{S}|},\;s\in\mathcal{S}. \label{eq:bellman_operator}
\end{align}
The following result regarding the properties of $\mathcal{T}(\cdot)$ is an immediate extension to that of the standard Bellman optimal operator. For completeness, a proof is presented in \Cref{subsec:proof_exist_optimal_policy_entropy}.
\begin{proposition}\label{prop:exist_optimal_policy_entropy}
$\mathcal{T}(\cdot)$ is a contraction mapping with respect to the $\ell_\infty$-norm, with contraction factor $\gamma$. In addition, suppose a policy $\zeta^*$ satisfies $V^{\zeta^*}=\mathcal{T}(V^{\zeta^*})$, then $\zeta^*$ is an optimal policy.
\end{proposition}
\subsection{Spatial Decay Properties}\label{subsec:spatial_decay_property}
Throughout this paper, we use spatial decay properties heavily, i.e. the fact that a certain quantity decays as the distance between two agents increases. Spatial decay properties have been investigated in the literature in various forms, including the exponential decay of $Q$-functions in \cite{qu2020scalablelocal,qu2020scalable} and correlation decay in combinatorial optimization \cite{gamarnik2013correlation,gamarnik2014correlation,bamieh2002distributed}. In this paper, we introduce the classes of $(\nu,\mu)$-decay polices and $(\nu,\mu)$-decay $Q$-functions. The decay properties of these quantities eventually enable us to control the optimality gap (compared to the best centralized policy) when restricting the agents to using only $\kappa$-hop localized policies (to be defined in \Cref{def:kappa-hop}).
Compared to the exponential decay of $Q$-functions in the literature, our work considers a different type of decay whose rate is polynomial. Further, we extend the decay property from $Q$-functions to policies which, broadly speaking, is similar in concept to \citet{shin2022near}, which studies a similar decaying policy class in linear dynamical systems.
To start, we first introduce the $(\nu,\mu)$-decay matrices.
\begin{definition}[$(\nu,\mu)$-decay matrix]\label{def:matrix_decay}
For $\nu,\mu>0$, a matrix $A \in\mathbb{R}^{n\times n}$
is said to be $(\nu,\mu)$-decay with respect to graph $\mathcal{G} = (\mathcal{V}, \mathcal{E})$ with $\mathcal{V} = \{1,2,\cdots,n\}$ if every entry of $A$ is non-negative and
\begin{align*}
\max\bigg\{ \sup_i \sum_{j=1}^n A_{ij}(\mathrm{dist}(i,j)+1)^\mu,\sup_{j}\sum_{i=1}^n A_{ij}(\mathrm{dist}(i,j)+1)^\mu \bigg\}&\leq \nu, %
%
\end{align*}
where $\mathrm{dist}(i,j)$ is the graph distance between $i$ and $j$ in $\mathcal{G}$.
\end{definition}
Intuitively speaking, for a $(\nu,\mu)$-decay matrix $A$, $A_{ij}$ decays polynomially as the graph distance between $i$ and $j$ increases. To see this, observe that we have for all $i\in \mathcal{N}$ and $\kappa\in\mathbb{N}$:
\begin{align}\label{eq:mu_decay_imply_distance_decay}
\sum_{j:\mathrm{dist}(i,j)>\kappa} A_{ij} \leq \sum_{j:\mathrm{dist}(i,j)>\kappa} A_{ij}\frac{(\mathrm{dist}(i,j)+1)^{\mu}}{(\kappa+1)^\mu}\leq \frac{\nu}{(\kappa+1)^\mu}.
\end{align}
Based on \Cref{def:matrix_decay}, we next define the $(\nu,\mu)$-decay policy class as follows.
\begin{definition}[$(\nu,\mu)$-decay policy]\label{def:mu_decay_policy}
Let $\zeta=(\zeta_1,\ldots,\zeta_n)$ be a joint policy, where $\zeta_i$ is the policy of agent $i\in \{1,2,\cdots,n\}$. The interaction matrix of $\zeta$, denoted by $Z^\zeta\in\mathbb{R}^{n\times n}$, is defined as
\begin{align*}
Z_{ij}^\zeta = \max_{s_{-j}} \max_{s_j,s_j'} \mathrm{TV}(\zeta_i(\cdot|s_j,s_{-j}),\zeta_i(\cdot|s_j',s_{-j}) ),\quad\text{for all } i,j\in \{1,2,\cdots,n\}.
\end{align*}
A policy $\zeta$ is said to be ($\nu$,$\mu$)-decay if $Z^\zeta$ is a ($\nu,\mu$)-decay matrix.
\end{definition}
In a $(\nu,\mu)$-decay policy, agent $i$'s action $a_i$ depends on the state of agent $j$ in a manner that the dependence decays polynomially in the graph distance between $i$ and $j$.
The next definition introduces $\sigma$-regular policies.
\begin{definition}\label{def:sigma_regular}
A distribution $d=(d_1,\ldots,d_M)$ over a set $\{1,2,\ldots,M\}$ is called $\sigma$-regular if $\max_{m,m'\in[M]}\log(d_m/d_{m'})\leq\sigma$. A joint policy $\zeta=(\zeta_1,\ldots,\zeta_n)$ is $\sigma$-regular if $\forall i, s\in\mathcal{S}$, the distribution $\zeta_i(\cdot|s)$ is $\sigma$-regular.
\end{definition}
Through out the paper, we use $\Delta_{\nu,\mu,\sigma}$ to denote the set of all joint policies that are $(\nu,\mu)$-decay and $\sigma$-regular.
Similarly, we also define a class of decaying $Q$-functions as follows.
\begin{definition}[($\nu$,$\mu$)-decay $Q$-function class]\label{def:Z_Q}
Let $Q_i\in\mathbb{R}^{|\mathcal{S}||\mathcal{A}|}$, $i\in \mathcal{N}$ be the local $Q$-functions defined in \eqref{eq:local_q_func}, and let $\mathbf{Q} = \{Q_i\}_{i\in\mathcal{N}}$. The interaction matrix of $\mathbf{Q}$, denoted by $Z^{\mathbf{Q}}\in\mathbb{R}^{n\times n}$, is defined as
\begin{align*}
Z^{\mathbf{Q}}_{ij} = \max_{s_{-j},a_{-j}}\max_{s_j,a_j,s_j',a_j'}|Q_i(s_j,a_j, s_{-j},a_{-j}) - Q_i(s_j',a_j', s_{-j},a_{-j})|, \quad\forall\; i,j\in\{1,2,\cdots,n\}.
\end{align*}
For any given $\nu$ and $\mu$, a local $Q$ function tuple $\mathbf{Q} = \{Q_i\}_{i\in\mathcal{N}}$ is said to be $(\nu,\mu)$-decay if $Z^{\mathbf{Q}}$ is a $(\nu,\mu)$-decay matrix.
\end{definition}
One benefit of the $(\nu,\mu)$-decay property of $\mathbf{Q} = \{Q_i\}_{i\in\mathcal{N}} $ is that it allows ``truncation'' of the local $Q$ functions. Specifically, given a positive integer $\beta$, and a local $Q$-function tuple $\mathbf{Q} = \{Q_i\}_{i\in\mathcal{N}} $, we can define the following truncated local $Q$-functions:
\begin{align}
\hat{Q}_i(s_{\cN_i^{\beta}},a_{\cN_i^{\beta}}) = \sum_{s_{\mathcal{N}_{-i}^\beta}, a_{\mathcal{N}_{-i}^\beta}} w(s_{\mathcal{N}_{-i}^\beta}, a_{\mathcal{N}_{-i}^\beta}; s_{\cN_i^{\beta}},a_{\cN_i^{\beta}}) Q_i(s_{\cN_i^{\beta}},s_{\mathcal{N}_{-i}^\beta},a_{\cN_i^{\beta}} a_{\mathcal{N}_{-i}^\beta}) \label{eq:truncated_q_def}
\end{align}
where weight parameters $w(s_{\mathcal{N}_{-i}^\beta}, a_{\mathcal{N}_{-i}^\beta}; s_{\cN_i^{\beta}},a_{\cN_i^{\beta}})\geq0$ satisfy $ \sum_{s_{\mathcal{N}_{-i}^\beta}, a_{\mathcal{N}_{-i}^\beta}} w(s_{\mathcal{N}_{-i}^\beta}, a_{\mathcal{N}_{-i}^\beta}; s_{\cN_i^{\beta}},a_{\cN_i^{\beta}}) = 1$.
It can be shown that despite the reduction in dimension, the truncated local $Q$ functions are a good approximate of the original local $Q$ functions under the $(\nu,\mu)$-decay property.
\begin{proposition}[Adapted from Lemma 4 in \cite{qu2020scalablelocal}]\label{prop:truncated_q_error}
Suppose the local $Q$ functions $\{Q_i\}_{i\in\mathcal{N}}$ satisfy $(\nu,\mu)$ decay property. Then, $\forall i$,
\begin{align*}
\sup_{s,a} \Big| Q_i(s,a) - \hat{Q}_i(s_{\cN_i^{\beta}},a_{\cN_i^{\beta}}) \Big| \leq \frac{\nu}{(\beta+1)^\mu}.
\end{align*}
\end{proposition}
\noindent This truncation of the local $Q$ functions have been adopted in the literature \citep{qu2020scalablelocal,qu2020scalable}. We also use this in our approach.
\section{Algorithm Design }\label{sec:algo_design}
We now present the design of Localized Policy Iteration, i.e., $\text{LPI}$. As discussed in the introduction, it is impractical to implement $\zeta_i$ because it needs access to the global state $s=(s_1,\ldots,s_n)$. To see this, note that it requires $\Omega(|\mathcal{S}|) = \Omega(\prod_{i=1}^n|\mathcal{S}_i|)$ parameters to even specify such a policy, which is impractically large and hard to store. Moreover, each agent would need access to the states of all the agents in order to implement such a policy, which is often hard to achieve in a large networked system due to communication challenges.
To address these issues, our focus is on localized policies, where agent $i$'s action depends only on the states of the agents who are close to $i$ in the network graph $\mathcal{G}$. Given this restriction on the policies, one may immediately ask what is lost when we restrict to localized policies compared with the centralized policies where the agents are allowed access to the global state. We show in \Cref{subsec:almost-optimal} that, under a structural assumption, using $\kappa$-hop localized policies is almost as good as using centralized policies, where the parameter $\kappa$ captures the level of localization. Then, in \Cref{subsec:algo}, we introduce our \text{LPI}\ framework that learns a near optimal $\kappa$-hop localized policy.
\subsection{Performance Gap between Localized Policies and Centralized Policies}\label{subsec:almost-optimal}
We begin by formally defining the class of $\kappa$-hop localized policies we consider. Recall that $\kappa>0$ is a positive integer, and we use $s_{\mathcal{N}_i^\kappa}$ to denote the states of the agents in $\mathcal{N}_i^\kappa$.
\begin{definition}[$\kappa$-hop policies]\label{def:kappa-hop}
A policy $\zeta = (\zeta_1,\ldots,\zeta_n) \in\Delta_{\mathrm{policy}}$ is called a $\kappa$-hop (localized) policy if the following equation holds for all $i\in\mathcal{N}$, $s_{{\color{black}\cN_i^{\khop}}}\in \mathcal{S}_{{\color{black}\cN_i^{\khop}}}$, and $s_{{\color{black}\cN_{-i}^{\khop}}},s'_{{\color{black}\cN_{-i}^{\khop}}} \in\mathcal{S}_{{\color{black}\cN_{-i}^{\khop}}}$:
\[ \zeta_i(\cdot\mid s_{{\color{black}\cN_i^{\khop}}},s_{{\color{black}\cN_{-i}^{\khop}}}) = \zeta_i(\cdot\mid s_{{\color{black}\cN_i^{\khop}}},s'_{{\color{black}\cN_{-i}^{\khop}}}) .\]
In other words, there exists $\hat{\zeta}_i: \mathcal{S}_{{\color{black}\cN_i^{\khop}}} \mapsto \Delta_{\mathcal{A}_i}$ such that
$\zeta_i(\cdot|s_{{\color{black}\cN_i^{\khop}}},s_{{\color{black}\cN_{-i}^{\khop}}}) = \hat{\zeta}_i(\cdot|s_{{\color{black}\cN_i^{\khop}}})$.
\end{definition}
From \Cref{def:kappa-hop}, we see that, when using a $\kappa$-hop localized policy, each agent only needs to know the states of the agents that are within its $\kappa$-hop neighborhood. Note that $\kappa$ is a tunable parameter in practice, and captures the trade-off between communication, optimality, and computational complexity. Such a policy is more practical to implement than a centralized policy because of both the reduction in dimension and the reduction in communication.
To state our result on the performance gap, the following definition regarding the system transition matrix is needed. Following~\citet{qu2020scalable}, we define a matrix $C\in\mathbb{R}^{n\times n}$ that characterizes the interaction strength between agents via the total variation of the transition probabilities.
\begin{align}\label{def:C_mat_tv}
{C}_{ij} = \left\{ \begin{array}{ll}
0, & \text{ if }j\notin \mathcal{N}_i,\\
\sup_{s_{\mathcal{N}_i/j},a_i}\sup_{s_j,s_j'} \mathrm{TV}( P_i(\cdot|s_j, s_{\mathcal{N}_i/j},a_i) , P_i(\cdot| s_j', s_{\mathcal{N}_i/j},a_i) ), & \text{ if } j\in \mathcal{N}_i/{i},\\
\sup_{s_{\mathcal{N}_i/i}}\sup_{s_i,s_i',a_i,a_i'} \mathrm{TV}( P_i(\cdot|s_i, s_{\mathcal{N}_i/i},a_i) , P_i(\cdot| s_i', s_{\mathcal{N}_i/i},a_i') ), & \text{ if } j=i.
\end{array} \right.
\end{align}
Our first main result states that $\kappa$-hop polices are nearly as good as centralized policies, with a gap that decays polynomially in $\kappa$.
\begin{theorem}\label{thm:subopt_dist_policy}
Suppose that $\gamma<0.8$, $\tau \geq 6\bar{r} \frac{4-3\gamma}{4-5\gamma}A_{\max}^2 e$, and $\sum_{j\in \mathcal{N}_i}C_{ij}<1/2$ for all $i\in \{1,2,\cdots,n\}$. Then there exists a $\kappa$-hop policy $\hat{\zeta}^{*,\kappa}$ that satisfies
\begin{align*}
J(\zeta^*) - J(\hat{\zeta}^{*,\kappa}) \leq {\frac{\bar{r} (4-3\gamma)}{(1-\gamma)(4-5\gamma)} \frac{1}{(\kappa+1)^\mu},}
\end{align*}
where
\begin{align*}
\mu= \min\bigg\{\log_2 \frac{\tau(4-5\gamma)}{6\bar{r}A_{\max}^2 e(4-3\gamma)} ,\log_2 \frac{1}{2 \sup_{i\in\mathcal{N}}\sum_{j\in \mathcal{N}_i}C_{ij}}\bigg\}.
\end{align*}
\end{theorem}
The above theorem states that when $\kappa$ increases, the optimality gap of $\kappa$-hop localized policies decays polynomially in $1/\kappa$. This suggests that, even for $\kappa$-hop policies with a relatively small $\kappa$, one can achieve reasonably good performance and also avoid the curse of dimensionality and the communication issue in large networked systems. \Cref{thm:subopt_dist_policy} motivates us to learn $\kappa$-hop localized policies, which is presented in the next section.
We note that the polynomial decay rate $\mu$ in \Cref{thm:subopt_dist_policy} depends on several factors. The factor $\sum_{j\in \mathcal{N}_i} C_{ij}$ can be viewed as the interaction strength between node $i$ and its neighbors. The smaller the total interaction strength is for all agents, the larger the decay parameter $\mu$. This is intuitive since weaker interaction means that $\kappa$-hop localized policies should perform better as there is less coupling between the nodes. Another important factor is $\tau$. The larger $\tau$ is, the larger the decay rate $\mu$. Intuitively, a larger $\tau$ generally means entropy regularization will play a more important role, which effectively ``dampens'' the interaction among agents. To understand this, note that the policy that maximizes the entropy is the uniform policy, and therefore, the larger the entropy regularization is, the less incentive there is for an agent's policy to depend on the states of far away agents.
It is also interesting to compare our result to the results in the Linear Quadratic Control (LQC) setting \citep{bamieh2002distributed,motee2008optimal,shin2022near}, where it has been shown that the performance gap between the optimal $\kappa$-hop policy and the optimal centralized policy decays exponentially in $\kappa$. This is a faster decay rate than the polynomial rate in our result. One reason for this difference is that the LQC setting is inherently a linear setting, whereas our MARL setting is inherently a combinatorial setting, which is typically more complicated. It remains an interesting question to understand the fundamental reason behind the discrepancy between the LQC setting and our setting.
Lastly, we note that, for \Cref{thm:subopt_dist_policy} to hold, we need a lower bound on $\tau$ and an upper bound on $\sup_i\sum_{j\in \mathcal{N}_i} C_{ij}$.
We believe these two bounds are hard to avoid. Bounds like these are common in the spatial decay literature in combinatorial settings. As an example, in \cite{gamarnik2013correlation,gamarnik2014correlation}, the ratio $I_2/I_1$ is assumed to be small enough, where $I_1$ can be viewed as the bias of each agent towards a specific action, and $I_2$ can be viewed as the interaction strength between neighboring agents. Put in the context of our paper, $I_1$ corresponds to the $\tau$ parameter, as the entropy regularization can be viewed as a bias towards the uniform policy, and $I_2$ corresponds to the total interactive strength $\sup_i\sum_{j\in \mathcal{N}_i} C_{ij}$. As a result, our assumptions on $\tau$ and $\sup_i\sum_{j\in \mathcal{N}_i} C_{ij}$ are consistent with those in the literature. On a different note, we also have an upper bound on $\gamma<0.8$, which we believe is an artifact of the proof. In \Cref{sec:experiment}, we show our approach also works when $\gamma>0.8$.
\subsection{Algorithm Design: Localized Policy Iteration } \label{subsec:algo}
\begin{algorithm}[t]
\caption{Localized Policy Iteration ($\text{LPI}$)}\label{alg:SVI}
\begin{algorithmic}[1]
\FOR{$m = 0, 1, 2, \cdots$}
\STATE Sample initial global state $s(0) \sim \rho$.\label{alg:SAC_Outline:Critic_Start}
\hrulefill\\ \textit{\color{gray}Policy Evaluation}
\FOR{$t = 0, 1, \cdots, T$}
\STATE Each agent $i$ takes action $a_i(t) \sim \hat{\zeta}_i^m(\cdot \mid s_{{\color{black}\cN_i^{\khop}}}(t))$ to obtain the next global state $s(t+1)$. \label{algo:run_policy}
\STATE Each agent $i$ records $s_{{\cN_i^{\beta}}}(t), a_{{\cN_i^{\beta}}}(t)$, $r_i(t):=r_i(s_i(t),a_i(t))$.
\label{algo:collect_trajectory}
\ENDFOR
\STATE Each agent $i$ conducts policy evaluation subroutine to estimate its truncated local $Q$-function\\ $\hat{Q}_i^m \leftarrow {\texttt{PolicyEvaluation}}(\beta,\{s_{{\cN_i^{\beta}}}(t), a_{{\cN_i^{\beta}}}(t), r_i(t)\}_{t=0}^T, \hat{\zeta}_i^m)$. \label{algo:policy_evaluation_return}
%
%
%
\hrulefill\\ \textit{\color{gray}Soft Policy Improvement}
\FOR{$p = 0, 1, \cdots, p_{\max}$}
\label{alg:policy_improvement_start}
\STATE Each agent $i$ runs the following iterative procedure to calculate a policy, where $\hat{\pi}_i^{0}$ is initialized at a uniformly random policy. \label{algo:policy_improvement}\\
For all $(a_{{\color{black}\cN_i^{\khop}}},s_{{\color{black}\cN_i^{\khop}}})\in\mathcal{A}_{{\color{black}\cN_i^{\khop}}}\times \mathcal{S}_{{\color{black}\cN_i^{\khop}}}$, update %
\begin{align}
\mathcal{Q}^i(a_i,a_{{\color{black}\cN_i^{\khop}}/i},s_{{\color{black}\cN_i^{\khop}}}) & = \frac{1}{n}\sum_{j\in {\color{black}\cN_i^{\khop}}} \hat{Q}_j^m([\ext{s_{{\color{black}\cN_i^{\khop}}}}]_{{\cN_j^{\beta}}},[\ext{a_{{\color{black}\cN_i^{\khop}}}}]_{{\cN_j^{\beta}} \backslash i},a_i),\label{eq:algo_local_aggregate_q}\\
\hat{\pi}_i^{p+1}(a_i\mid s_{{\color{black}\cN_i^{\khop}}}) &= \frac{\big(\hat{\pi}_i^{p}(a_i \mid s_{{\color{black}\cN_i^{\khop}}})\big)^{1 - \eta \tau}}{Z_i^{p}(s_{{\color{black}\cN_i^{\khop}}})} \exp\Big(\eta \mathbb{E}_{a_{j}\sim\hat{\pi}_{j}^{p}([\ext{s_{{\color{black}\cN_i^{\khop}}}}]_{{\color{black}\cN_j^{\khop}}}),j\in {\color{black}\cN_i^{\khop}}/\{i\}}\big[\mathcal{Q}^i(a_i,a_{{\color{black}\cN_i^{\khop}}/i},s_{{\color{black}\cN_i^{\khop}}})\big]\Big), \label{eq:algo_policyimprovement}
\end{align}%
%
where $Z_i^{p}(s_{{\color{black}\cN_i^{\khop}}})$ is the normalization term.
\ENDFOR \label{alg:policy_improvement_end}
\STATE Each agent sets $\hat{\zeta}_i^{m+1} \leftarrow \hat{\pi}_i^{p_{\max}+1}$. \label{algo:policy_improvement_return}
\ENDFOR
\end{algorithmic}
\end{algorithm}
The details of \text{LPI}\ are presented in \Cref{alg:SVI}. It is a policy iteration style algorithm where each agent updates a $\kappa$-hop policy $\hat{\zeta}_i^m$, with $m$ being the iteration counter. Within each iteration, the algorithm is divided into two major steps: policy evaluation and policy improvement. Each is described in detail below, followed by a discussion of the communication and computation requirements of the algorithm.
\textbf{Policy evaluation.} Each agent implements the current policy (Line \ref{algo:run_policy}) to collect samples (Line \ref{algo:collect_trajectory}). Then, in Line~\ref{algo:policy_evaluation_return}, each agent $i$ estimates a \emph{truncated} local $Q$ function (defined in \eqref{eq:truncated_q_def}). Such a truncated local $Q$-function is much smaller in dimension than the full local $Q$-function, and the error caused by the truncation is small (cf. \Cref{prop:truncated_q_error}). We note that Line~\ref{algo:policy_evaluation_return} uses a subroutine {\texttt{PolicyEvaluation}}, which we leave unspecified for now because our algorithm can accommodate many popular policy evaluation schemes such as Temporal Difference (TD) learning. Further, our final convergence guarantee holds as long as the policy evaluation subroutine satisfies a exactness property (\Cref{def:beta-hop-state-aggregation-policy-eva}) to be defined in \Cref{sec:convergence}. Moreover, in \Cref{subsec:policy_evaluation}, we provide a version of TD learning as the {\texttt{PolicyEvaluation}}\ subroutine that can learn the truncated local $Q$ functions and satisfy \Cref{def:beta-hop-state-aggregation-policy-eva}.
\textbf{Policy improvement.} The policy improvement step runs from Line~\ref{alg:policy_improvement_start} to Line~\ref{alg:policy_improvement_end}. It is an iterative procedure with $p_{\max}$ iterations, and each agent updates a $\kappa$-hop policy $\hat{\pi}_i^p$. The core step is for the agents to collectively implement \eqref{eq:algo_local_aggregate_q} and \eqref{eq:algo_policyimprovement}, where each agent $i$ sets $\hat{\pi}_i^{p+1}$ to be the softmax policy according to $\mathcal{Q}^i$. We explain this step in detail below.
\textit{Calculating $\mathcal{Q}^i$ in \eqref{eq:algo_local_aggregate_q}.} $\mathcal{Q}^i$ is an \emph{locally aggregated $Q$ function}, where it averages over the truncated local $Q$ functions of agent $i$'s $\kappa$ hop neighborhood: $\{\hat{Q}_j\}_{j\in{\color{black}\cN_i^{\khop}}}$. We note that $\mathcal{Q}^i$ only depends on the states and actions of of $i$'s $\kappa$-hop neighborhood $s_{\color{black}\cN_i^{\khop}},a_{\color{black}\cN_i^{\khop}}$, but in the mean while $\hat{Q}_j$ depends on the state and action of node $j$'s $\beta$-hop neighborhood, which might not be in ${\color{black}\cN_i^{\khop}}$. Therefore, when evaluating $\hat{Q}_j$, for the nodes $\ell \in {\cN_j^{\beta}}/{\color{black}\cN_i^{\khop}} $, we use a default value for their state and action denoted as $s^{\mathrm{default}}_{\ell},a^{\mathrm{default}}_{\ell}$. More formally, we define the following extension operator:
\begin{definition}[Extension Operator]\label{def:ext_operator}
Define a state tuple $s_{\mathcal{J}} = (s_j)_{j\in\mathcal{J}}\in\mathcal{S}_{\mathcal{J}}$ for a subset of agents $\mathcal{J}\subseteq\mathcal{N}$. We define a corresponding global state $\ext{s_{\mathcal{J}}}$ based on $s_{\mathcal{J}}$:
\begin{align}
[\ext{s_{\mathcal{J}}}]_j=
\begin{cases}
s_j&\text{if } j\in\mathcal{J},\\
s^{\mathrm{default}}_j&\text{if} j\not\in\mathcal{J}.
\end{cases}
\end{align}
where $s^{\mathrm{default}}$ is a default global state. The same notation is used to extend local actions to global actions.
\end{definition}
\noindent We note that, throughout this paper, the default state $s^{\mathrm{default}}$ is fixed and can be any state tuple in $\mathcal{S}$. Its value does not affect our final guarantee. With \Cref{def:ext_operator}, we can write the evaluation of $\hat{Q}_j $ as $\hat{Q}_j( [\ext{s_{{\color{black}\cN_i^{\khop}}}}]_{\cN_j^{\beta}}, [\ext{a_{{\color{black}\cN_i^{\khop}}}}]_{\cN_j^{\beta}})$. This gives rise to \eqref{eq:algo_local_aggregate_q}. The rationale of calculating $\mathcal{Q}^i$ in this way is that, as shown later in the proof, we have for any $s,a_{-i}, a_i,a_i'$
\begin{align*}
\mathcal{Q}^i(a_i,a_{{\color{black}\cN_i^{\khop}}/i},s_{{\color{black}\cN_i^{\khop}}}) - \mathcal{Q}^i(a_i',a_{{\color{black}\cN_i^{\khop}}/i},s_{{\color{black}\cN_i^{\khop}}}) \approx \hat{Q}^m(a_i, a_{-i}, s) - \hat{Q}^m (a_i', a_{-i}, s)
\end{align*}
where $\hat{Q}^m(s,a) = \frac{1}{n} \sum_{j\in\mathcal{N}}\hat{Q}_j^m(s_{{\cN_j^{\beta}}},a_{{\cN_j^{\beta}}}) $, the average of the truncated local $Q$ functions for iteration $m$. In other words, $\mathcal{Q}^i$ is a good estimate of $\hat{Q}^m$ (up to a function that does not depend on $a_i$), which in turn is a good estimate of the true $Q$ function $Q^{\hat{\zeta}^m}$. Therefore, we can then conduct a multiplicative weights policy update based on $\mathcal{Q}^i$, which we discuss next.
\emph{Multiplicative weights policy update \eqref{eq:algo_policyimprovement}.} The basic idea of \eqref{eq:algo_policyimprovement} is for each agent $i$ to update its policy using the multiplicative weights algorithm, with $\mathcal{Q}^i$ as the score for each action $a_i$. Note that $\mathcal{Q}^i$ not only depends on $a_i$, but also $a_{{\color{black}\cN_i^{\khop}}/i}$, so when conducting the update, we take the expectation of $a_j$ using the current policy of agent $j$, $\hat{\pi}_j^p$. When doing so, $\hat{\pi}_j^p$ depends on states that are outside ${\color{black}\cN_i^{\khop}}$, and for these states, we set it to a default value (the same as the default value used in the calculation of $\mathcal{Q}^i$). We show later in the proof (\Cref{lem:policy_improvement_error}) that the update \eqref{eq:algo_policyimprovement} is approximately solving the maximization in the Bellman optimal operator \eqref{eq:bellman_operator}.
\textbf{Computation and communication.} The major computational burden of $\text{LPI}$ lies in the steps that compute the truncated local $Q$ functions and the $\kappa$-hop polices. The complexity of these scales with the largest state-action space size of the $\kappa$ and $\beta$-hop neighborhood in the network. Therefore, our algorithm can avoid the exponential computation burden associated with the exponentially large state and action spaces.
In terms of communication, each agent only needs local communication with agents in the $\max(\beta,\kappa)$-hop neighborhood, as opposed to centralized communication. Specifically, in Line~\ref{algo:collect_trajectory} each agent $i$ needs to receive information on the states and actions of agents in the $\beta$-hop neighborhood $s_{{\cN_i^{\beta}}}(t),a_{{\cN_i^{\beta}}}(t)$. In Line~\ref{algo:policy_improvement} (eq. \eqref{eq:algo_policyimprovement}), each agent $i$ needs to know $\{\hat{\pi}_j^{p}\}_{j\in{\color{black}\cN_i^{\khop}}}$ as well as the truncated $Q$-functions $\{\hat{Q}_j^m
\}_{j\in{\color{black}\cN_i^{\khop}}}$ for the agents in the $\kappa$-hop neighborhood.
\section{Convergence Analysis}\label{sec:convergence}
This section provides a convergence guarantee for \text{LPI}. We first present our requirements for the {\texttt{PolicyEvaluation}}\ subroutine in \Cref{def:beta-hop-state-aggregation-policy-eva}. Then, under these requirements, we present our main convergence result for \text{LPI}\ in \Cref{thm:convergence_svi}. Finally, in \Cref{subsec:policy_evaluation}, we provide a specific policy evaluation subroutine, {\text{Localized TD(0)}}, which is a variation of the approach proposed in \cite{lin2021multi}, and show that it can meet the \Cref{def:beta-hop-state-aggregation-policy-eva}.
\subsection{Convergence of Localized Policy Iteration}
Our requirement for the {\texttt{PolicyEvaluation}}\ subroutine is stated formally in \Cref{def:beta-hop-state-aggregation-policy-eva}. Intuitively, the policy evaluation process involves two parts of errors: a bias is introduced because we only estimate the truncated local $Q$ functions (cf. \eqref{eq:truncated_q_def}) using information collected within the $\beta$-hop neighborhood rather than global network. Such a truncation introduces a bias that is on the order of $O(\nu'/(\beta + 1)^{\mu})$ because of the $(\nu', \mu)$-decay property of the true local Q function (\Cref{prop:truncated_q_error}). In addition to the bias caused by the truncation, a stochastic error also exists due to the inherent stochasticity of the observed samples. Under proper assumptions, the stochastic error decays to zero as the number of samples $T$ increases. Since the bias part of the error is `inevitable', we require the policy evaluation algorithm to achieve an approximation error that is in the same order of the bias with high probability after a finite number of iterations, formally stated in \Cref{def:beta-hop-state-aggregation-policy-eva}.
\begin{definition}\label{def:beta-hop-state-aggregation-policy-eva}
A policy evaluation algorithm is said to be $(\sigma,\nu',\mu)$-exact if the following condition holds: For any $\sigma$ regular policy $\hat{\zeta}$ whose corresponding local $Q$ functions $\{Q_i^{\hat{\zeta}}\}$ is $(\nu',\mu)$ decay,
and $\delta \in (0, 1)$, there exists a function $c_{pe}(\delta,\sigma, \nu',\mu)$, such that for any $\beta\in\mathbb{N}$, there exits a $T_{eval}(\delta,\sigma, \nu',\mu, \beta)\in\mathbb{N}$ such that when the length of the trajectory supplied to the subroutine $T \geq T_{eval}(\delta,\sigma, \nu',\mu, \beta)$ steps, with probability at least $1 - \delta$, the following inequality holds
\[ \sup_{(s, a) \in \mathcal{S}\times \mathcal{A}}\abs{Q_i^{\hat{\zeta}}(s, a) - \hat{Q}_i(s_{{\cN_i^{\beta}}}, a_{{\cN_i^{\beta}}})} \leq \frac{c_{pe}(\delta,\sigma,\nu',\mu)}{(\beta + 1)^\mu}, \forall i\in \mathcal{N},\]
where $Q_i^{\hat{\zeta}}$ is the true local $Q$-functions under policy $\hat{\zeta}$, and $\hat{Q}_i$ is the output of the policy evaluation subroutine. When the context is clear, we may drop the parenthesis of $c_{pe}, T_{eval}$.
\end{definition}
Using the above definition, we can now state our main convergence result for \Cref{alg:SVI}.
\begin{theorem}\label{thm:convergence_svi}
Suppose $\gamma<0.8$, $\tau\geq 40\bar{r} \frac{4-3\gamma}{4-5\gamma}A_{\max}^2 e$, and $\sum_{j\in \mathcal{N}_i}C_{ij}<1/2$ for all $i\in \{1,2,\cdots,n\}$.
Let $\nu' = \frac{4-3\gamma}{4-5\gamma}\bar{r}$, $\mu=\min\Big\{\log_2 \frac{\tau(4-5\gamma)}{40\bar{r}A_{\max}^2 e(4-3\gamma)} ,\log_2 \frac{1}{2 \sup_{i\in\mathcal{N}}\sum_{j\in \mathcal{N}_i}C_{ij}}\Big\}$, and $\tilde\sigma=\frac{2\nu'}{\tau n}$. Suppose the \emph{{\texttt{PolicyEvaluation}}}\ subroutine in \Cref{alg:SVI} is $(\tilde{\sigma},\nu',\mu)$-exact with constants $c_{pe}(\cdot), T_{eval}(\cdot)$ (cf. \Cref{def:beta-hop-state-aggregation-policy-eva}). Fixing any $\kappa$, take the algorithm parameters as $\beta = \frac{\kappa+1}{2}(\frac{2f(\kappa) c_{pe}}{\nu'})^{\frac{1}{\mu}}$, $\eta=\frac{1}{\tau}$, and $p_{\max}\geq -\log_2{\frac{4 + c_{pe}/(2^{\mu}\nu')}{3(\kappa/2+1)^\mu}}$. Then, given $M\in\mathbb{N}$ and $\delta\in(0,1)$, when the trajectory input to the \emph{{\texttt{PolicyEvaluation}}}\ subroutine $T \geq T_{eval}(\delta/M, \tilde{\sigma},\nu',\mu,\beta)$, we have with probability at least $1-\delta$,
\[J(\zeta^*) - J(\hat{\zeta}^M) \leq \gamma^{M} \Vert V^{\hat{\zeta}^0} - V^*\Vert_\infty + \frac{3(4-3\gamma)\bar{r} }{(1-\gamma)^2(4-5\gamma)} \bigg(4 + \frac{c_{pe} (4-5\gamma)}{2^{\mu}(4-3\gamma)\bar{r}}\bigg) \frac{1}{(\kappa/2+1)^\mu}. \]
\end{theorem}
As shown in \Cref{thm:convergence_svi}, \text{LPI}\ converges geometrically in $M$, with a steady state error on the order of $O(\frac{1}{(\kappa+1)^\mu})$, i.e., the steady state error decays polynomially in $\kappa$. This steady state error is a result of both the policy evaluation error in \Cref{def:beta-hop-state-aggregation-policy-eva}, and the fact that we are using a truncated $\kappa$-hop policy as opposed to a global policy.
\textbf{Sample complexity. }As we discussed in \Cref{subsec:algo}, the {\texttt{PolicyEvaluation}}\ subroutine can be chosen to be any algorithm that satisfies \Cref{def:beta-hop-state-aggregation-policy-eva} and the sample complexity of $\text{LPI}$ depends on the specific choice. In \Cref{subsec:policy_evaluation}, we describe a specific {\texttt{PolicyEvaluation}}\ subroutine, $\beta$-hop Localized TD(0), that satisfies the requirement. Under this specific subroutine,
we derive the sample complexity of $\text{LPI}$ in the following corollary.
\begin{corollary}\label{cor:convergence_with_localized_td}
Let the assumptions of \Cref{thm:convergence_svi} and \Cref{thm:beta-hop-policy-evaluation} hold. For any $\varepsilon>0$ and $\delta\in(0,1)$, when using $\beta$-hop {\text{Localized TD(0)}}\ as the \emph{{\texttt{PolicyEvaluation}}}\ subroutine, the sample complexity of \Cref{alg:SVI} to achieve $\varepsilon$-optimality is in the order of
\begin{align}\label{eq:sample_complexity}
\Theta\left( \frac{1}{\varepsilon^2}\frac{ f(\kappa)^2 \log(1/\varepsilon) \log [f(\beta) \log(1/\varepsilon)] }{\xi(\tilde\sigma,\beta)^2}\right),
\end{align}
where $\xi(\tilde{\sigma},\beta)$ is defined in \Cref{network-assp:geometric-mixing} and means the smallest probability the state-action pairs in $\beta$-hop neighborhoods are visited.
\end{corollary}
Based on the convergence result in \Cref{thm:convergence_svi}, to find an $\varepsilon$-optimal policy, we only need to set $M = \Theta(\log(1/\varepsilon))$ and $\kappa = \Theta((1/\varepsilon)^{1/\mu} )$, and correspondingly $\beta = \Theta(\kappa (f(\kappa))^{1/\mu} )$. According to \eqref{eq:T_eval} that we show later in \Cref{thm:beta-hop-policy-evaluation}, the iteration complexity of $\beta$-hop {\text{Localized TD(0)}}\ is $T_{eval} = \Theta( \frac{(\beta+1)^{2\mu} \log (f(\beta) M/\delta)}{\xi(\tilde{\sigma},\beta)^2} ) = \Theta(\frac{ (1/\varepsilon)^2 f(\kappa)^2 \log [f(\beta) \log(1/\varepsilon)] }{\xi(\tilde\sigma,\beta)^2}) $. Thus the sample complexity of $\text{LPI}$ follows the simple calculation $MT_{eval}$ and is given in \eqref{eq:sample_complexity}. In all the $\Theta(\cdot)$ notations above, we only keep the dependence on the network size $n$ and the $\varepsilon$ parameter, which involves $\varepsilon$ itself and by extension, the $\kappa,\beta,M$ parameters.
In this sample complexity bound, we have the $\frac{1}{\varepsilon^2}$ factor that is standard in the RL literature. In addition, instead of depending on the global-state action space size (exponential in $n$), we have a square dependence on $\frac{1}{\xi(\tilde{\sigma},\beta)}$, where $\xi(\tilde{\sigma},\beta)$ is defined in \Cref{network-assp:geometric-mixing} and means the smallest probability the state-action pairs in $\beta$-hop neighborhoods are visited. As such, $\frac{1}{\xi(\tilde{\sigma},\beta)}$ scales with the largest state action space size of the $\beta$-hop neighborhoods, as opposed to the entire network. Therefore, $\text{LPI}$ is much more scalable and implementable than other methods that enjoy global convergence such as centralized tabular RL methods \citep{bertsekas1996neuro}. This advantage is especially pronounced in sparse networks where $\beta$-hop neighborhoods are much smaller than the entire network.
Lastly, beyond the $\frac{1}{\varepsilon^2}$ factor and $\frac{1}{(\xi(\tilde\sigma,\beta))^2}$ factor and a few $\log$ factors, our bound also contains a factor $f(\kappa)^2$, where we recall $f(\kappa)$ is the size of the largest $\kappa$-hop neighborhood. This factor reflects the complexity of the $\kappa$-hop policy we try to learn.
\subsection{Policy Evaluation via $\beta$-hop Localized TD(0)} \label{subsec:policy_evaluation}
\begin{algorithm}[ht]
\caption{$\beta$-hop Localized TD(0) (Agent $i$)}\label{alg:beta-hop-TD-0}
\begin{algorithmic}[1]
\REQUIRE Parameter $\beta$, a sequence of $\beta$-hop state, $\beta$-hop action, and local reward tuples $\{s_{{\cN_i^{\beta}}}(t), a_{{\cN_i^{\beta}}}(t), r_i(t)\}$, local policy $\hat{\zeta}_i^m$, and a sequence of learning rate $\{\alpha_t\}$.
\STATE Initialize $\hat{Q}_i^0$ to be all zero vector.
\STATE Set $\hat{r}_i(t) \gets r_i(t) - n \tau \mathbb{E}_{a_i \sim \hat{\zeta}_i^m(\cdot \mid s_{{\color{black}\cN_i^{\khop}}}(t))} \log \hat{\zeta}_i^m(a_i \mid s_{{\color{black}\cN_i^{\khop}}}(t))$.
\FOR{$t = 1, \cdots, T$}
\STATE Update the local estimation $\hat{Q}_i$ with step size $\alpha_{t-1}$,
{\begin{equation*}
\begin{aligned}
&\hat{Q}_i^t \big(s_{{\cN_i^{\beta}}}(t-1), a_{{\cN_i^{\beta}}}(t-1)\big) =\\
&(1 - \alpha_{t-1})\hat{Q}_i^{t-1} \big(s_{{\cN_i^{\beta}}}(t-1), a_{{\cN_i^{\beta}}}(t-1)\big) + \alpha_{t-1}\big(\hat{r}_i(t) + \gamma \hat{Q}_i^{t-1} \big(s_{{\cN_i^{\beta}}}(t), a_{{\cN_i^{\beta}}}(t)\big)\big),\\
&\hat{Q}_i^t \big(s_{{\cN_i^{\beta}}}, a_{{\cN_i^{\beta}}}\big) = \hat{Q}_i^{t-1} \big(s_{{\cN_i^{\beta}}}, a_{{\cN_i^{\beta}}}\big)\text{ for }\big(s_{{\cN_i^{\beta}}}, a_{{\cN_i^{\beta}}}\big) \not = \big(s_{{\cN_i^{\beta}}}(t-1), a_{{\cN_i^{\beta}}}(t-1)\big).
\end{aligned}
\end{equation*}}
\label{alg:SAC_Outline:Critic_End}
\ENDFOR
\STATE For every $(s_{{\cN_i^{\beta}}}, a_{{\cN_i^{\beta}}})$ pair, set $\hat{Q}_i^T(s_{{\cN_i^{\beta}}}, a_{{\cN_i^{\beta}}}) \gets \hat{Q}_i^T(s_{{\cN_i^{\beta}}}, a_{{\cN_i^{\beta}}}) + n \tau \mathbb{E}_{a_i \sim \hat{\zeta}_i^m(\cdot \mid s_{{\color{black}\cN_i^{\khop}}})} \log \hat{\zeta}_i^m(a_i \mid s_{{\color{black}\cN_i^{\khop}}})$ and return $\hat{Q}_i^T(\cdot)$
\end{algorithmic}
\end{algorithm}
To provide a concrete example of the {\texttt{PolicyEvaluation}}\, subroutine, we introduce and analyze {\text{Localized TD(0)}}\ in this subsection. The pseudo-code of {\text{Localized TD(0)}}\ is given in \Cref{alg:beta-hop-TD-0}. It is a variation of a policy evaluation subroutine used in \cite{lin2021multi}, where each agent conducts temporal difference learning using the states and actions of its local $\beta$-hop neighborhood. Note that compared to \cite{lin2021multi}, we also add entropy regularization in the update (see Line \ref{alg:SAC_Outline:Critic_End} of \Cref{alg:beta-hop-TD-0}).
In this section, we show that \Cref{alg:beta-hop-TD-0} satisfies \Cref{def:beta-hop-state-aggregation-policy-eva} by utilizing the convergence results in \cite{lin2021multi}. We first state the assumption needed.
\begin{assumption}\label{as:MC}
There exists a policy $\zeta_b=(\zeta_{b,1},\zeta_{b,2},\cdots,\zeta_{b,n})\in\Delta_{\textrm{policy}}$ such that the Markov chain $\{s(t)\}_{t\geq 0}$ induced by $\zeta_b$ is irreducible and aperiodic.
\end{assumption}
Based on \Cref{as:MC}, we show that all $\sigma$-regular policies are sufficiently explorative.
\begin{lemma}\label{network-assp:geometric-mixing}
Define $\mathcal{Z} := \mathcal{S} \times \mathcal{A}$. Under \Cref{as:MC}, for any $\sigma$-regular policy $\hat{\zeta}$, the induced Markov chain $\{z(t) := \left(s(t), a(t)\right)\}$ is irreducible and aperiodic, hence admits a unique stationary distribution $d^{\hat{\zeta}} \in \Delta_{\mathcal{Z}}$ with strictly positive components. Further, there exists positive constants $K_1(\sigma)$ and $K_2(\sigma)\geq 1$ depending on $\sigma$ such that
\[\forall z' \in \mathcal{Z}, \forall t \geq 0, \sup_{\mathcal{K} \subseteq \mathcal{Z}}\Bigg|\sum_{z \in \mathcal{K}}d_z^{\hat{\zeta}} - \sum_{z \in \mathcal{K}}\mathbb{P}(z(t) = z \mid z(0) = z')\Bigg| \leq K_1 e^{-t/K_2},\]
Further, given any $\beta\in\mathbb{N}$, for each agent $i$ and $z' \in \mathcal{Z}_{{\cN_i^{\beta}}}$, define $d^{\hat{\zeta}}_{i, \beta}(z') = \sum_{z \in \mathcal{Z}: z_{{\cN_i^{\beta}}} = z'} d^{\hat{\zeta}}(z)$, which is the marginal stationary distribution for the state-actions in ${\cN_i^{\beta}}$, and define $\xi(\sigma,\beta) := \inf_{i \in \mathcal{N}, z' \in \mathcal{Z}_{{\cN_i^{\beta}}}} d^{\hat{\zeta}}(z')$ as the minimum probability in this distribution.
\end{lemma}
\Cref{network-assp:geometric-mixing} is an immediate implication of a result on the sufficient exploration of non-deterministic policies stated in \Cref{ap:exploration}. Note that the only assumption we need here is that there exists a policy $\zeta_b$ such that the induced Markov chain $\{S_k\}$ is irreducible and aperiodic (\Cref{as:MC}). This is in contrast with the analysis in existing literature, where \Cref{network-assp:geometric-mixing} is directly assumed to hold \citep{qu2020scalablelocal}. Therefore, our proof of \Cref{network-assp:geometric-mixing} is of independent interest in the literature of policy evaluation.
\Cref{network-assp:geometric-mixing} enables us to apply Theorem 3.2 in \cite{lin2021multi} to show that $\beta$-hop Localized TD(0) is a $(\sigma, \nu',\mu)$-exact policy evaluation algorithm.
\begin{theorem}\label{thm:beta-hop-policy-evaluation}
Suppose the policy $\hat{\zeta}$ we want to evaluate is $\sigma$ regular and under the policy, the local $Q$-functions satisfy the $(\nu', \mu)$-decay property. Suppose $K_1(\sigma), K_2(\sigma), \xi(\sigma,\beta)$ are the constants in \Cref{network-assp:geometric-mixing}. Recall that the local reward at every time step is upper bounded by $\bar{r}$. Let the step size of \Cref{alg:beta-hop-TD-0} be $\alpha_t = \frac{H}{t + t_0}$ with $t_0 = \max(4H, 2K_2 \log T)$, and $H = \frac{2}{(1 - \gamma) \xi(\sigma,\beta)}$. Then, \Cref{alg:beta-hop-TD-0} is $(\sigma,\nu',\mu)$-exact with constant $c_{pe}(\delta,\sigma,\nu',\mu) = \frac{2 \nu'}{1 - \gamma}$ and $T_{eval}(\delta,\sigma,\nu',\mu, \beta)$ is upper bounded by{\small
\begin{align}
\tilde{O}\Bigg(\frac{(\beta + 1)^{2\mu} (\bar{r} + \tau \log A_{\max})^2 K_2(\sigma) \log(f(\beta)K_2(\sigma)/\delta)}{(\nu')^2(1 - \gamma)^4(\xi(\sigma,\beta))^2} + \frac{(\beta + 1)^\mu (\bar{r} + \tau \log A_{\max}) (K_1(\sigma) + 1)(K_2(\sigma) + 1)}{\nu'(1 - \gamma)^2(\xi(\sigma,\beta))^2}\Bigg), \label{eq:T_eval}
\end{align}}
where we recall $f(\beta) = \sup_{i \in \mathcal{N}} \big|\mathcal{N}_i^\beta\big|$ is the size of the largest $\beta$-hop neighborhood.
\end{theorem}
\section{Convergence Proof for Localized Policy Iteration}
We now prove our main results for the convergence of $\text{LPI}$. The key technical idea underlying our analysis is a novel closure property for a class of policies with spatially decaying properties. We introduce this property first, and then apply it to prove the results in the previous sections.
\subsection{Key Idea: Closure of Decay Policy Class under Policy Iteration} \label{subsec:keyidea}
We first present a prototype algorithm in \Cref{alg:prototype}, which is an exact policy iteration algorithm that runs exact policy evaluation followed by exact policy improvement to update the global policy. While this algorithm is not practical, it is useful in developing a generic framework to analyze the convergence of $\text{LPI}$ (\Cref{alg:SVI}). %
For that purpose, in this subsection we prove an important ``closure'' property of the prototype algorithm (\Cref{alg:prototype}): when starting at an initial policy in a decay policy class $\Delta_{\nu,\mu,\sigma}$ (defined in~\Cref{def:mu_decay_policy}), the policy at every iteration of the prototype algorithm remains in the same $\Delta_{\nu,\mu,\sigma}$ class. This property provides the foundation of our proof for both \Cref{thm:subopt_dist_policy} and \Cref{thm:convergence_svi}. %
\begin{algorithm}[ht]
\caption{Exact Policy Iteration (Prototype)}\label{alg:prototype}
\begin{algorithmic}[1]
\STATE \textbf{Input:} initial global policy $\zeta_0$.
\FOR{$m = 0, 1, 2, \cdots, M-1$}
\STATE Calculate the $Q$-function for policy $\zeta^{m}$ as $Q^{\zeta^{m}}$
\STATE Updates the global policy $\zeta^{m+1}=(\zeta_{1}^{m+1},\ldots,\zeta_{n}^{m+1})$, where
\begin{align*}
\{\zeta_{i}^{m+1}(\cdot|s)\}_{i\in\mathcal{N}}=\argmax_{\pi_1(\cdot|s)\in \Delta_{\mathcal{A}_1}, \ldots, \pi_n(\cdot|s)\in \Delta_{\mathcal{A}_n}} \mathbb{E}_{a_1\sim \pi_1(\cdot|s),\ldots, a_n\sim \pi_n(\cdot|s)}\bigg[ Q^{\zeta^{m}}(s,a) - \sum_{i=1}^n \tau \log \pi_i(a_i|s) \bigg].
\end{align*}
\ENDFOR
\STATE \textbf{Output:} $\zeta^{M}$
\end{algorithmic}
\end{algorithm}
\textbf{Closure of $\Delta_{\nu,\mu,\sigma}$ under \Cref{alg:prototype}.} In \Cref{thm:convergence_prototype}, we formally establish the property that when starting with $\zeta^0\in\Delta_{\nu,\mu,\sigma}$, the iterates in \Cref{alg:prototype} remain in the policy class $\Delta_{\nu,\mu,\sigma}$. The proof of \Cref{thm:convergence_prototype} can be found in \Cref{sec:proof_of_closure}.
\begin{theorem}\label{thm:convergence_prototype}
Suppose $\gamma<0.8$ and $\tau \geq 6\bar{r} \frac{4-3\gamma}{4-5\gamma}A_{\max}^2 e$, and $\forall i, \sum_{j\in \mathcal{N}_i}C_{ij}<1/2$. Define
\begin{align*}
\nu = 1/2, \quad \mu= \min\bigg\{\log_2 \frac{\tau(4-5\gamma)}{6\bar{r}A_{\max}^2 e(4-3\gamma)} ,\log_2 \frac{1}{2 \sup_{i\in\mathcal{N}}\sum_{j\in \mathcal{N}_i}C_{ij}}\bigg\}, \quad \sigma = \frac{\bar{r}(4-3\gamma)}{(4-5\gamma)n\tau}.
\end{align*}
Then, the following holds.
\begin{itemize}
\item [(a)] When initial policy satisfies $\zeta^0\in\Delta_{\nu,\mu,\sigma}$, all iterates $\zeta^m$ in \Cref{alg:prototype} will be in $\Delta_{\nu,\mu,\sigma}$.
\item [(b)] $Q^{\zeta^m}$ is $(\nu',\mu)$-decay with $ \nu' = \bar{r} \frac{4-3\gamma}{4-5\gamma}$.
\item [(c)] $V^{\zeta^m}$ converges to the unique fixed point $V^*$ of $\mathcal{T}$ with geometric rate, i.e. $\Vert V^{\zeta^m} - V^* \Vert_\infty \leq \gamma^{m} \Vert V^{\zeta^0} - V^* \Vert_\infty$.
\end{itemize}
\end{theorem}
The results in \Cref{thm:convergence_prototype} demonstrate that the defined policy class $\Delta_{\nu,\mu,\sigma}$ is closed under the policy iteration operator in \Cref{alg:prototype}. This key observation provides a pathway for proving our main theoretical results, as we explain below.
\textbf{Pathway to prove \Cref{thm:subopt_dist_policy}.} Based on the closure of the policy class $\Delta_{\nu,\mu,\sigma}$, the optimal policy is also in $\Delta_{\nu,\mu,\sigma}$. We show that if we ``truncate'' the optimal policy to a $\kappa$-hop policy, the performance loss is on the order of $O(\frac{1}{(\kappa+1)^\mu})$. This directly leads to a proof of \Cref{thm:subopt_dist_policy}, which we detail in \Cref{subsec:proof_dist_policy_subopt}.
\textbf{Pathway to prove \Cref{thm:convergence_svi}.} A second consequence of \Cref{thm:convergence_prototype} is that we can view \Cref{alg:SVI} as an inexact version of the prototype algorithm (\Cref{alg:prototype}), which reduces the complexity in implementation, communication, and training. Specifically, \Cref{alg:SVI} introduces the following types of errors:
\begin{itemize}[leftmargin=*]
\item \textit{Error caused by truncated $Q$-functions}: In \Cref{alg:SVI}, we only learn $\beta$-hop truncated versions of the $Q$-functions. By \Cref{thm:convergence_prototype}, the true $Q$-functions are $(\nu',\mu)$-decay, and as a result, the truncation causes an error on the order of $O(\frac{1}{(\beta+1)^\mu} )= O(\frac{1}{(\kappa+1)^\mu})$ (Noticing $\kappa\leq \beta$).
\item \textit{Error caused by truncated policies}: We only learn $\kappa$-hop truncated policies, which also causes an $O(\frac{1}{(\kappa+1)^\mu})$ error.
\item \textit{Error caused by inexact policy evaluation}: Since we use finite samples to estimate the truncated $Q$-functions, this causes statistical errors depending on the sample size. However, with high probability, this error diminishes to $0$ as the number of samples $T$ increases.
\item \textit{Error caused by inexact policy improvement}: In \Cref{alg:SVI}, we cannot directly implement the $\arg\max$ procedure as in \Cref{alg:prototype}. Instead, we use an iterative procedure \eqref{eq:algo_policyimprovement}, which we later show corresponds to the mirror descent algorithm for solving the $\arg\max$. This causes an optimization error, which diminishes to $0$ as the number of iterations $p_{\max}$ for \eqref{eq:algo_policyimprovement} increases.
\end{itemize}
As discussed above, the first two types of errors can be bounded by the order of $O(\frac{1}{(\kappa+1)^\mu})$ which depends on the size of the neighborhood in our localized approximation of the policy and the $Q$ functions, while the last two types of errors can be made arbitrarily small as long as the algorithm is run for sufficiently many steps. This eventually leads to a proof of \Cref{thm:convergence_svi}, which we detail in \Cref{subsec:convergence_proof}.
\subsection{Proof of \Cref{thm:subopt_dist_policy}: Near-optimality of $\kappa$-hop Policies}\label{subsec:proof_dist_policy_subopt}
As discussed in \Cref{subsec:keyidea}, the optimal policy $\zeta^*$ is a $\sigma$-regular $(\nu,\mu)$-decay policy with the values of $\nu,\mu,\sigma$ given by the condition in \Cref{thm:convergence_prototype}. To prove \Cref{thm:subopt_dist_policy}, we simply truncate the optimal policy to the $\kappa$-hop neighborhood. Specifically, the ``truncated'' policy is defined as
\begin{align}
\hat{\zeta}_i^*(\cdot|s_{{\color{black}\cN_i^{\khop}}}) = \zeta_i^*(\cdot|s_{{\color{black}\cN_i^{\khop}}},s^{\mathrm{default}}_{{\color{black}\cN_{-i}^{\khop}}}), \forall i.
\end{align}
For any $i\in\mathcal{N}$, $s\in\mathcal{S}$, for the simplicity of notations, we re-order the set $\mathcal{N}$ as follows
\begin{align*}
\{l_1,\ldots,l_{|{\color{black}\cN_{-i}^{\khop}}|},l_{|{\color{black}\cN_{-i}^{\khop}}|+1},\ldots,l_n\},
\end{align*}
where $\{l_1,\ldots,l_{|{\color{black}\cN_{-i}^{\khop}}|}\}={\color{black}\cN_{-i}^{\khop}}$
and $\{l_{|{\color{black}\cN_{-i}^{\khop}}|+1},\ldots,l_n\}={\color{black}\cN_i^{\khop}}$. We also use $\mathcal{N}_{[l_j]}$ to denote $\{l_1,\ldots,l_j\}$ and $\mathcal{N}/\mathcal{N}_{[l_j]}$ to denote $\{l_{j+1},\ldots,l_n\}$. Then, using the triangle inequality we have
\begin{align}\label{eq:tv_dist_triangle_decompose}
\mathrm{TV}(\hat{\zeta}_i^*(\cdot|s_{{\color{black}\cN_i^{\khop}}}),\zeta_i^*(\cdot|s))&\leq \sum_{j=|{\color{black}\cN_{-i}^{\khop}}|}^{1}\mathrm{TV}(\zeta_i^*(\cdot|s_{\mathcal{N}_{[l_j]}}^{\mathrm{default}},s_{\mathcal{N}/\mathcal{N}_{[l_j]}}),\zeta_i^*(\cdot|s_{\mathcal{N}_{[l_{j-1}]}}^{\mathrm{default}},s_{\mathcal{N}/\mathcal{N}_{[l_{j-1}]}})),
\end{align}
where we define $\mathcal{N}_{l_0}=\Phi$ to be the empty set, which implies for $j=1$, $\mathcal{N}/\mathcal{N}_{[l_{j-1}]}=\mathcal{N}$ and $s_{\mathcal{N}/\mathcal{N}_{[l_{j-1}]}}=s$ is the global state. By the definition of the interaction matrix in \Cref{def:mu_decay_policy}, we immediately have
\begin{align} \label{eq:proof_thm1:tv_bound}
\sup_{i\in\mathcal{N}}\sup_{s\in\mathcal{S}} \mathrm{TV}(\hat{\zeta}_i^*(\cdot|s_{{\color{black}\cN_i^{\khop}}}),\zeta_i^*(\cdot|s))
& \leq \sup_{i\in\mathcal{N}}\sum_{j\in \mathcal{N}_{-i}^\kappa } Z^{\zeta^*}_{ij} \nonumber \\
&\leq \frac{1}{(\kappa+1)^\mu} \sup_{i\in\mathcal{N}}\sum_{j\in \mathcal{N}_{-i}^\kappa } (\mathrm{dist}(i,j)+1)^\mu Z_{ij}^{\zeta^*}\nonumber\\
&\leq \frac{\nu}{(\kappa+1)^\mu},
\end{align}
where the second inequality is due to \eqref{eq:mu_decay_imply_distance_decay} and the last inequality holds because $\zeta^*$ is in the $(\nu,\mu)$-decay class. This further indicates $\hat{\zeta}_i^*$ is $O(\frac{1}{(\kappa+1)^\mu})$ close to $\zeta_i^*$.
To proceed, we introduce the following performance difference bound that bounds the value functions of two policies by the $\mathrm{TV}$ distance between the two policies:
\begin{lemma}\label{lem:performance_diff_tv}
Suppose $\zeta,\tilde{\zeta}\in\Delta_{\mathrm{policy}}$ are $\sigma$-regular, and further, $Q^{\tilde{\zeta}}$ is $(\nu',\mu)$-decay. Then, we have
\begin{align}
\Vert V^\zeta-V^{\tilde{\zeta}}\Vert_\infty\leq \frac{1}{1-\gamma} \bigg(\tau\sigma + \frac{\nu'}{n}\bigg) \sum_{i=1}^n \sup_{s\in\mathcal{S}}\mathrm{TV}(\tilde\zeta_i(\cdot|s),\zeta_i(\cdot|s)).
\end{align}
\end{lemma}
With the above \Cref{lem:performance_diff_tv}, we have
\begin{align*}
J(\zeta^*) - J(\hat{\zeta}^*) &= \mathbb{E}_{s \sim\rho}\left( V^{\zeta^*}(s) - V^{\hat{\zeta}^*}(s)\right)
\leq \Vert V^{\zeta^*} - V^{\hat{\zeta}^*}\Vert_\infty \\
&\leq \frac{1}{1-\gamma} \bigg(\tau\sigma + \frac{\nu'}{n}\bigg) \sum_{i=1}^n \sup_{s\in\mathcal{S}}\mathrm{TV}(\zeta_i^*(\cdot|s),\hat{\zeta}_i^*(\cdot|s))
\leq \frac{1}{1-\gamma} (n\tau\sigma + \nu') \frac{\nu}{(\kappa+1)^\mu}\\
&\leq {\frac{\bar{r} (4-3\gamma)}{(1-\gamma)(4-5\gamma)} \frac{1}{(\kappa+1)^\mu},}
\end{align*}
where in the last inequality, we have plugged in { $n\tau\sigma = \nu' = \bar{r} \frac{4-3\gamma}{4-5\gamma}$ and $\nu=1/2$. }
This demonstrates that the $\kappa$-hop policy $\hat{\zeta}^*$ is $O(\frac{1}{\kappa^\mu})$-optimal, and setting $\hat{\zeta}^{*,\kappa}$ as $\hat{\zeta}^*$ concludes the proof of \Cref{thm:subopt_dist_policy}.
\subsection{Proof of \Cref{thm:convergence_svi}: Convergence Analysis of Localized Policy Improvement} \label{subsec:convergence_proof}
In this section, we prove the convergence of $\text{LPI}$.
Our proof uses an induction argument, and the induction assumption is that, at the $m$-th iteration of \Cref{alg:SVI}, the policy $\hat{\zeta}^m$ is $\tilde\sigma$ regular and its local $Q$-functions $\{ Q_i^{\hat{\zeta}^m}\}_{i=1}^n$ is $(\nu',\mu)$-decay, with constants $\tilde\sigma,\nu',\mu$ given in \Cref{thm:convergence_svi}'s statement. This induction assumption is clearly true for $m=0$ because of \Cref{lem:policy-q} and the fact that $\hat{\zeta}^0$ is a uniform policy.
Now under this induction assumption, we first show that the local $Q$ functions $\hat{Q}_i^m$ returned by the policy evaluation step (i.e., the ${\texttt{PolicyEvaluation}}$ subroutine in Line~\ref{algo:policy_evaluation_return}) of \Cref{alg:SVI} is a good approximation of the true local $Q$-functions $Q_i^{\hat{\zeta}^m}$ of the policy $\hat{\zeta}^m$.
More specifically, recall that we assumed the policy evaluation step in \Cref{alg:SVI} is $(\tilde{\sigma},\nu',\mu)$-exact as defined in \Cref{def:beta-hop-state-aggregation-policy-eva}. This means for any given $\delta \in (0, 1)$ and $\beta\in\mathbb{N}$, there exists constants $T_{eval}(\frac{\delta}{M},\tilde{\sigma},\nu',\mu, \beta), c_{pe}(\frac{\delta}{M},\tilde{\sigma},\nu',\mu)$ such that when the input trajectory to ${\texttt{PolicyEvaluation}}$ has length $T \geq T_{eval}(\frac{\delta}{M}, \tilde{\sigma},\nu',\mu,\beta)$ steps, its output $\hat{Q}_i^m$ satisfies
\begin{align}\label{lem:policy_evaluation_error}
\forall i, \sup_{(s, a) \in \mathcal{S}\times \mathcal{A}}\abs{Q_i^{\hat{\zeta}^m}(s, a) - \hat{Q}_i^m(s_{{\cN_i^{\beta}}}, a_{{\cN_i^{\beta}}})} \leq \frac{c_{pe}(\frac{\delta}{M},\tilde{\sigma},\nu',\mu)}{(\beta + 1)^\mu}:=\epsilon
\end{align}
with probability at least $1 - \frac{\delta}{M}$. In the rest of the proof, we write $c_{pe}(\frac{\delta}{M},\tilde{\sigma},\nu',\mu)$ as $c_{pe}$ for simplicity.
Given \eqref{lem:policy_evaluation_error}, we next show that the policy improvement step (Line \ref{algo:policy_improvement_return}) of \Cref{alg:SVI} returns a $\tilde\sigma$ regular policy $\hat\zeta^{m+1}$ that is $O(\frac{1}{\kappa^\mu})$ close to the policy given by the optimal Bellman operator, and further $\{Q_i^{\hat\zeta^{m+1}}\}$ is $(\nu',\mu)$ decay.
More precisely, we present the following \Cref{lem:policy_improvement_error}, the full proof of which can be found in \Cref{sec:proof_policy_improvement_error}.
\begin{lemma}\label{lem:policy_improvement_error} Consider the settings of \Cref{thm:convergence_svi}. Suppose at iteration $m$, the local $Q$-functions $\{ Q_i^{\hat{\zeta}^m}\}_{i=1}^n$ is $(\nu',\mu)$-decay and \eqref{lem:policy_evaluation_error} is true. %
Then, the policy improvement part (Line \ref{algo:policy_improvement_return}) will return a policy $\hat{\zeta}^{m+1}$ that satisfies
\begin{align}
\mathcal{T} V^{\hat{\zeta}^m} - V^{\hat{\zeta}^{m+1}} \leq \frac{3(4-3\gamma)\bar{r} }{(1-\gamma)(4-5\gamma)} \frac{4 + c_{pe} (4-5\gamma)/(2^{\mu}(4-3\gamma)\bar{r})}{(\kappa/2+1)^\mu} \mathbf{1} := \frac{c_{pi}}{(\kappa/2+1)^\mu} \mathbf{1}, \label{eq:policy_improvement_error}
\end{align}
where $\mathcal{T}$ is the global Bellman optimal operator with entropy regularization defined in \eqref{eq:bellman_operator}. Further, $\hat{\zeta}^{m+1}$ is $\tilde\sigma$ regular and $Q^{\hat{\zeta}^{m+1}}$ is $(\nu',\mu)$-decay.
\end{lemma}
Note that \Cref{lem:policy_improvement_error} implies that $\hat{\zeta}^{m+1}$ is $\tilde\sigma$-regular and $Q^{\hat{\zeta}^{m+1}}$ is $(\nu',\mu)$-decay. Therefore, conditioned on the induction assumption for $m$, the induction assumption holds for $m+1$ with probability at least $1-\frac{\delta}{M}$. As a consequence, using a union bound, we must have with probability at least $1-\delta$, for all $m=0,\ldots,M-1$, the induction assumption, and by extension \eqref{eq:policy_improvement_error}, is true. We now condition on this event to show the final convergence bound.
For any $m=0,\ldots, M-1$, by \eqref{eq:policy_improvement_error},
\begin{align*}
0\leq V^* - V^{\hat{\zeta}^{m+1}} &= V^* - \mathcal{T} V^{\hat{\zeta}^{m}} + \mathcal{T} V^{\hat{\zeta}^{m}}- V^{\hat{\zeta}^{m+1}}\leq \Vert \mathcal{T} V^{\hat{\zeta}^{m}} - V^* \Vert_\infty \mathbf{1} + \frac{c_{pi}}{(\kappa/2+1)^\mu} \mathbf{1} .
\end{align*}
Taking the infinity norm, we get
\begin{align*}
\Vert V^* - V^{\hat{\zeta}^{m+1}}\Vert_\infty&\leq \Vert \mathcal{T} V^{\hat{\zeta}^{m}} - V^* \Vert_\infty + \frac{c_{pi}}{(\kappa/2+1)^\mu} \leq \Vert \mathcal{T} V^{\hat{\zeta}^{m}} - \mathcal{T} V^* \Vert_\infty + \frac{c_{pi}}{(\kappa/2+1)^\mu}\\
&\leq \gamma \Vert V^{\hat{\zeta}^{m}} - V^*\Vert_\infty + \frac{c_{pi}}{(\kappa/2+1)^\mu}\leq \gamma^{m+1} \Vert V^{\hat{\zeta}^0} - V^*\Vert_\infty + \frac{1}{1-\gamma} \frac{c_{pi}}{(\kappa/2+1)^\mu},
\end{align*}
where the third inequality is due to \Cref{prop:exist_optimal_policy_entropy}. The desired convergence bound follows by noticing $ J(\zeta^*) - J(\hat{\zeta}^{M})\leq \Vert V^* - V^{\hat{\zeta}^M}\Vert_{\infty}$.
\section{Experiments}\label{sec:experiment}
Though the main focus of this paper is the theoretical convergence of the proposed localized algorithm $\text{LPI}$ to the global optimal policy, we also provide some preliminary experiments to demonstrate its empirical advantages in practice.
\subsection{Experimental Setup}
We first describe an example of networked MARL problems, where $n$ agents cooperatively work together to control the spread of a global process, e.g., information leakage or an infectious disease.
In particular, we consider $n$ agents that are connected through a line graph. For each agent $i\in[n]$, its state is a $2$-dimensional vector $s_i = (s^1_{i},s^2_{i})$, where $s^1_{i}$ and $s^2_{i}$ take binary values. Each agent has a binary action space, $a_i\in \{0, 1\}$. The value of $s^1_{i}$ in state $s_i$ obeys the following transition rule that is not affected by the action:
\begin{align*}
\bar{s}^1_i(t+1)=
\begin{cases}
1 & \text{if one of } s^1_{i-1}(t), s^1_i(t), s^1_{i+1}(t) = 1,\\
0 & \text{otherwise}.
\end{cases}\\
P(s^1_i(t+1)=1|\bar{s}^1_i(t+1))=
\begin{cases}
1-p_1 & \text{if } \bar{s}^1_i(t+1) = 1,\\
0 & \text{otherwise},
\end{cases}
\end{align*}
where $p_1\in(0,1)$. To interpret this, each agent first deterministically enters an intermediate state $\bar{s}^1_i(t+1)$ based on its own and neighbors' states in the previous time step. The true $s_i^1(t+1)$ of agent $i$ will be activated (set to $1$) with probability $1-p_1$ or $0$ according to the intermediate state.
Similarly, the value of $s_i^2$ in state $s_i$ obeys the following transition rule determined by the action:
\begin{align*}
P\big( \bar{s}^2_i(t+1)=1|s^2_i(t),a_i(t)\big)=
\begin{cases}
1 & \text{if } s^2_{i}(t)= 1,\\
p_{\text{eff}} & \text{if } s^2_{i}(t)= 0, a_i(t) = 1,\\
0 & \text{otherwise}.
\end{cases}
\end{align*}
\begin{align*}
P\big(s^2_i(t+1)=1|\bar{s}^2_i(t+1)\big)=
\begin{cases}
1-p_2 & \text{if } \bar{s}^2_i(t+1) = 1,\\
0 & \text{otherwise}.
\end{cases}
\end{align*}
Here $\bar s_i^2(t+1)$ is an intermediate state, which will be activated determnistically if the agent's previous state is already activated, i.e, $s_i^2(t)=1$, or activated with probability $p_{\text{eff}}$ if $s_i^2(t)=0$ but the agent takes action $1$. And the true $s_i^2(t+1)$ remains activated with probability $1-p_2$.
This model defines a simple form of propagating/spreading dynamics on a graph, with the agents' actions providing a mechanism to control the spread. We decompose the reward into two terms, one depending only on the state $s_i=(s_i^1,s_i^2)$ and the other depending only on the action,
$ r_i(s_i,a_i) = r_i^s (s_i^1,s_i^2) + r_i^a(a_i)$, where the state reward $r_i^s(\cdot)$ and action reward $r_i^a(\cdot)$ are defined as
\begin{align*}
r_i^s(s^a_i,s^b_i) =
\begin{cases}
0 & \text{if } s_i^1 =1, s_i^2 = 0, \\
1 & \text{otherwise}.
\end{cases}
\qquad
r_i^a(a_i) =
\begin{cases}
1 & \text{ if } a_i=0, \\
1 - c & \text{ if } a_i=1 .
\end{cases}
\end{align*}
It is easy to verify that states $(s_i^1, s_i^2) = (0,0), (1,1), (0,1)$ have a high state reward $r_i^s$, and $(s_i^1, s_i^2) = (1,0)$ has a low reward (or incurs a penalty). This corresponds to an agent incurring a penalty if a protection action is not taken before the dynamics reaches the agent. Furthermore, the protection action itself incurs a cost $c$ in the action reward $r_i^a$.
Intuitively, if an agent does not observe any of its $\kappa$-hop neighbors to have $s^1(t)=1$, it should take action $a(t)=0$ to get the largest action reward. However, if some of its neighboring agents have $s^1(t)=1$ and the cost $c$ of taking action $1$ is relatively small, it should take action $1$ to increase $s^2$ in order to get a reward $r^s=1$ even if its $s^1$ changes to $1$ at some time. If the probability $p_{\text{eff}}$ that action $a(t)=1$ being effective is smaller, the agent should start taking action $a=1$ earlier, when its nearest agent has $s^1(t)=1$ is at a larger distance, to make sure that it has a high probability to have $s^2=1$ when $s^1$ propagates to its position. In this sense, the optimal policy should depend on not only the local state but the states of other agents as well, and we can expect a large performance difference between localized policy with small $\kappa$ and the global optimal policy.
\paragraph{Parameter Settings}
In our experiments, we use a variation of $\beta$-hop Localized TD(0) which has a constant step size of $0.1$. We set $\beta=\kappa$ for simplicity. We set the environment parameters to be $p_1=0.6$, $p_2=0.7$, $c=0.3$ and $p_{\text{eff}}=0.4$. We set the training parameters to be $\gamma=0.95$ and $\eta=0.05$. We train $\text{LPI}$ for $50$ outer loops and in the inner loop we perform policy update (Line \ref{algo:policy_improvement} of \Cref{alg:SVI}) for $p_{\max}=10$ steps. %
For each experiment, we repeat it for $10$ times and plot the median in a solid line and $25/75$ percent performance values in the shaded area. %
\subsection{Experimental Results}
\begin{figure*}[t]
\centering
\subfigure[$\tau=0.02$]{\includegraphics[width=0.32\textwidth]{SIGMETRICS/figures/Plot-tau=0.02-nodeNum=8.pdf}}
\subfigure[$\tau=0.05$]{\includegraphics[width=0.32\textwidth]{SIGMETRICS/figures/Plot-tau=0.05-nodeNum=8.pdf}}
\subfigure[$\tau=0.1$]{\includegraphics[width=0.32\textwidth]{SIGMETRICS/figures/Plot-tau=0.1-nodeNum=8.pdf}}
\caption{Comparison of the performance of $\text{LPI}$ for different $\kappa$ under different levels of entropy regularization. %
\label{fig:comparison_differ_tau}}
\end{figure*}
In \Cref{fig:comparison_differ_tau}, we compare the performance of $\text{LPI}$ with different choices of $\kappa$, which represents how much local information we used in the local policy learning on each agent. We also present different levels of entropy regularization in each subfigure of \Cref{fig:comparison_differ_tau} by setting $\tau=0.02,0.05$ and $0.1$. We set $n=8$ in the line graph. It can be seen that a larger $\kappa$ leads to a better total regularized reward but a lower convergence rate, which is consistent with our theoretical findings. %
\begin{figure*}[t]
\centering
\subfigure[$n=5$]{\includegraphics[width=0.32\textwidth]{SIGMETRICS/figures/Plot-tau=0.03333333333333333-nodeNum=5.pdf}}
\subfigure[$n=10$]{\includegraphics[width=0.32\textwidth]{SIGMETRICS/figures/Plot-tau=0.06666666666666667-nodeNum=10.pdf}}
\subfigure[$n=15$]{\includegraphics[width=0.32\textwidth]{SIGMETRICS/figures/Plot-tau=0.1-nodeNum=15.pdf}}
\caption{Comparison of the performance of $\text{LPI}$ for different $\kappa$ in the settings with different network sizes. %
\label{fig:comparison_differ_networksize}}
\end{figure*}
In \Cref{fig:comparison_differ_networksize}, we illustrate that our algorithm works for various network sizes by comparing the training curves among different network sizes $n=5, 10$ and $15$ while keeping $\tau$ as a constant. In each plot in \Cref{fig:comparison_differ_networksize}, larger $\kappa$ always leads to a better total regularized reward. Also, by comparing these three plots, we can see similar convergence rates for different network sizes. This shows that our algorithm has similar per-agent efficiency for networks of different scales.
We note that some of our settings violate the bounds on $\tau$ and $\eta$ in our theorems, while $\text{LPI}$ still performs well. Thus, in practice, one can expect our algorithm to be applicable to a larger problem class than suggested by our theoretical analysis, which could be conservative.
\section{Conclusion and Future Work}
This paper studies a cooperative MARL problem in networked systems. We provided the first theoretical guarantee on the performance gap between localized polices that make decisions only based on the information within a neighborhood of each agent and the optimal centralized policy. We achieved this by showing that a $\kappa$-hop localized policy where each agent chooses actions based on the states of its $\kappa$-hop neighbors is nearly globally optimal. Our analysis relies on a novel characterization of a class of spatial decaying policies. Further, we proposed a specific algorithm, Localized Policy Iteration ($\text{LPI}$), that learns a policy in this class. $\text{LPI}$ is communication-efficient and scales to large networked systems due to its localized implementation. We further provided a finite-sample analysis of $\text{LPI}$ showing that it converges to the globally optimal centralized policy and achieves $\varepsilon$-optimality using only local information of the $\kappa=\Theta(\text{poly}(1/\varepsilon))$-hop neighborhood of each agent. It is worth noting that $\text{LPI}$ is the first localized algorithm that converges to the centralized globally optimal policy in the networked MARL setting. Finally, we conducted numerical experiments on a MARL problem where multiple agents on a graph cooperate together to control the spreading dynamics of a global process such as information leakage or disease transmission. %
There are many interesting questions motivated by this work. For example, it remains an open problem whether the polynomial dependence of the optimality gap on the neighborhood size $\kappa$ can be improved to an exponential decaying gap, which has been shown in the LQC setting by \citet{shin2022near}. It is also interesting to explore whether our analysis extends to the competitive MARL setting, where the objectives of agents are different from each other.
| {'timestamp': '2022-12-01T02:18:16', 'yymm': '2211', 'arxiv_id': '2211.17116', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17116'} | arxiv |
\section*{Introduction}\label{S:one}
As many engineering applications have become increasingly reliant on user data, data privacy has become a concern that data aggregators and curators must take into consideration. In numerous applications, such as
healthcare~\cite{YANG20181437}, energy systems~\cite{Asghar2017}, transportation systems~\cite{Zhang2018} and Internet of Things (IoT)~\cite{Medaglia2010},
the data gathered to support system operation
often contains sensitive individual information. Differential privacy~\cite{Dwork2014} has emerged as a standard privacy framework
that can be used in such applications to protect sensitive data while allowing
privatized data to remain useful.
Differential privacy is a statistical notion of privacy that provides privacy guarantees
by adding carefully calibrated noise to sensitive data or functions of sensitive data.
Its key features include: (i) it is robust to side information, in that any additional knowledge about data-producing entities does not weaken
their privacy by much~\cite{Kasiviswanathan_Smith_2014}, and (ii) it is immune to post-processing, in that any transformation of private data stays private~\cite{Dwork2014}.
Well-known mechanisms for the enforcement of differential privacy include
the Laplace mechanism~\cite{Dwork2006}, the Gaussian mechanism~\cite{Dwork2014},
and the exponential mechanism~\cite{McSherry2007,McSherry2009}. Other mechanisms have
been developed for specific applications, in some cases
by building upon or modifying these
well-known mechanisms. A representative sample
includes the Dirichlet mechanism on the unit
simplex~\cite{Gohari2021}, mechanisms for sensitive words
of symbolic data~\cite{chen2022}, the matrix-variate Gaussian
mechanism for matrix-valued queries~\cite{chanyaswad2018},
and the XOR mechanism for binary-valued data~\cite{ji2021}.
As the use of differential privacy has grown, these and other mechanisms
have been needed to respond to privacy needs in settings with
constraints on allowable data.
The Gaussian mechanism has been used for some classes of numerical data, although it may also require modifications for some types
of sensitive data because the Gaussian mechanism adds unbounded noise. For example,
the Gaussian mechanism may generate
negative values for data such as ages, salaries, and weights, and
such negative values are not meaningful in these contexts.
One attempt to solve this problem is through
projecting out-of-domain results back to the closest value in the given domain.
Although this procedure does not weaken differential privacy because
it is only post-processing on private data,
it has been observed to lead to low accuracy in applications~\cite{holohan2018bounded} and
thus is undesirable. Nonetheless, the Gaussian mechanism has been
used in numerous applications, including deep learning~\cite{Abadi2016}, \cite{Yu2019}, convex optimization~\cite{Bassily2014}, filtering and estimation problems~\cite{Le2014} and cloud control~\cite{Hale2018},
all of which can use data that is inherently bounded in some way.
On the other hand, compared to the Laplace mechanism, which is another popular privacy mechanism designed for
numerical data, the Gaussian mechanism is able to use lower-variance noise to provide the same privacy level for
high-dimensional data. This is because the variance of privacy noise
is an increasing function of the sensitivity of
a given query, and the Gaussian mechanism allows the use of the~$L_2$ sensitivity which, in
applications like
federated learning~\cite{Wei2020} and deep learning~\cite{Abadi2016}, is much lower than the $L_1$ sensitivity used
in Laplace mechanism.
Therefore, in this paper we develop a new type of Gaussian mechanism that
accounts for the boundedness of semantically valid data in a given application.
In the univariate case we consider data confined to a closed interval, and
in the multivariate case we consider data confined to a product of closed
intervals. For both cases we show that the bounded Gaussian
mechanism provides~$\epsilon$-differential privacy, rather
than~$(\epsilon, \delta)$-differential privacy as is provided by the
ordinary Gaussian mechanism. We also present algorithms for finding
the minimum variance necessary to enforce~$\epsilon$-differential privacy
using the bounded Gaussian mechanism. The mechanisms we develop do not rely on projections
and thus avoid the harms to accuracy that can accompany projection-based approaches.
Besides, \cite{Balle2018} point out that the original Gaussian mechanism's variance bound is far from tight when the privacy parameter $\epsilon$ approaches either $0$ or $\infty$. This is because the original Gaussian mechanism calibrates noise with a worst-case bound which is only tight for a small range of $\epsilon$. In this work, we present
bounded mechanisms that address this limitation by leveraging the boundedness of the domains we consider.
This boundedness excludes the tail of each Gaussian distribution from our analysis and allows for the development of tight bounds
on the variance of noise required for all~$\epsilon$.
Related work in~\cite{holohan2018bounded} developed a bounded Laplace mechanism,
and in this work we bring the ability to bound private data to the
Gaussian mechanism. Developments in~\cite{Liu2019} include
a generalized Gaussian mechanism with bounded support, and we show
in Section~\ref{S:algo} that the mechanism developed in this paper
requires significantly lower variance of noise to attain
differential privacy and thus provides improved accuracy.
\textbf{Notation} Let $\mathbb{N}$ denote the set of all positive integers and
let $I$ denote the identity matrix.
We use non-bold letters to denote scalars, e.g., $a\in\mathbb{R}$, and we use
bold letters denote vectors, e.g., $\mathbf{b}\in\mathbb{R}^n$.
All intervals of the form~$[a, b]$ are assumed to have~$a < b$. For~$\mathbf{a},\mathbf{b} \in \mathbb{R}^m$
we define~$[\mathbf{a}, \mathbf{b}] = [a_1, b_1] \times [a_2, b_2] \times \cdots \times [a_m, b_m]$.
We also use the function
\begin{equation*}
\text{erf}(z) = \frac{2}{\sqrt{\pi}}\int_0^z e^{-t^2}dt.
\end{equation*}
\section{Preliminaries and Problem Statement}
This section gives background on differential privacy and problem statements that are the focus of the remainder of the paper.
\subsection{Differential Privacy Background}
Differential privacy is enforced by a \emph{mechanism}, which is a randomized map.
We let~$S$ denote the space of sensitive data of interest.
For nearby pieces of sensitive data, a mechanism must produce outputs that are approximately distinguishable. The definition of “nearby” is given by an adjacency relation.
\begin{defi}[Adjacency]
Fix $k\in\mathbb{N}$. Two databases $d,d'\in S^n$ are adjacent if they differ in $k$ rows.
\end{defi}
For numerical queries $Q:S^n\rightarrow \mathbb{R}^m$, $m \in \mathbb{N}$, the sensitivity of a query~$Q$, denoted~$\Delta Q$, is used to calibrate
the variance of privacy noise used to implement privacy.
Throughout this paper we will use the~$\ell_2$-sensitivity.
\begin{defi}[$\ell_2$-Sensitivity]\label{def:sensitivity}
The $\ell_2$-sensitivity of a query $Q:S^n\rightarrow\mathbb{R}^m$ is
\begin{equation*}
\Delta Q := \max_{\text{adjacent }d,d'}||Q(d)-Q(d')||_2.
\end{equation*}
\end{defi}
The $\ell_2$ sensitivity captures the largest
magnitude by which the outputs of~$Q$ can change
across two adjacent input databases. We next introduce the definition of differential privacy itself.
\begin{defi}[Differential Privacy]
Fix a probability space~$(\Omega, \mathfrak{F}, \mathbb{P})$,
an adjacency parameter~$k \in \mathbb{N}$, a privacy parameter $\epsilon>0$, and a query $Q:S^n\rightarrow\mathbb{R}^m$. A mechanism $M: \Omega \times S^n \to \mathbb{R}^m$ is $(\epsilon,\delta)$-differentially private if for all measurable sets $A\subseteq\mathbb{R}^m$ and for all adjacent databases $d,d'\in S^n$ it satisfies
$\mathbb{P}\big[M(Q(d))\in A\big] \leq e^\epsilon\mathbb{P}\big[M(Q(d'))\in A\big]+\delta$.
\end{defi}
The privacy parameter $\epsilon$ sets the strength of privacy protections, and a smaller $\epsilon$ implies stronger privacy.
The parameter $\delta$ can be interpreted as a relaxation parameter, in the sense that
it is the probability that~$\epsilon$-differential privacy fails to hold~\cite{Beimel2013}
(though it may hold with a different value of~$\epsilon$).
If $\delta=0$, then a mechanism is said to be $\epsilon$-differentially private.
In the literature, $\epsilon$ has ranged from $0.01$ to $10$~(\cite{Hsu_2014}). A differential privacy mechanism guarantees that the randomized outputs of
two adjacent databases will be made approximately indistinguishable to any recipient of their privatized forms, including any eavesdroppers.
One widely used differential privacy mechanism is the Gaussian mechanism. The standard Gaussian mechanism is given by the following theorem:
\begin{thm}[Standard Gaussian Mechanism]
Let $\epsilon\in(0,1)$ and~$\delta \in (0, 1]$ be given. Fix an adjacency parameter~$k \in \mathbb{N}$.
For $c^2>2\ln{(1.25/\delta)}$ and a query $Q$ of the database $d$, the Gaussian mechanism $M_G(Q(d))=Q(d)+\eta$, $\eta \sim \mathcal{N}(\mathbf{0},\sigma^2I)$ with parameter $\sigma^2\geq c\Delta Q/\epsilon$ is $(\epsilon,\delta)$-differentially private.
\end{thm}
As discussed in the introduction, the Gaussian mechanism has been favored
over the Laplace mechanism in several applications, including deep learning,
empirical risk minimization, and various problems in control
theory and optimization. Simultaneously, these applications may have bounds
on the data they use, such as bounds on training data for a learning algorithm or
bounds on states in a control system, though the Gaussian mechanism has infinite
support and hence produces unbounded private outputs.
\subsection{Problem Statement}
In this work we seek a Gaussian
mechanism that respects given bounds on data, and we formalize the development
of this mechanism in the next two problem statements.
\begin{prob}[Univariate bounded Gaussian mechanism]\label{prob:univ_bd_gaus}
Given a query $Q:S^n\rightarrow D$, where $D=[a,b]\subset\mathbb{R}$ ($a<b$, both finite)
is a constrained domain, and a privacy parameter~$\epsilon > 0$,
develop a mechanism $M_B: \Omega \times S^n \to D$
that is an $\epsilon$-differentially private approximation of~$Q$
and generates outputs in~$D$ with probability~$1$.
\end{prob}
\begin{prob}[Multivariate bounded Gaussian mechanism]\label{prob:multi_bd_gaus}
Given a query $Q:S^n\rightarrow D$, where $D=[\mathbf{a},\mathbf{b}]\subset\mathbb{R}^m$
($a_i<b_i$, both finite for all $i$)
is a constrained domain,
and a privacy parameter~$\epsilon > 0$,
develop a mechanism $M_B: \Omega \times S^n \to D$
that is an $\epsilon$-differentially private approximation of~$Q$
and generates outputs in~$D$ with probability~$1$.
\end{prob}
We solve Problem~\ref{prob:univ_bd_gaus} in Section~\ref{sec:bounded_gaussian_mechanism},
and we solve Problem~\ref{prob:multi_bd_gaus}
in Section~\ref{sec:multivariate_mechanism}.
\section{Univariate Bounded Gaussian mechanism}\label{sec:bounded_gaussian_mechanism}
In this section, we develop the bounded Gaussian mechanism for a bounded domain $D=[a,b]\subset\mathbb{R}$.
We now give a formal statement of the univariate bounded Gaussian mechanism, and this
will be the focus of the rest of this section:
\begin{defi}[Univariate Bounded Gaussian Mechanism]\label{def:bounded_guassian}
Fix~$\sigma > 0$.
Let a query~$Q : S^n \to D$ be given where $D=[a,b]\subset\mathbb{R}$, and suppose that~$d \in S^n$
generates the output~$Q(d) = s \in D$.
Then the univariate bounded Gaussian mechanism $M_B:\Omega\times S^n\to D$
is given by the probability density function
\begin{equation}
p_B(x)=\begin{cases}
\frac{1}{\sigma}\frac{\phi\left(\frac{x-s}{\sigma}\right)}{\Phi\left(\frac{b-s}{\sigma}\right)-\Phi\left(\frac{a-s}{\sigma}\right)} & \text{if } x\in D,\\
0 & \text{otherwise,}
\end{cases}
\end{equation}
where
\begin{align*}
&\phi(x) = \frac{1}{\sqrt{2\pi}}\exp\left(-\frac{1}{2}x^2\right), \\
&\Phi(x) = \frac{1}{2}\left(1+\text{erf}(x/\sqrt{2})\right).
\end{align*}
\end{defi}
Since $Q(d)=s$, the density function $p_B(x)$ is not the same for each database, and data-dependent noise
is known to be problematic in general for differential privacy~\cite{Nissim2007}.
Therefore using the parameters of the standard Gaussian mechanism
is no longer guaranteed to satisfy differential privacy for the bounded Gaussian mechanism. We next provide the parameters
required for the bounded Gaussian mechanism to provide differential privacy by first introducing some preliminary results.
\subsection{Preliminary Results}
\begin{lem}\label{lem:preli_result_1}
Let~$\sigma>0$ be given. For a database $d\in S^n$
and a query~$Q$ with $Q(d)=s\in D$ and $D=[a,b]\subset \mathbb{R}$, let
\begin{align}
C(s,\sigma) = \frac{1}{\Phi\left(\frac{b-s}{\sigma}\right)-\Phi\left(\frac{a-s}{\sigma}\right)}.\label{eq:definition_C}
\end{align}
Let $d'\in S^n$ be adjacent to $d$ in the sense of Definition~\ref{def:sensitivity}, and suppose that $Q(d')=s'\in D$. Then we have
\begin{align*}
\max_{s,s'} \frac{C(s,\sigma)}{C(s',\sigma)} = \frac{C(a,\sigma)}{C(a+c,\sigma)},
\end{align*}
where $c=|s'-s|\leq \Delta Q$.
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_preli_result_1}.
\end{proof}
This leads to the following lemma.
\begin{lem}\label{lem:preli_result_2}
Let $C(s,\sigma)$ be given in Equation~\eqref{eq:definition_C}.
Given two adjacent databases $d\in S^n$ and $d'\in S^n$
and a query $Q:S^n\rightarrow D$,
suppose that
$Q(d)=s$ and $Q(d')=s'$ such that $s'=s+c$ and by the definition of adjacency we have $|c|\leq \Delta Q$.
Then
\begin{equation*}
\max_c \frac{C(a,\sigma)}{C(a+c,\sigma)}=:\Delta C(\sigma)=\begin{cases}
\frac{C(a,\sigma)}{C(a+\Delta Q,\sigma)} & \text{if } \Delta Q\leq\frac{b-a}{2},\\[5pt]
\frac{C(a,\sigma)}{C\left(\frac{b+a}{2},\sigma\right)} & \textnormal{otherwise.}
\end{cases}
\end{equation*}
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_preli_result_2}.
\end{proof}
\subsection{Main Result on the Univariate Bounded Gaussian Mechanism}
We now proceed to the main result of this section, which bounds the variance
required for the bounded Gaussian mechanism to provide~$\epsilon$-differential privacy.
\begin{thm}\label{thm:main_result_1}
Let~$\epsilon > 0$ and let a query~$Q : S^n \to D$ be given.
Suppose~$d\in S^n$ generates the output $Q(d)=s\in D$ and $D=[a,b]\subset \mathbb{R}$.
Then the Univariate Bounded Gaussian mechanism~$M_B$
provides~$\epsilon$-differential privacy if
\begin{equation}\label{eq:diff_pvt_one_d}
\sigma^2\geq \frac{\left[(b-a)+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C(\sigma))}.
\end{equation}
\end{thm}
\begin{proof}
See Appendix~\ref{apdx:proof_main_result_1}.
\end{proof}
We observe that in Equation~\eqref{eq:diff_pvt_one_d} the privacy noise variance $\sigma$ appears on both sides of the equation. Given a value of~$\epsilon > 0$, it is desirable to use
the smallest~$\sigma$ as this corresponds to using the smallest variance of privacy
noise for a given privacy level.
To do so, in the next section, we form a zero finding problem to find the
minimum~$\sigma$ that satisfies Equation~\eqref{eq:diff_pvt_one_d}.
\subsection{Calculating \texorpdfstring{$\sigma$}{Lg}}\label{sec:calculate_sigma}
Let $\sigma^*$ be the smallest admissible value of $\sigma$. The calculation of $\sigma^*$ can be formulated
as a zero finding problem, where we require
\begin{equation}
f(\sigma^*)=(\sigma^*)^2 - \frac{\left[(b-a)+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C(\sigma^*))}=0.\label{eq:function_f}
\end{equation}
We now present some technical lemmas concerning the function $f$ with respect to a point
\begin{equation}
\sigma_0=\sqrt{\frac{\left[(b-a)+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon}}.\label{eq:sigma_0}
\end{equation}
\begin{lem}\label{lem:denominator_greater_0}
For any $\epsilon>0$, we have $\epsilon-\ln(\Delta C(\sigma_0))>0$.
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_denominator_greater_0}.
\end{proof}
\begin{lem}\label{lem:delta_c_greater_0}
For all $\sigma\in(0,\infty)$, we have $\ln(\Delta C(\sigma))>0$.
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_delta_c_greater_0}.
\end{proof}
Next, Lemma~\ref{lem:lemma_f_sigma_0} shows the value of $f(\sigma_0)$ and Lemma~\ref{lem:lemma_f_decreasing} shows $f$ is a monotonically increasing function on $[\sigma_0,\infty)$.
\begin{lem}\label{lem:lemma_f_sigma_0}
For the point $\sigma_0=\sqrt{\frac{\left[(b-a)+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon}}$, we have $f(\sigma_0)<0$.
\end{lem}
\begin{proof}
By plugging in $\sigma_0$ we have
\begin{equation*}
f(\sigma_0)=\frac{\left[(b-a)+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon}-\frac{\left[(b-a)+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C(\sigma_0))}.
\end{equation*}
By Lemma~\ref{lem:denominator_greater_0} and Lemma~\ref{lem:delta_c_greater_0} we have $\epsilon>\epsilon-\ln(\Delta C(\sigma_0))>0$. Therefore $f(\sigma_0)<0$.
\end{proof}
\begin{lem}\label{lem:lemma_f_decreasing}
For any $\sigma\in[\sigma_0,\infty)$, we have $f'(\sigma)>0$.
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_lemma_f_decreasing}.
\end{proof}
By combining Lemma~\ref{lem:lemma_f_sigma_0} and Lemma~\ref{lem:lemma_f_decreasing}, we can use Algorithm 1 in~\cite{holohan2018bounded}, given below as Algorithm~\ref{alg:zero_finding_algorithm},
to find the exact fixed point of~$f$, which in our case is $\sigma^*$.
\begin{algorithm}
\SetAlgoLined
\SetKwInOut{Input}{Input}
\SetKwInOut{Output}{Output}
\Input{Function $f$ given in Equation~\eqref{eq:function_f}, initial condition for privacy noise variance $\sigma_0$ given in Equation~\eqref{eq:sigma_0}}
\Output{Optimal privacy parameter~$(\sigma^*)^2$}
left$=\sigma_0^2$\;
right$=\frac{\left[(b-a)+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C(\sigma_0))}$\;
intervalSize$=($left$+$right$)/2$\;
\While{intervalSize$>$right$-$left}{
intervalSize $=$ right $-$ left\;
$(\sigma^*)^2=\frac{\text{left}+\text{right}}{2}$\;
\If{$\frac{\left[(b-a)+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C(\sigma^*))}\geq(\sigma^*)^2$}{
left $=(\sigma^*)^2$\;
}
\If{$\frac{\left[(b-a)+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C(\sigma^*))}\leq(\sigma^*)^2$}{
right $=(\sigma^*)^2$ \;
}
}
\Return $(\sigma^*)^2$
\caption{A Zero Finding Algorithm}
\label{alg:zero_finding_algorithm}
\end{algorithm}
The output of Algorithm~\ref{alg:zero_finding_algorithm} can be used
in Definition~\ref{def:bounded_guassian} to form the univariate bounded Gaussian mechanism,
and Theorem~\ref{thm:main_result_1} shows that doing so provides~$\epsilon$-differential privacy.
We next present an analogous mechanism for multi-variate query responses.
\section{Multivariate Bounded Gaussian mechanism} \label{sec:multivariate_mechanism}
We begin by formally defining the multivariate bounded Gaussian mechanism, and it
will be the focus of the remainder of this section.
\begin{defi}[Multivariate Bounded Gaussian Mechanism]\label{def:bounded_guassian_nd}
Fix~$\sigma_m>0$. Let a query~$Q : S^n \to D$ be given, where $D=[\mathbf{a},\mathbf{b}]\subset \mathbb{R}^m$.
For a database $d\in S^n$ and its output $Q(d)=\mathbf{s}\in D$, the multivariate bounded Gaussian mechanism $M_B^m:\Omega\times \mathbb{R}^n\to D$ is given by the probability density function
\begin{equation}
p_B(\mathbf{x})=\begin{cases}
\frac{\exp{\left(-\frac{1}{2}(\mathbf{x}-\mathbf{s})^T\Sigma^{-1}(\mathbf{x}-\mathbf{s})\right)}}{\int_\mathbf{a}^\mathbf{b}\exp{\left(-\frac{1}{2}(\mathbf{x}-\mathbf{s})^T\Sigma^{-1}(\mathbf{x}-\mathbf{s})\right)}d\mathbf{x}} & \text{if } \mathbf{x}\in D,\\[5pt]
0 & \text{otherwise,}
\end{cases}
\end{equation}
where $\Sigma = \sigma_m^2I \in \mathbb{R}^{m \times m}$.
\end{defi}
Before introducing the this mechanism's differential privacy guarantee we first require some preliminary results.
\subsection{Preliminary Results}
\begin{lem}\label{lem:preli_result_3}
Fix~$\sigma_m>0$. For a database $d\in S^n$ and a query $Q(d)=\mathbf{s}\in D$ and $D=[\mathbf{a},\mathbf{b}]\subset \mathbb{R}^m$, let
\begin{align}
C_m(\mathbf{s},\sigma_m) = \frac{1}{\int_\mathbf{a}^\mathbf{b}\exp{\left(-\frac{1}{2}(\mathbf{x}-\mathbf{s})^T\Sigma^{-1}(\mathbf{x}-\mathbf{s})\right)}d\mathbf{x}}.\label{eq:definition_C_multidim}
\end{align}
Let an adjacent database $d'\in S^m$ satisfy $Q(d')=\mathbf{s}'\in D$. Then we have
\begin{align*}
\max_{\mathbf{s},\mathbf{s}'} \frac{C_m(\mathbf{s},\sigma_m)}{C_m(\mathbf{s}',\sigma_m)} = \frac{C_m(\mathbf{a},\sigma_m)}{C_m(\mathbf{a}+\mathbf{c},\sigma_m)},
\end{align*}
where $c_i=|s_i-s_i'|$ for the $i^{th}$ element of $\mathbf{c}\in\mathbb{R}^m$ and $||\mathbf{c}||_2\leq\Delta Q$.
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_preli_result_3}.
\end{proof}
Now we define $\Delta C_m(\sigma_m,\mathbf{c}^*)$, where
\begin{align*}
\frac{C_m(\mathbf{a},\sigma_m)}{C_m(\mathbf{a}+\mathbf{c},\sigma_m)}\leq \frac{C_m(\mathbf{a},\sigma_m)}{C_m(\mathbf{a}+\mathbf{c}^*,\sigma_m)}=:\Delta C_m(\sigma_m,\mathbf{c}^*),
\end{align*}
where $\mathbf{c}^*\in\mathbb{R}^m$ is the optimal value of $\mathbf{c}=(c_1,\dots,c_m)^T$ in the following optimization problem:
\begin{align}
\max_{\mathbf{c}\in\mathbb{R}^m}\,\,\,&\Delta C_m(\sigma_m,\mathbf{c})\label{eq:objective_function}\\
\text{subject to } \,\, &0\leq c_i\leq b_i-a_i \text{ for each }i\nonumber\\
&||\mathbf{c}||_2 \leq \Delta Q.\nonumber
\end{align}
\begin{rem}
The optimization problem in~\eqref{eq:objective_function} is a concave maximization problem.
In general, the value of~$c^*$ does not have a closed form, but it can be efficiently
computed
numerically using standard optimization software such as CVX or CasADi.
\end{rem}
\begin{comment}
\begin{lem}\label{lem:preli_result_4}
Let $C(\mathbf{s},\sigma_m)$ be given in Equation~\eqref{eq:definition_C_multidim}. For two adjacent database $d$ and $d'$ with a query $Q$. Let $Q(d)=\mathbf{s}$ and $Q(d')=\mathbf{s}'$ such that $\mathbf{s}'=\mathbf{s}+\mathbf{c}$ and $|\mathbf{c}|\leq \Delta Q$, then
\begin{equation*}
\frac{C(\mathbf{a},\sigma_m)}{C(\mathbf{a}+\mathbf{c},\sigma_m)}\leq\frac{C(\mathbf{a},\sigma_m)}{C\left(\frac{\mathbf{b}+\mathbf{a}}{2},\sigma_m\right)}\leq\Delta C_n(\sigma_m)=\exp\left(\frac{3||\mathbf{b-a}||_2^2}{8\sigma_m^2}\right)
\end{equation*}
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_preli_result_4}.
\end{proof}
\end{comment}
\subsection{Main Results}
We now proceed to the main result of this section, which bounds the variance
required for the multivariate bounded Gaussian mechanism to provide~$\epsilon$-differential privacy.
\begin{thm}\label{thm:main_result_2}
Let~$\epsilon>0$ and a query~$Q : S^n \to D$ be given.
For a database $d\in S^n$ and its output $Q(d)=\mathbf{s}\in D$, where $D=[\mathbf{a},\mathbf{b}]\subset \mathbb{R}^n$,
the multivariate bounded Gaussian mechanism $M_B$ provides $\epsilon$-differential privacy if
\begin{equation} \label{eq:sigma_m_multi}
\sigma_m^2\geq \frac{\left[||\mathbf{b-a}||_2+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C_m(\sigma_m,\mathbf{c}^*))}.
\end{equation}
\end{thm}
\begin{proof}
See Appendix~\ref{apdx:proof_main_result_2}.
\end{proof}
As with the univariate bounded Gaussian mechanism, we see that~$\sigma_m$ appears on both sides of~\eqref{eq:sigma_m_multi}. Hence, we will use numerical
methods to compute it.
\subsection{Calculating \texorpdfstring{$\sigma_m$}{Lg}}
We will follow similar steps to those in Section~\ref{sec:calculate_sigma}. Let $\sigma_m^*$ be the minimal admissible value of~$\sigma_m$ that satisfies~\eqref{eq:sigma_m_multi}.
Then for $D\subset \mathbb{R}^m$ we have
\begin{equation}
f_m(\sigma_m^*)=(\sigma_m^*)^2 - \frac{\left[||\mathbf{b}-\mathbf{a}||_2+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C_m(\sigma_m^*,\mathbf{c}^*))}=0.\label{eq:f_n}
\end{equation}
We now present some lemmas concerning the function $f_n$ with respect to the
point
\begin{equation}
\sigma_{m,0}=\sqrt{\frac{\left[||\mathbf{b}-\mathbf{a}||_2+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon}}.\label{eq:sigma_0_nd}
\end{equation}
\begin{lem}\label{lem:denominator_greater_0_nd}
For any $\epsilon>0$, we have $\epsilon-\ln(\Delta C_m(\sigma_{m,0},\mathbf{c}^*))>0$, where $\mathbf{c}^*$ is defined in Equation~\eqref{eq:objective_function}.
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_denominator_greater_0_nd}.
\end{proof}
\begin{lem}\label{lem:delta_c_greater_0_nd}
For $\sigma_{m,0}=\sqrt{\frac{\left[||\mathbf{b}-\mathbf{a}||_2+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon}}$, we have $\ln(\Delta C_m(\sigma_{m,0},\mathbf{c}^*))>0$.
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_delta_c_greater_0_nd}.
\end{proof}
\begin{lem}\label{lem:lemma_f_sigma_0_nd}
For a point $\sigma_{m,0}=\sqrt{\frac{\left[||\mathbf{b}-\mathbf{a}||_2+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon}}$, we have $f_m(\sigma_{m,0})<0$.
\end{lem}
\begin{proof}
By plugging in $\sigma_{m,0}$ we have
\begin{align*}
f_m(\sigma_{m,0})=\frac{\left[||\mathbf{b}-\mathbf{a}||_2+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon}-\frac{\left[||\mathbf{b}-\mathbf{a}||_2+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C_m(\sigma_{m,0},\mathbf{c}^*))}.
\end{align*}
With Lemma~\ref{lem:denominator_greater_0_nd} and Lemma~\ref{lem:delta_c_greater_0_nd} we have $\epsilon>\epsilon-\ln(\Delta C_m(\sigma_{m,0},\mathbf{c}^*))>0$. Therefore $f_m(\sigma_{m,0})<0$.
\end{proof}
\begin{lem}\label{lem:lemma_f_decreasing_nd}
For any $\sigma_m\in[\sigma_{m,0},\infty)$, we have $f_m'(\sigma)>0$.
\end{lem}
\begin{proof}
See Appendix~\ref{apdx:proof_lemma_f_decreasing_nd}.
\end{proof}
By combining Lemma~\ref{lem:lemma_f_sigma_0_nd} and Lemma~\ref{lem:lemma_f_decreasing_nd} we can use Algorithm 1 in~\cite{holohan2018bounded} to find the exact fixed point of $f_m$, namely $\sigma_m^*$, which is shown in Algorithm~\ref{alg:zero_finding_algorithm_2}.
The output of Algorithm~\ref{alg:zero_finding_algorithm_2} can be combined with
the mechanism in Definition~\ref{def:bounded_guassian_nd}, and
Theorem~\ref{thm:main_result_2} shows that this combination gives~$\epsilon$-differential privacy
for multivariate queries.
\begin{algorithm}
\SetAlgoLined
\SetKwInOut{Input}{Input}
\SetKwInOut{Output}{Output}
\Input{Function $f_m$ given in Equation~\eqref{eq:f_n}, Initial privacy parameter $\sigma_{m,0}$ given in Equation~\eqref{eq:sigma_0_nd}.}
\Output{Optimal privacy parameter~$(\sigma_m^*)^2$.}
left$=\sigma_{m,0}^2$\;
Compute $c^*$ from the optimization problem in~\eqref{eq:objective_function}\;
rignt$=\frac{\left[||\mathbf{b-a}||_2+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C_m(\sigma_{m,0},\mathbf{c}^*))}$\;
intervalSize$=($left$+$right$)*2$\;
\While{intervalSize$>$right$-$left}{
intervalSize $=$ right $-$ left\;
$(\sigma_m^*)^2=\frac{\text{left}+\text{right}}{2}$\;
Compute $c^*$ from the optimization problem in \eqref{eq:objective_function}\;
\If{$\frac{\left[||b-a||_2+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C_m(\sigma_m^*,\mathbf{c}^*))}\geq(\sigma_m^*)^2$}{
left $=(\sigma_m^*)^2$\;
}
\If{$\frac{\left[||\mathbf{b-a}||+\frac{\Delta Q}{2}\right]\Delta Q}{\epsilon-\ln(\Delta C_m(\sigma_m^*,\mathbf{c}^*))}\leq(\sigma_m^*)^2$}{
right $=(\sigma_m^*)^2$\;
}
}
\Return $(\sigma_m^*)^2$
\caption{A Zero Finding Algorithm for Multivariate Bounded Gaussian Mechanism}
\label{alg:zero_finding_algorithm_2}
\end{algorithm}
\section{Numerical Results}\label{S:algo}
This section presents simulation results.
We consider queries of the properties of a graph. Specifically, the bounded data we consider is (i) the average degree in an undirected graph, and (ii)
the second-smallest eigenvalue of the Laplacian of an undirected graph. This eigenvalue is also called the Fiedler value~\cite{fiedler73} of the graph. It is known that an undirected graph
is connected if and only if its Fiedler value is positive~\cite{fiedler73},
and the Fiedler value also sets the rate of convergence of various
dynamical processes over graphs~\cite{mesbahi10}.
We let $G=(V,E)$ denote a connected, undirected graph on $10$ nodes. In this experiment we have a two-dimensional query $Q$ to compute (i) the algebraic connectivity, equal to the second smallest eigenvalue $\lambda_{2}$ of the Laplacian matrix of~$G$, which satisfies $\lambda_{2}\in[0,10]$ here, and (ii) the degree of a fixed but arbitrary node $i$,
denoted~$N^i$, which satisfies $N^i \in [1,9]$ here.
Therefore, for a graph~$G$ we have $Q(G)=[\lambda_{2},N_{\text{out}}]^T\in D$, where $D= [\mathbf{a,b}]\subset\mathbf{R}^2$, with $\mathbf{a}=[0,1]^T$ and $\mathbf{b}=[10,9]^T$. For a fixed~$k \in \mathbb{N}$, we say that two graphs are adjacent if they have the same node set but differ in $k$ edges.
Let $\Delta Q_{\lambda_2}$ denote the sensitivity of $\lambda_2$, let $\Delta Q_{N^i}$ denote the sensitivity of node $i$'s degree, and let $\Delta Q=||(\Delta Q_{\lambda_2},\Delta Q_{N^i})^T||_2$ denote the sensitivity of the query $Q$. From~\cite[Lemma 1]{chen2021} we have $\Delta Q_{\lambda_2}=2k$ and $\Delta Q_{N^i}=k$.
Thus,~$\Delta Q = \sqrt{5}k$.
In our simulations we set $k=2$.
Table~\ref{table:1} gives some example variances computed for using the multivariate
bounded Gaussian mechanism. In Figure~\ref{fig:Normal_distribution}, there is a general decrease in the variance of the bounded Gaussian mechanism as $\epsilon$ grows. This
decrease
agrees with intuition because a larger $\epsilon$ implies weaker privacy protection and thus the private output distribution has a higher peak on the true query answer.
We now compare the proposed mechanism with generalized Gaussian mechanism~\cite{Liu2019}. Let $\sigma_{GG}^2$ be the variance of generalized Gaussian mechanism and $\sigma_{BG}^2$ be the bounded Gaussian mechanism. Then we define the Percent Reduction in variance as
\begin{equation*}
\text{Percent Reduction} = \frac{\sigma_{GG}^2-\sigma_{BG}^2}{\sigma_{GG}^2}\times 100\%.
\end{equation*}
Both Figure~\ref{fig:Normal_distribution} and Table~\ref{table:1} show that the bounded Gaussian mechanism always generates smaller variance, i.e., $\sigma_{BG}^2<\sigma_{GG}^2$ and
the $\text{Percent Reduction}>0$ for all $\epsilon$. In other words, compared to the
generalized Gaussian mechanism~\cite{Liu2019},
the bounded Gaussian mechanism generates private outputs with less noise but with the same level of privacy protection.
\begin{table}
\begin{tabular}{|c|c|c|c|}
\hline
$\epsilon$ & Generalized Gaussian $\sigma_{GG}^2$ & Bounded Gaussian $\sigma_{BG}^2$ & Percent Reduction \\ [0.5ex]
\hline\hline
0.1 & 1320.0 & 857.5 & 35.0\% \\
\hline
0.5 & 264.0 & 170.3 & 35.5\% \\
\hline
1.0 & 132.0 & 84.3 & 36.1\% \\
\hline
1.5 & 88 & 55.8 & 36.6\% \\
\hline
2.0 & 66 & 41.5 & 37.2\% \\
\hline
2.5 & 52.8 & 32.9 & 37.7\% \\
\hline
3.0 & 44 & 27.2 & 38.2\% \\[1ex]
\hline
\end{tabular}
\caption{Some example values of $\sigma_{BG}$ with different values of $\epsilon$. The last column shows the percentage reduction in variance attained by using the bounded Gaussian mechanism we develop.}
\label{table:1}
\end{table}
\begin{figure}[h]
\centering
\includegraphics{bounds_compare.pdf}
\caption{The variance comparison of proposed machanism and Liu's mechanism from~\cite[Definition 5]{Liu2019}.
With a larger $\epsilon$, which gives weaker privacy, the variance of bounded Gaussian mechanism decreases quickly and is always smaller than
that of the generalized Gaussian mechanism. This means that the bounded Gaussian mechanisms require less noise and provide better accuracy while maintaining the same level of protection.
In addition, the blue triangles ascent from left to right, indicating that the reduction in variance grows as~$\epsilon$ grows.
}
\label{fig:Normal_distribution}
\end{figure}
\section{Conclusion}\label{S:item}
This paper presented two differential privacy mechanisms, namely the univariate and multivariate bounded Gaussian mechanisms,
for bounded domain queries of a database of sensitive data. Compared to the existing generalized Gaussian mechanism, the bounded Gaussian mechanisms we present generate private outputs with less noise
and better accuracy for the same privacy level. Future work will apply this mechanism to real world applications, such as privately forecasting
epidemic propagation, federated learning and optimization, and explore privacy and performance trade-off. Besides, future work will design a denoise post-processing procedure to generate more accurate private outputs.
| {'timestamp': '2022-12-01T02:21:04', 'yymm': '2211', 'arxiv_id': '2211.17230', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17230'} | arxiv |
\section{Introduction}
Deep learning as such is based on the idea that concatenations of (suitably chosen) nonlinear functions increase expressivity so that complex pattern modeling and recognition problems can be solved. While initial approaches such as AlexNet \citep{alexnet} only used moderate depth, improvements such as batch normalization \cite{batchnorm,bn_covshift,bn_autotune} or residual connections \cite{resnet} made the training of networks with hundreds or even thousands of layers possible, and this did contribute to significant practical gains.
From a theoretical perspective, a networks depth (along with its width) is known to upper bound the complexity of the function that it can represent \citep{vc_bounds} and therefore upper bounds the networks expressivity. Indeed, deeper networks are found to enhance performance \citep{efficientnet}, but gains seem to taper off and saturate with increasing depth. Very deep networks are also known to be more difficult to analyze \citep{generalization}, more computationally expensive to train or infer and suffer from numerous stability issues such as vanishing \citep{vanishing_gradients}, exploding \citep{fixup} and shattering \citep{shattering_gradients} gradients. Similar arguments can be made about layer width: a sufficiently large network can memorize any given function \citep{original_uat}, but under standard initialization and training infinite width networks degrade to Gaussian processes \cite{Jacot2018}.
From a practical perspective, there are now many successful recipes for creating networks of a prescribed depth, but it is still difficult to understand -- empirically or analytically -- how many nonlinear layers and features per layer are actually needed to solve a problem, and how effective a chosen architecture actually is in exploiting its expressive potential in the sense of a deep stack of concatenated nonlinear computations.
Our paper addresses this question from an empirical perspective: we use a very simple setup that associates every nonlinear unit with a cost at channel granularity, which can be raised continuously, while simultaneously trying to maintain performance. This is done by replacing each ReLU layer with channel-wise PReLU activations \citep{prelu} and regularizing their slopes towards linearity. Such a linearized feature channel therefore only forms linear combinations of existing feature channels, thereby not effectively contributing to the nonlinear complexity of the network. Observing the partially linearized network can tell us \textit{how many} nonlinear units are needed by a given network and also \textit{where} they are needed. We measure the average amount of nonlinear units a given input traverses until it is classified disregarding subsequent linear mappings along computational paths, as these do not increase expressivity in a nonlinear sense.
Using tool, we make a series of experiments on common convolutional network architectures on standard computer vision tasks by partially linearizing networks after regular training, make the following observations:
\begin{itemize}
\item The amount of nonlinear units in the network can be reduced considerably before suffering larger performance losses and where the transition occurs depends on the difficulty of the task to learn.
\item The average amount of nonlinear units encountered along a path in the computation graph ("effective depth") of the resulting networks is very low before performance collapses.
\item When applying the same regularization strength to networks of varying width and depth, the effective width and depth is similar for all resulting partially linearized networks for a fixed task.
\item A network partially linearized at a later stage of training outperforms the same network partially linearized earlier. The biggest difference is notable in the early training phase.
\end{itemize}
These findings indicate, consistent with earlier hypothesis \citep{lottery} that there is a core nonlinear structure in networks that forms during the first epochs of training whose shape depends on the task to solve and is largely independent of the shape of initial network chose.
\section{Related Work}
\iffalse
A lot of work has been done to understand the implications of depth on expressivity, generalization performance and the function classes that can be learned efficiently. The well-known universal approximation theorem \citep{original_uat} shows that a network with only one layer but sufficient width is able to ``memorize'' any function. Indirectly, this might suggests that the generalization capabilities of neural networks might be tightly linked to their depth. In this spirit, \citet{narrow_uat} reformulate the well-known universal approximation theorem \citep{original_uat} for deep and narrow networks; \citep{debauchies} are studying what class of functions can be effectively approximated by deep ReLU networks. Despite the empirical success of deep models, analyzing the training dynamics of deep networks is generally very difficult; hence, a lot of work considers the properties of shallow networks as model systems \citep{shallow_dynamics}.
\citet{resnet_ensemble} show that ResNets can be understood as an ensemble of shallower networks: the average effective path length inside such a network is indeed much shorter than the depth of the network, since the path lengths follow a binomial distribution. Their model corresponds to our ``normalized'' average path length model.
\todo{I would leave this out (becaues only tangentially related):}
\citet{ringing_relus} research how different activation functions affect the roughness of the loss landscape, specifically using Leaky ReLU activations to steer the nonlinearity of a network.
\fi
Different approaches to network pruning were explored in recent years: magnitude-based weight pruning, weight-regularization techniques, sensitivity-based pruning and search-based approaches \citep{compression_survey}. \citet{lottery} extract a highly performant, sparse and re-trainable subnetwork by removing all low-magnitude weights after a given training time, re-initializing the network and iterating this process.This motivates the "lottery ticket hypothesis" of a network consisting of a smaller core structure embedded in the larger, overparametrized and redundant network, which, in their case, can be extracted by weight pruning. Our paper prunes nonlinear units, coming to a similar finding of a problem-difficulty-dependent minimal set, embedded in a much larger and deeper network, when considering nested nonlinear computations. \citet{sparse_resnets} find sparse subnetworks using different types of weight-regularization on a ResNet; in particular the authors find a shallower subnetwork that can beat the performance of an even deeper network. Our method, aiming at removing nonlinear feature channels from the network, is also tightly related to the classical dropout \citep{dropout} method as well as its modern successors such as ShakeDrop \cite{shakedrop}.
Simplification of networks by reducing nonlinearity has become a major area of interest. A lot of recent work has studied the neural tangent kernel (NTK) approximation, which linearizes the network function wrt. its parameters. It arises in the infinite width limit (under mild conditions) or by explicitly performing a linear Taylor-approximation of a finite network~\cite{Jacot2018,nonlin_advantage}. As it fully linearizes training, the NTK has been tremendously useful for gaining a better understanding of the training of deep network, such explaining double-descent generalization \cite{belkin2019reconciling,wilson2020bayesian}. Maybe unsurprisingly, linearized training hurts performance in practice~\cite{nonlin_advantage} and theory: \citet{Roberts2022} attribute it to the loss of detection of higher-order moments in the data distribution). Fort et al.~have coined the term ``\textit{nonlinear advantage}'' for the observed loss in performance when linearizing early in training. Within the NTK framework, the impact of ReLUs can be captured by path kernels \cite{Lakshminarayanan2020}, the learning of which improves results and generalizes when retraining. Our APL measures are tightly related to the proposed (gated) path-integral formulation there. Our paper simplifies the network function itself by reducing the number of nonlinear units in the network and therefore partially linearizing it in both inputs and weights,finding a similar, but difficulty-dependent nonlinear advantage.
\citet{layer_folding} use a methodology similar to ours, but applied layer-wise and aiming at improved performance characteristics at inference time. Our approach is different, using (channel-wise) regularization as an analytical tool to understand the emergent structure within a complex nonlinear network better.
\section{Reducing Nonlinear Feature Channels}
In order to reduce the amount of nonlinear feature channels in a network, we take network architectures and replace their ReLU activations with PReLUs. We then use a single PReLU weight for every channel and add a sparsity regularization of $L_{0.5}= \sum |1 - \alpha_i|^{0.5}$ to the regular training loss scaled with a \textit{regularization weight} $\omega$, where $\alpha_i$ is the variable slope of the i-th PReLU. Since this loss is discontinuous at $1$, we completely remove a PReLU unit if their slope gets close enough to one. We call such a unit \textit{inactive}, while all other units are \textit{active}.
\subsection{Average Path Length (APL)}
\begin{figure}[h!]
\centering
\includegraphics[width=.7\linewidth]{figs/PathLength.pdf}
\caption{In this Figure, a residual connection (red) skips 4 small fully connected layers. The left-most and right-most nodes are connected by 257 different paths. Using \textit{unnormalized} average path length implies a $1/257$ chance of selecting the red path and the same chance of selecting the blue path. Using \textit{normalized} average path length, we have a $1/2$ chance of selecting the red path and a $1/512$ chance of selecting the blue path.}
\label{apl_vs_napl}
\end{figure}
The traditional notion of depth corresponds to the amount of activation layers encountered when following the computation graph of a network from input to output. For networks where nonlinearity is removed in certain channels, and thus the amount of activation layers encountered highly differs according to the path taken through the network, considering the average amount of active units encountered per path might be a more informative choice.
Let $G=(V,E)$ be the directed acyclic graph that represents the computation graph of a given feedforward neural network. Since we are only interested in the nonlinear structure of the graph, a node in the graph corresponds to a PReLU unit in the network. We denominate $V_d\subset V$ the subset of nodes that correspond to the $d$-th layer in the network. Let $v_{in}, v_{out} \in V$ be the respective input and output vertices of the graph. Let $R\subset V$ be a subset of the vertices that represent the blocks containing an active PReLU i.e. $|\alpha - 1| > \epsilon$, where $\alpha$ is the weight of the PReLU.
Let $\mathcal{P}^{(n)}\subset V^n$ be the set of all paths of length $n$ in $G$ that originate in $v_{in}$, i.e. $p_1 \in v_{in}$ and $(v_i,v_{i+1})\in E$ for all $1\leq i\leq n-1$. We define the \textit{effective path length} of a path $p\in\mathcal{P}^{(n)}$ as the number of active PReLU activations it traverses: $\phi(p) \vcentcolon= |\{v_i \in p~|~v_i \in R,~ 1\leq i \leq n \}|$, which is always smaller or equal to its regular length $|p|$. Let $v\in V$ be a vertex of the graph, we then define its path histogram function $\phi^{(l)}(v) \vcentcolon= |\{p \in \mathcal{P}^{(l')} ~|~ p_l = v, ~\phi(p) = l, ~1\leq l' \leq l \}|$ as the number of paths from $v_{in}$ to $v$ of effective length $l$. We finally define the \textit{average path length (APL)} of the network as $APL(G) \vcentcolon=\frac{\sum_{i=0}^{d}i\cdot \phi^{(i)}(v_{out})}{\sum_{i=0}^{d}\phi^{(i)}(v_{out})}$, where $d$ is the depth of the network. In order to effectively compute the APL of a network, we resort to dynamic programming.
\begin{theorem}
Let $v\in V$ be a vertex in the network. We can then compute its path histogram function by summing over all vertices that have an outgoing edge to $v$:
$\phi^{(l)}(v) = \begin{cases}
\sum_{v'\in V}\mathbbm{1}_{(v', v)\in E}\cdot\phi^{(l-1)}(v')\quad\text{if }v\in R,\\
\sum_{v'\in V}\mathbbm{1}_{(v', v)\in E}\cdot\phi^{(l)}(v')\quad~~~ \text{otherwise.}
\end{cases} $
\end{theorem}
\begin{figure*}[tb]
\centering
\includegraphics[width=.9\linewidth]{plots/featureviz.png}
\caption{Visualization of the same feature channels for a ResNet50 at different degrees of partial linearization.}
\label{featureviz}
\end{figure*}
A proof can be found in the Appendix. In simple terms, we obtain the path histogram of a given node by summing the path histograms of all incoming nodes and shifting it "to the right" if a node contains an active ReLU.
\textbf{Implementation details:} This recursion can easily be implemented in a modified forward pass through the network by re-using the batch dimension of the input tensor as "histogram dimension" that saves the path histogram function $\phi^{(l)}(v)$ for a given neuron $v$. By setting all weights of a linear (fully connected or convolutional) layer to one and biases to zero, executing the layer then automatically outputs for each neuron the sum of all inputs and therefore sums the path histogram functions of all incoming nodes. We then just need to "shift" the obtained histogram if an active PReLU is present to obtain the correct histogram function for $v$. Other layers such as batch normalization or pooling layers have to be ignored. We finally just need to chose a constant $1/0/0/\dots$ input for network and extract the obtained histograms in the last layer. For reasons discussed below, it can be useful to normalize the histograms before adding them inside a ResBlock; we call the resulting value the \textit{normalized average path length}. An illustrative example for a histogram computation of a non-residual and a residual network can be found in the Appendix in Figure \ref{hist_example}.
By Proposition 1, the \textit{unnormalized average path length} (APL) describes the expected number of active PReLU units a path contains if we draw a path \textit{uniformly from the set of all possible paths}. In networks with residual connections, this heavily favors longer paths, as every additional layer used increases the number of possible paths exponentially (ref. Appendix Figure \ref{hist_explosion}). In this measure, despite residual connections, the initial path length of a ResNet is only slightly lower than its depth which might seem unintuitive.
The \textit{normalized average path length} (NAPL) describes, as illustrated in Figure \ref{apl_vs_napl}, the expected number of active PReLUs a path contains if we follow a random outgoing edge at every node in the path. In a residual network this means that inside a ResBlock, both summands (main branch and residual connection) have equal weight.
\begin{figure*}[tb]
\begin{minipage}[t]{0.475\linewidth}
\centering
\includegraphics[width=0.7\linewidth]{plots/prop_disabled_rn_56_ns.png}
\end{minipage}
\hfill
\begin{minipage}[t]{0.475\linewidth}
\centering
\includegraphics[width=0.7\linewidth]{plots/prop_disabled_rn_56_s.png}
\end{minipage}
\caption{Proportion of inactive PReLUs when partially linearizing a ResNet56 NoShort / Short with $\omega = 0.003$.}
\label{prop_disabled}
\end{figure*}
\iffalse
By using a dynamic programming approach, we compute a histogram of the effective path lengths in the resulting subnetwork. This calculation can be implemented in a modified forward pass by storing the number of paths of length $l$ that pass through a given neuron in the $l$-th entry of the batch dimension. To obtain the histogram over path lengths, one must set to pass-through every layer but convolutional/linear layers, set all biases to zero and the network input to $1/0/0/\hdots$; for every PReLU activation, if an activation weight is not fully linear, the histogram of the activation is shifted by one channel to indicate that the paths through this neuron passed a nonlinearity. The histogram is then extracted at the last layer and can be visualized along the average path length throughout the training process. A illustrative example is sketched in Figure \ref{hist} and more details on histogram computation can be found in the Appendix .
\begin{figure}[tb]
\centering
\resizebox{5cm}{5cm}{
\input{figs/hist_ns_small.tex}
}
\caption{Computing the histogram of effective path lengths using dynamic programming. Red circles represent a layer with an active PReLU, black circles represent an inactive PReLU.}
\label{hist}
\end{figure}
\bgreen{Eventuell die path graphik ersetzen mit der die auch normalized APL zeigt}
\fi
Both APL and NAPL do not depend on the absolute number of active PReLUs in a layer but rather on their relative proportion. For this reason, we will also use the simple measure of \textit{effective network width} or ENW of a network. It is the absolute number of active PReLUs per layer, averaged over all layers. This measure depends only on the extracted "core" network and is therefore useful for comparing architectures of different width.
\iffalse
\subsection{Linear Blocks}
Additionally to the Path length, we investigate \textit{Linear Blocks} as a measure of linearity in the network. We call a Linear Block a maximally sized subsequence of layers containing no active PReLUs in-between. Layers making up a Linear Blocks can be completely folded into a single linear layer \citep{layer_folding} with a bigger kernel size. Linear Blocks do not contribute to a network's expressivity and can be therefore viewed as superfluous to the networks expressive power.
The size of these blocks might therefore correlate in some way to architecture efficiency. Since we only want to count superfluous layers, we define the size of a linear block as the number of connected linear layers minus one. We can then define the \textit{Average Linear Block Length} as the average size of all blocks. Contrary to average path length, networks with high linear block size could directly be reparametrized as a strictly shallower network.
\bgreen{Mal grob geschrieben, kann man ja immernoch raus nehmen}
\subsection{Extracted Networks are equivalent to Densenets using a single block}
As concurrent linear layers can be merged, we can use our approach to create a network containing only the active PReLUs. For easy of mathematical notation we will assume no residual connections, although the idea holds for any feed-forward network:
We separate every layer $l$ into two functions, one calculating results for active PReLU units $a_l(x_{l-1})$ and one calculating results for inactive PReLU units $d_l(x_{l-1})$. Since the input $x_{l-1}$ of layer $l$ is equal to the output of the previous layer, which can also be separated, we can write:
$$a_l(x) = a_l(a_{l-1}(x_{l-2}) \oplus d_{l-1}(x_{l-2}))$$
By applying this idea recursively only for the inactive PReLU units, we obtain:
$$a_l(x) = a_l(a_{l-1}(x_{l-2}) \oplus d_{l-1}(a_{l-2}(x_{l-3})\oplus d_{l-2}(...)))$$
as $d_{l-1}$ is a linear function we can separate the function to apply to only active or inactive units. By doing this we can merge all concatenations of these linear units. In the end we get a function depending only on previous active PReLU units and the original input in a linear way:
$$ a_l(x) = a_l(a_{l-1}(x_{l-2}) \oplus d'_{l-1}(a_{l-2}(x_{l-3})) \oplus d'_{l-2}(a_{l-3}(x_{l-4})) ...\oplus d'_{0}(x_0))$$
Since we can do this in any layer we can remove all inactive PReLU channels, resulting in a network similar to a Denseblock, see \ref{}
\bgreen{rewrite math to make more sense! add figure! }
Note that these networks encode the same function, even though they have drastically different architectures.
\fi
\iffalse
\subsection{Layer fusion}
If an activation function separating two linear layers also becomes linear, these two layers can be easily fused together. In the convolutional case, combining eg. two 3x3 kernels results in a convolution operator that is a linear subspace of all 5x5 kernels. Contrary to the work of \citep{layer_folding}, we focus on a layer fusion technique that keeps working in the linear subspace of the original filters as we found that this results in a better training performance \bred{EXPERIMENT TBD}. Since our fusion operation remains in the same function space, the parameter cost of the model remains the same. The two other factors to consider are space complexity and runtime.
\subsubsection{Space complexity analysis}
In the fully connected case, the analysis is simple: a linear layer represented by a matrix of size $i\times m$ followed by a linear layer of size $m\times o$ can be multiplied together into a matrix of size $i\times o$.
In the convolutional case this is also possible, but with an additional caveat. Using the associative property of the convolution operator, two 1D-convolutions with respective kernel size $k_1$ and $k_2$ can be combined into a single convolutional layer of kernel size $k_1+k_2-1$. \\
In the following we will be using the naming convention $(\textnormal{in\_ch}, \textnormal{out\_ch}, \textnormal{kernel\_size},\textnormal{kernel\_size})$ for the weights of convolutional layers. By fusing two convolutional layers with respective weight shape $(I,M,k_1, k_1)$ and $(M,O,k_2,k_2)$, we then obtain a convolutional layer of size $(I,O,k_1+k_2-1,k_1+k_2-1)$. The total space complexity is therefore $I\cdot M\cdot k_1^2 + M\cdot O \cdot k_2^2$ for the separated layers and $I\cdot O \cdot (k_1 + k_2 -1 )^2$ in the fused case. Therefore, it depends on the number of channels if combining layers result in savings in space complexity. From the simple but realistic case $k_1=k_2$ and $I=M=O$: the fused cost is strictly higher and is approximately double the separate cost, we deduce that the space complexity is mostly increasing when fusing layers.
By fusing together more and more layers, the receptive field becomes bigger and the resulting layer structure resembles more a fully-connected layer with weight dependencies. The maximum receptive field of the combined convolutions is obviously bounded by the latent width and height of the image.
\subsubsection{Runtime analysis}
\citep{layer_folding} found that fused layers, despite requiring more absolute operations, yield lower runtimes.
\fi
\section{Experiments}
In this section, we apply linearization to trained network architectures on different datasets and observe the resulting structure to see if we can find some regularities in their behavior that are consistent over different datasets and architectures - both by visual inspection and statistical analysis.
As our techniques requires networks with ReLU activations, we chose a ResNet \citep{resnetv2} and PyramidNet \citep{pyramidnet} with ("Short") and without ("NoShort") residual connections as examples of standard architectures with and without residual connections with differently distributed feature channels. For ease of comparison with related work, we work with standard image classification datasets of variable but well-known difficulty: CIFAR-10, CIFAR-100 \citep{cifar}, CINIC-10 \cite{cinic10}, Tiny ImageNet \citep{tiny_imagenet} and ILSVRC 2012 (called ImageNet in the following) \citep{imagenet}. CIFAR-10 is used by default if not further specified for experiments requiring many runs. We trained all networks from scratch except on ImageNet where we use a pre-trained ResNet50 from the Torchvision library.
We chose the most basic setup for regular training that is capable of delivering benchmark results for the chosen architectures: regular training with ReLU units, momentum SGD, a multistep learning-rate scheduler and weight decay. Afterwards, the ReLU units were replaced by regularized PReLUs (with initial negative slope 0) and we resumed training in a shorter post-training step. Concerning learning-rate scheduling in the post-training step, we needed a big learning rate initially to reach the target nonlinearity and a lower learning rate afterwards in order to reach a good performance. We therefore reverted to the initial learning rate and use the same multistep scheduling as in the regular training phase adapted to the shorter post-training phase. More details about architectures and training regimes used can be found in the Appendix.
We decided to use the normalized average path to avoid overflows for deeper networks (the absolute number of paths through the network grows exponentially in depth) and because it is in-line with previous works discussing path lengths in ResNets \citep{resnet_ensemble}. Results with unnormalized path length yield similar results albeit the absolute numbers are higher as shown in the Appendix.
\subsection{Visual Inspection of the Remaining Nonlinear Feature Channels}
We start with informal observations about how reducing the amount of nonlinear feature channels in a network affects what they react to, in order to gain an intuition about how the resulting networks might behave. We visualized some feature channels from ResNet50 Short trained on ImageNet and partly linearized to different degrees ($\omega\in[0.0005,0.0025]$) with the Lucent \citep{lucent} library; the performance and amount of remaining active PReLU units in these networks is shown in Figure \ref{performance_imgnet} and discussed in later sections. We chose some arbitrary feature channels from a deeper layer that are still active in all three networks. We see that in most cases, we can recognize a given feature over the different networks. Generally, the feature visualizations seem subjectively sharper for higher $\omega$, but sometimes mix with others or change drastically. We conclude that our method is not simply selecting feature channels but also changes what input they react to - with an in intensity depending on the regularization weight used.
\subsection{Performance and Structure of Partially Linearized Networks}
\begin{figure*}[tb]
\begin{minipage}[t]{0.475\linewidth}\vspace{0mm}%
\centering
\includegraphics[width=7cm]{plots/regtest_archcompare_test.png}
\caption{NAPL and test accuracy for different partially linearized network architectures with $\omega\in [0.0005, 0.005]$.}
\label{performance}
\end{minipage}
\hfill
\begin{minipage}[t]{0.475\linewidth}\vspace{0mm}%
\centering
\includegraphics[width=7cm]{plots/imgnet_6ep.png}
\caption{NAPL, accuracy and active features channels for a partially linearized ResNet50 pre-trained on Imagenet with $\omega\in [0.0005, 0.0025]$.}
\label{performance_imgnet}
\end{minipage}
\end{figure*}
\label{sect_performance}
We now observe the temporal evolution of the linearization process for two different network architectures in Figure \ref{prop_disabled}. When evaluating the proportion of inactive PReLUs per layer, we note that every architecture presents a distinct pattern: for the ResNet56 NoShort, we see that the remaining nonlinearity is concentrated in a connected block, whereas for the ResNet56 Short, the remaining active PReLUs are distributed more evenly over the layers. Interestingly, the connected block of remaining nonlinearity in the ResNet56 NoShort is located in the middle of the network and not on either end, excluding simple vanishing/exploding gradient effects as a cause. The fact that for the ResNet56 NoShort, many layers are fully linearized \textit{without explicit insensitive to do so} indicates that such network architectures might not use their full expressive potential. The stripe-like structure of remaining nonlinearities in the ResNet56 Short corresponds to the placement of the residual connections and indicates that these might help in utilizing the full depth of the network.
We found the qualitative behavior for both architectures to be consistent on the CIFAR-100 dataset (ref. Appendix), albeit the exact location of the connected nonlinear layer block changes. We conclude that despite regularizing every nonlinear unit equally, distinct patterns form in the remaining nonlinearities in the network that depend on network architecture.
Second, we want to demonstrate the effects of partial linearization on generalization performance for different architectures and datasets. We plotted the performance of partially linearized networks for different choices of $\omega$ on Cifar10 in Figure \ref{performance}. Darker colors represent a higher regularization weight and the disk sizes represents the global proportion of inactive PReLUs. We can see that for all networks, the top-1 test performance remains high even for a comparably small NAPL values until it collapses. We also see that depending on network architecture, for a similar NAPL value, different networks architectures present a distinct percentage of inactive PReLUs, further supporting our claim of a network-dependent structure being extracted by linearization. Qualitatively similar plots can be found for the CIFAR-100 dataset in the Appendix. We further verified our claims for a ResNet50 on the ImageNet dataset in Figure \ref{performance_imgnet}; note that this network contains a non-ReLU activation layer (maximum pooling) that we included in our calculations.
Third, we want to investigate whether a partially linearized network of a given average depth can outperform a shallow network of similar (absolute) depth. For this, we indicated the performance of a ResNet6 and a ResNet6 "wide" with at least as many parameters as the ResNet56 trained for 200 epochs as horizontal lines for the Cifar10 runs. Comparing the performance of the partially linearized ResNet56 to the ResNet6 "wide", we note that the performance of the partially linearized deep network is superior to the performance of shallow networks of comparable depth, hinting that linearizing \textit{after} training can be advantageous. Since NAPL is only an \textit{average} measure of depth, a network with NAPL $n$ is not strictly comparable to a network with true depth $n$ since for the latter, the number of nonlinear units on a computation path is strictly inferior to $n$; we address this limitation in a later section.
\subsection{Analyzing the Shape of the "Core Network"}
In this section, we investigate whether we can find some regularities in the shape of the resulting network if we partially linearize networks of different initial shape.
\begin{figure*}[tb]
\begin{minipage}[t]{0.475\linewidth}\vspace{0mm}%
\centering
\includegraphics[width=7cm]{plots/depthtest.png}
\caption{Validation accuracy and average path length during linearization of ResNets of different depth for $\omega = 0.003$.}
\label{depthtest}
\end{minipage}
\hfill
\begin{minipage}[t]{0.475\linewidth}\vspace{0mm}%
\centering
\includegraphics[width=7cm]{plots/widthtest.png}
\caption{Validation accuracy and average path length during linearization of ResNets56 of different width for $\omega = 0.003$.}
\label{widthtest}
\end{minipage}
\end{figure*}
\begin{figure*}[tb]
\begin{minipage}[t]{0.475\linewidth}\vspace{0mm}%
\centering
\includegraphics[width=7cm]{plots/widthtest_active.png}
\caption{Inverse proportion of active PReLUs and NAPL for ResNet56 Short of different width after linearization for $\omega = 0.003$. A linear fit to the blue curve is drawn in grey.}
\label{widthtest_active}
\end{minipage}
\hfill
\begin{minipage}[t]{0.475\linewidth}\vspace{0mm}%
\centering
\includegraphics[width=7cm]{plots/regtest.png}
\caption{Test accuracy and average path length after linearization of ResNet56 for different regularization weight choices $\omega$ on the Cifar10, CINIC-10 and CIFAR-100 dataset.}
\label{regtest_compare}
\end{minipage}
\end{figure*}{}
\subsubsection{ENW Converges Approx. Independently of Initial Width}
\label{section_width}
We now want to analyze the effect of network width on the shape of the resulting partially linearized network. We therefore apply our linearization technique to different versions of ResNet56 Short scaled in width by a factor of $\nu\in\{0.25,0.5, 1, 1.5, 2, 2.38 \}$ and measure the NAPL and performance of the resulting networks. In Figure \ref{widthtest}, we see that wider networks seem to have better performance but lower NAPL. The relationship between the number of filters in a layer and the average path length seems reciprocal: this would imply that the average number of active neurons per layer remains approximately equal. To confirm this, in Figure \ref{widthtest_active} we plotted the inverse proportion of active PReLUs after post-training linearization for all networks. We can see a linear relationship, confirming that the average amount of active neurons per layer remains roughly constant - independently of the initial width chosen.
\subsubsection{NAPL Converges Approx. Independently of Initial Depth}
\label{depthtest_sect}
We saw that independently of the network width chosen, there was a similar amount of neurons per layer that remained active. We now want to establish if we can make a similar statement with regard to network depth. Therefore, we repeated the experiment of the last section for networks of different depth. In Figure \ref{depthtest}, we see that independently of the initial network chosen, the resulting network's NAPL converges to a similar value while having comparable training performances. Shallower networks seemingly converge to a marginally higher NAPL but this is merely an artifact of how we scaled ResNet blocks and is not observable on a simple convolutional network with constant width (ref. Appendix). The results hint the existence of a core nonlinear structure that forms during training that is necessary to learn a given task that is approximately constant in depth and width, regardless of the initial network with chosen. Similar experiments on depth and width on the CIFAR-100 in the Appendix show qualitatively the same behaviour but with different NAPL values.
\subsubsection{NAPL Depends on Task Difficulty}
To understand how the difficulty of the task to learn affects the shape of the resulting partially linearized networks, we regularized many instances of ResNet56 Short for different choices of $\omega$ on CIFAR-10, CINIC-10 and CIFAR-100. Looking at Figure \ref{regtest_compare}, we first note that by increasing the regularization weight, the NAPL of the resulting network is decreased as expected, but this effect seems to saturate exponentially while the test accuracy is only reduced linearly in $\omega$. This seems to imply that there is a minimum NAPL necessary to learn a given task. We also see that the NAPL measured is consistently higher for harder datasets (datasets where the networks reach a low top-1 accuracy), except for very high regularization values where the CINIC-10 and CIFAR-10 curves converge. We conclude that our method is able to extract a network with minimal nonlinearity able to learn a given task.
\begin{figure*}[h!]
\begin{minipage}[t]{0.475\linewidth}\vspace{0mm}%
\vspace{1.35cm}%
\begin{adjustbox}{width=\columnwidth,center}
\begin{tabular}{lllll l}
\toprule
Architecture& Base & Linear. & Exact & Layerwise P. & Global P.\\
\midrule
\textit{CIFAR-10}&&&&&\\
\\
ResNet56Short&92.7 & 89.2&\cellcolor{green!25}$89.0 \pm 0.0013$&\cellcolor{green!25}$90.0 \pm 0.0021$&\cellcolor{green!25}$89.7 \pm 0.0027 $\\
ResNet56NoShort&84.8 & 81.3&\cellcolor{green!25}$81.8 \pm 0.0033$&\cellcolor{green!25}$81.8 \pm 0.0065$& \cellcolor{red!25}$74.0 \pm 0.0063$\\
PyramidNet110Short &94.7&91.5&\cellcolor{green!25}$91.4 \pm 0.0003$&\cellcolor{green!25}$ 91.7 \pm 0.0012$&\cellcolor{green!25}$91.6 \pm 0.0014$\\
\midrule
\textit{CIFAR-100}&&&&&\\
\\
ResNet56Short & 69.9 &68.3&\cellcolor{red!25}$66.8 \pm 0.0042$&\cellcolor{red!25}$66.7 \pm 0.0134$&\cellcolor{red!25}$65.2 \pm 0.0044$\\
ResNet56NoShort & 56.7 & 54.8& \cellcolor{red!25}$45.3 \pm 0.0110$ &\cellcolor{red!25}$45.8 \pm 0.0263$& \cellcolor{red!25}$47.0 \pm 0.0218$ \\
\bottomrule
\end{tabular}
\end{adjustbox}
\caption{Performance of the extracted partially linearized network compared to baseline networks where we re-train the same network from scratch with the same amount of inactive PReLUs but differently distributed. Standard deviation over five runs is indicated for the re-trained networks.}
\label{retrain_table}
\end{minipage}
\hfill
\begin{minipage}[t]{0.475\linewidth}\vspace{0mm}%
\centering
\includegraphics[width=7cm]{plots/lottery_remade.png}
\caption{Test accuracy of networks partially linearized at different epochs during training on different datasets.}
\label{nonlin_advantage}
\end{minipage}
\end{figure*}
\subsection{The Nonlinear Advantage}
In Figure \ref{performance}, we observed that a partially linearized deep network can outperform a shallow network of comparable depth: this hints the existence of a "nonlinear advantage" for partially linearized networks in the sense that linearizing at a later stage of training is more advantageous compared to an earlier stage. In this section, we want to make sure that the observed effect is strictly due to the \textit{linearization later on} in training and cannot only be attributed to architecture differences between the two networks. For this, we compare the performance of networks with the same architecture that are partially linearized at different stages of training.
\subsubsection{Re-training Partially Linearized Networks From Scratch}
In a first step, we consider the most extreme case of comparing a network partially linearized \textit{after being fully trained} to a network of the same architecture that contains the same amount of nonlinear units \textit{at initialization}. We consider three different ways of transferring the distribution of inactive PReLU units from the partially linearized network to the new network that work at different granularity: exact, layer-wise and network-wise. This way, we are able to see whether the exact layerwise distribution of active PReLU units is important for the network to train to its full potential. We re-train the network 5 times, using the same number of epochs and schedule as in the original training scheme. Apart from the mask of inactive PReLUs, everything else (network weights, optimizer etc.) is re-initialized and the network is trained from scratch.
\begin{itemize}
\item \textbf{Exact: } The exact binary masks of inactive PReLU are kept.
\item \textbf{Layer-Wise Permutation:} The binary masks of inactive PReLUs are kept but shuffled with all PReLU units within the same layer.
\item \textbf{Global Permutation:} The binary masks of inactive PReLUs are kept but shuffled with all PReLU units in the network.
\end{itemize}
In the table in Figure \ref{retrain_table}, we see that for the "easy" dataset CIFAR-10, the nonlinear advantage is nonexistent since all networks trained with the exact and layerwise permutated nonlinearities reach the full performance of the network that was partly linearized after training. The slight gain in performance can be attributed to the higher number of epochs where the network can adapt to the missing nonlinearity. Further we see that only for the ResNet56 NoShort, the network which differs most from a uniform distribution in its remaining PReLU units (ref. Figure \ref{prop_disabled}), the full performance was not reached with a global permutation in PReLU masks whereas for all other architectures, full performance was reached. We conclude that nonlinear advantage is nonexistent for this easy dataset and the layerwise distribution of PReLU units matters only for networks with a very distinct (non-uniform) structure in its remaining PReLU units.
As for the significantly more difficult dataset CIFAR-100, we see that no setting can reach the performance of the network that was partly linearized after training, not even re-training where the exact PReLU masks are transferred; this clearly confirms the existence of a nonlinear advantage for harder problems.
\subsubsection{Training Phases}
In a second step, we want to break down how linearizing a network at different stages of training affects its performance. For this, we train a ResNet56 Short (PyramidNet41 for Tiny ImageNet) on four datasets of varying difficulty since previous results indicate that we can only measure it on harder datasets. At different stages of the training, we activate our regularizer with a fixed regularization weight, resume training and measure the final performance of the network. As regularizing the network at different stages of training with the same regularization weight can result in massive differences in the amount of inactive PReLUs, we slightly modified our regularizer to stop when a goal percentage (we chose 80\%, a value high enough to impact training performance) of inactive PReLUs over all layers is reached. We see that even when using this method, networks regularized later in training are still significantly more performant than networks partially linearized earlier in training. This effect is particularly pronounced for the harder dataset Tiny ImageNet, indicating a correlation between effect strength and the hardness of the task at hand.
\section{Discussion and Future Work}
In our experiments, we found that when naively penalizing nonlinearity equally for each feature channel in the network, surprisingly shallow structures form for networks without residual connections, indicating that their actual depth isn't fully utilized. We also found that we can extract a more performant shallow network when partially linearizing \textit{after} training compared to training a similarly linear network from scratch, further supporting our claim that fewer nonlinearity is needed than previously thought. Reducing combinatorial complexity in this way might help us gain new insights in network optimization processes, given that many theoretical works on network optimization are limited to shallow networks.
We also found strong indications that during training, neural networks form a small "core nonlinear structure" that is hidden within the network, confirming previous observations such as the "lottery ticket hypothesis" and "nonlinear advantage" from another angle. We further found indications that the shape of this structure is strongly dependent on the problem on hand.
Finally, we used a feature visualization library to view the
features of linearized networks and interestingly we found that features that can be recognized across networks seem to have subjectively more clearly defined shapes and increased sharpness. The reduced complexity of linearized networks combined with this fact might indicate that our approach can support efforts to reach explainable AI.
\clearpage
| {'timestamp': '2022-12-01T02:19:53', 'yymm': '2211', 'arxiv_id': '2211.17180', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17180'} | arxiv |
\section{More Details on Dataset Construction} \label{appendix:dataset}
In this section, we provide more complementary details to \Cref{sec:exp:tasks}. Table \ref{table:appendix:examples_data} shows examples of text input and target for three datasets. For Huffpost News and FewRel, we subsample exactly 200,50 examples per label class. For FewNERD, as it can have multiple label types per example, we subsample at 50 examples per label class.
\begin{table}[H]
\centering
\scalebox{0.75}{
\begin{tabular}{p{1.5cm}p{7cm}}
\toprule
\textbf{Dataset} & \textbf{Example} \\[0.5ex]
\toprule
\multirow{2}{*}{Huffpost} & 'Tis The Season To Be Cheeky With 'Jingle Butts' Music Video. Clip features both male and female butt models. $\rightarrow$ weird news \\ \cline{2-2}
& The 4 Best Last-Minute Christmas Gift Ideas. Scrambling to shop for that last relative, significant other or hard-to-buy-for friend? We're here to help. $\rightarrow$ style and beauty \\[0.5ex]
\hline
\multirow{2}{*}{FewNERD} & One of the Yak-3s was destroyed right away . $\rightarrow$ Yak-3s ! product airplane ;\\ \cline{2-2}
& All Together Now is a British reality television music competition which first aired on BBC One on 27 January 2018 . $\rightarrow$ All Together Now ! event other ; BBC One ! organization media ;\\[0.5ex]
\hline
\multirow{2}{*}{FewRel} & Its main base was at Tampere - Pirkkala Airport ( TMP ) , Tampere . Pirkkala Airport | Tampere $\rightarrow$ place served by trainsport hub\\ \cline{2-2}
& He represented Sweden at the 1934 FIFA World Cup . 1934 FIFA World Cup | Sweden $\rightarrow$ participating teams\\[0.5ex]
\bottomrule
\end{tabular}
}
\caption{Examples of text input $\rightarrow$ text target for Huffpost News, fewNERD and FewRel}
\label{table:appendix:examples_data}
\end{table}
\section{More Qualitative Examples} \label{appendix:qual}
Similar to \Cref{sec:exp:qual_analysis}, we show another example of \textsc{\small{ModularPrompt}}\xspace on stage-fused NER in Figure \ref{fig:appendix:case_study} and more example predictions in Figure \ref{fig:appendix:case_study_1}. These additional examples strengthen the conclusions in \Cref{sec:exp:qual_analysis}. In the second example in Figure \ref{fig:appendix:case_study_1}, \textsc{\small{ModularPrompt}}\xspace tags "Big Twin Sauce" as a \textit{product food} while its ground truth tag is \textit{product other}. We can see \textsc{\small{ModularPrompt}}\xspace considers the context as the entity is associated with a restaurant. Similarly, in the third example, "Kobo Touch" is actually a hardware reader and its ground truth tag is \textit{product other}. However, such world knowledge is not available and \textsc{\small{ModularPrompt}}\xspace tags it as a software based on the context of "eBooks" and libraries.
\begin{figure}[H]
\centering
\includegraphics[width=0.48\textwidth]{image/case_study_app_1.png}
\caption{\small Another example of \textsc{\small{ModularPrompt}}\xspace for stage-fused NER}
\label{fig:appendix:case_study}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[width=0.48\textwidth]{image/case_study_app_2.png}
\caption{\darkBlue{Successful} (blue) and \red{failure} (red) cases of \textsc{\small{ModularPrompt}}\xspace predictions for stage-fused NER}
\label{fig:appendix:case_study_1}
\end{figure}
\section{Detailed Results on Stage-agnostic and Stage-specific Settings} \label{sec:appendix_results}
Table \ref{appendix:table:agnostic:all} shows detailed stage-agnostic results. $D_{\{1..k\}}$ corresponds to multi-stage training over domains $\{1,..,k\}$ and testing over the aggregated domains. For baselines, we use their checkpoints after k-th stage for evaluating $D_{\{1..k\}}$. For \textsc{\small{ModularPrompt}}\xspace, we use the final checkpoint. Table \ref{appendix:fuse:news_ner}, \ref{appendix:fuse:re} show detailed stage-fused results. $D_k$' denotes k-th task fused stage.
\begin{table*}[htbp!]
\centering
\scalebox{0.65}{
\begin{tabular}{lllll|lll|llll}
\Xhline{3\arrayrulewidth}
\multirow{2}{*}{\textbf{Methods}} & \multicolumn{4}{c|}{News Classification} & \multicolumn{3}{c|}{NER} & \multicolumn{4}{c}{RE}\\ \cline{2-6} \cline{7-10} \cline{11-12}
& D$_{\{1..2\}}$ & D$_{\{1..3\}}$ & D$_{\{1..4\}}$ & D$_{\{1..5\}}$ & D$_{\{1..2\}}$ & D$_{\{1..3\}}$ & D$_{\{1..4\}}$ & D$_{\{1..2\}}$ & D$_{\{1..3\}}$ & D$_{\{1..4\}}$ & D$_{\{1..5\}}$ \\
\hline
Finetune$_{Multitask}$ & 60.0$_{\pm 5.2 }$ & 61.6$_{\pm 4.8 }$ & 62.1$_{\pm 4.3 }$ & 60.6$_{\pm 5.0 }$ & 64.3$_{\pm 0.3 }$ & 68.1$_{\pm 0.3 }$ & 64.5$_{\pm 0.2 }$ & 85.3$_{\pm 1.0 }$ & 87.4$_{\pm 0.6 }$ & 83.7$_{\pm 2.2 }$ & 87.9$_{\pm 0.6 }$\\[1ex]
\hline
Finetune & 57.8$_{\pm 0.9 }$ & 35.2$_{\pm 1.8 }$ & 29.4$_{\pm 1.2 }$ & 23.0$_{\pm 0.6 }$ & 39.8$_{\pm 0.4 }$ & 30.9$_{\pm 2.1 }$ & 25.0$_{\pm 2.7 }$ & 71.1$_{\pm 2.2 }$ & 57.4$_{\pm 2.5 }$ & 48.0$_{\pm 1.6 }$ & 40.8$_{\pm 2.2 }$\\
Finetune$_{EWC}$ & \textbf{61.4}$_{\pm 2.6 }$ & 35.3$_{\pm 1.8 }$ & 27.3$_{\pm 2.5 }$ & 22.5$_{\pm 1.2 }$ & 42.9$_{\pm 2.2 }$ & 37.8$_{\pm 4.8 }$ & 26.6$_{\pm 2.8 }$ & 79.2$_{\pm 3.5 }$ & 61.2$_{\pm 6.5 }$ & 52.5$_{\pm 3.4 }$ & 45.4$_{\pm 3.2 }$ \\
Finetune$_{MAS}$ & 58.9$_{\pm 1.1}$ & 46.9$_{\pm 2.8}$ & 38.7$_{\pm 3.0}$ & 29.2$_{\pm 2.9}$ & 48.6$_{\pm 7.5 }$ & 37.1$_{\pm 2.1 }$ & 25.4$_{\pm 2.9 }$ & 74.5$_{\pm 3.9 }$ & 61.3$_{\pm 2.7 }$ & 54.7$_{\pm 1.5 }$ & 46.2$_{\pm 1.8 }$\\
Adapter & 45.2$_{\pm 2.6 }$ & 29.3$_{\pm 0.4 }$ & 24.5$_{\pm 0.5 }$ & 19.3$_{\pm 0.3 }$ & 38.9$_{\pm 1.0 }$ & 27.7$_{\pm 0.7 }$ & 21.2$_{\pm 2.0 }$ & 56.6$_{\pm 1.4 }$ & 40.4$_{\pm 2.5 }$ & 36.9$_{\pm 1.2 }$ & 28.6$_{\pm 1.9 }$\\
Adapter$_{EWC}$ & 45.6$_{\pm 3.0}$ & 29.6$_{\pm 0.5}$ & 24.4$_{\pm 0.6}$ & 18.6$_{\pm 1.0}$ & 38.6$_{\pm 0.7}$ & 29.1$_{\pm 1.7}$ & 20.5$_{\pm 1.3}$ & 54.9$_{\pm 1.2}$ & 42.6$_{\pm 1.5}$ & 36.1$_{\pm 0.8}$ & 27.8$_{\pm 1.2}$ \\
Adapter$_{MAS}$ & 45.6$_{\pm 2.6}$ & 30.0$_{\pm 0.8}$ & 26.1$_{\pm 2.5}$ & 20.1$_{\pm 1.5}$ & 38.2$_{\pm 0.3}$ & 28.6$_{\pm 1.1}$ & 21.1$_{\pm 2.0}$ & 57.1$_{\pm 2.9}$ & 40.5$_{\pm 1.9}$ & 35.5$_{\pm 1.9}$ & 28.3$_{\pm 0.5}$ \\
PT & 36.9$_{\pm 0.5}$ & 27.9$_{\pm 0.4}$ & 21.7$_{\pm 0.4}$ & 16.1$_{\pm 0.3}$ & 37.0$_{\pm 0.3 }$ & 26.1$_{\pm 0.3 }$ & 18.8$_{\pm 0.1 }$ & 47.3$_{\pm 1.0 }$ & 32.4$_{\pm 0.5 }$ & 24.3$_{\pm 0.4 }$ & 19.6$_{\pm 0.1 }$ \\
PT$_{EWC}$ & 36.9$_{\pm 1.1}$ & 28.2$_{\pm 0.2}$ & 21.5$_{\pm 0.3}$ & 16.5$_{\pm 0.5}$ & 36.7$_{\pm 0.8}$ & 26.0$_{\pm 0.4}$ & 19.0$_{\pm 0.5}$ & 46.8$_{\pm 0.5}$ & 32.3$_{\pm 1.2}$ & 25.4$_{\pm 0.9}$ & 20.1$_{\pm 0.8}$ \\
PT$_{MAS}$ & 43.0$_{\pm 3.5}$ & 30.1$_{\pm 5.2}$ & 24.1$_{\pm 4.5}$ & 23.8$_{\pm 5.9}$ & 28.8$_{\pm 2.8}$ & 29.2$_{\pm 6.0}$ & 29.3$_{\pm 4.6}$ & 51.3$_{\pm 1.3}$ & 36.0$_{\pm 0.9}$ & 30.7$_{\pm 1.7}$ & 25.1$_{\pm 4.9}$ \\
PT$_{CL}$ & 60.3$_{\pm 3.7 }$ & 41.8$_{\pm 7.5 }$ & 35.4$_{\pm 3.3 }$ & 28.1$_{\pm 2.9 }$ & 47.4$_{\pm 4.6 }$ & 39.7$_{\pm 3.9 }$ & 30.9$_{\pm 5.4 }$ & 69.9$_{\pm 7.8 }$ & 54.3$_{\pm 3.9 }$ & 47.9$_{\pm 4.2 }$ & 43.1$_{\pm 4.9 }$\\[1ex]
\hline
ModularPT & 60.3$_{\pm 3.9 }$ & \textbf{53.9}$_{\pm 2.3 }$ & \textbf{51.1}$_{\pm 1.4 }$ & \textbf{43.2}$_{\pm 0.6 }$ & \textbf{63.3}$_{\pm 1.4 }$ & \textbf{53.9}$_{\pm 4.3 }$ & \textbf{44.8}$_{\pm 4.9 }$ & \textbf{81.3}$_{\pm 3.3 }$ & \textbf{70.1}$_{\pm 3.7 }$ & \textbf{65.1}$_{\pm 2.2 }$ & \textbf{61.8}$_{\pm 1.8 }$\\
w/o transfer & 61.2$_{\pm 2.8}$ & 48.9$_{\pm 2.4}$ & 43.1$_{\pm 2.7}$ & 35.4$_{\pm 2.7}$ & 62.6$_{\pm 1.4}$ & 53.8$_{\pm 1.7}$ & 43.0$_{\pm 3.6}$ & 82.2$_{\pm 2.3}$ & 67.2$_{\pm 3.2}$ & 59.4$_{\pm 2.0}$ & 54.8$_{\pm 2.7}$\\
w/o subset\_inv & 62.4$_{\pm 1.9}$ & 53.9$_{\pm 3.2}$ & 50.0$_{\pm 2.9}$ & 41.1$_{\pm 2.4}$ & 60.0$_{\pm 2.8}$ & 51.2$_{\pm 3.5}$ & 40.0$_{\pm 4.6}$ & 74.4$_{\pm 10.9}$ & 66.2$_{\pm 4.8}$ & 60.3$_{\pm 3.5}$ & 58.2$_{\pm 2.6}$\\[1ex]
\Xhline{3\arrayrulewidth}
\end{tabular}
}
\caption{Detailed Stage-agnostic Performance on News Classification, NER and RE.}
\label{appendix:table:agnostic:all}
\end{table*}
\begin{table*}
\centering
\scalebox{0.67}{
\begin{tabular}{lllllll|lllll}
\Xhline{3\arrayrulewidth}
\multirow{2}{*}{\textbf{Methods}} & \multicolumn{6}{c|}{News Classification} & \multicolumn{5}{c}{NER} \\ \cline{2-7} \cline{8-12}
& D1' & D2' & D3' & D4' & D5' & Mean & D1' & D2' & D3' & D4' & Mean \\
\hline
Finetune$_{Multitask}$ & 58.5$_{\pm 0.7 }$ & 57.5$_{\pm 1.7 }$ & 60.8$_{\pm 2.7 }$ & 64.4$_{\pm 1.8 }$ & 62.2$_{\pm 1.6 }$ & 60.7$_{\pm 0.6 }$ & 64.3$_{\pm 1.0 }$ & 53.8$_{\pm 0.1 }$ & 51.0$_{\pm 0.7 }$ & 59.1$_{\pm 0.2 }$ & 57.0$_{\pm 0.0 }$ \\ [0.5ex]
\hline
Finetune & 20.5$_{\pm 1.5 }$ & 21.7$_{\pm 1.2 }$ & 21.8$_{\pm 1.3 }$ & 24.5$_{\pm 1.3 }$ & 23.4$_{\pm 1.0 }$ & 22.4$_{\pm 0.5 }$ & 20.9$_{\pm 2.9 }$ & 24.1$_{\pm 2.9 }$ & 35.4$_{\pm 1.8 }$ & 19.1$_{\pm 3.4 }$ & 24.9$_{\pm 2.1 }$ \\
Finetune$_{EWC}$ & 20.9$_{\pm 1.7 }$ & 21.9$_{\pm 0.7 }$ & 21.2$_{\pm 2.2 }$ & 25.6$_{\pm 1.8 }$ & 23.3$_{\pm 1.7 }$ & 22.6$_{\pm 1.0 }$ & 21.8$_{\pm 1.5 }$ & 24.6$_{\pm 1.4 }$ & 34.7$_{\pm 2.0 }$ & 19.3$_{\pm 4.2 }$ & 25.1$_{\pm 1.7 }$ \\
Finetune$_{MAS}$ & 26.4$_{\pm 6.2 }$ & 25.6$_{\pm 2.9 }$ & 26.8$_{\pm 3.4 }$ & 38.4$_{\pm 7.0 }$ & 26.5$_{\pm 6.4 }$ & 28.8$_{\pm 3.3 }$ & 22.4$_{\pm 3.5 }$ & 25.2$_{\pm 0.9 }$ & 19.1$_{\pm 4.4 }$ & 27.2$_{\pm 5.9 }$ & 23.5$_{\pm 1.3 }$ \\
Adapter & 15.8$_{\pm 0.9 }$ & 20.5$_{\pm 0.4 }$ & 15.5$_{\pm 2.0 }$ & 22.6$_{\pm 0.6 }$ & 19.6$_{\pm 1.2 }$ & 18.8$_{\pm 0.3 }$ & 17.1$_{\pm 2.0 }$ & 21.6$_{\pm 3.3 }$ & 33.5$_{\pm 1.7 }$ & 15.0$_{\pm 1.9 }$ & 21.8$_{\pm 1.7 }$ \\
Adapter$_{EWC}$ & 15.2$_{\pm 1.3}$ & 20.4$_{\pm 0.5}$ & 13.7$_{\pm 2.0}$ & 23.5$_{\pm 1.9}$ & 18.0$_{\pm 1.4}$ & 18.1$_{\pm 1.0}$ & 17.3$_{\pm 1.8}$ & 21.0$_{\pm 2.5}$ & 33.8$_{\pm 1.6}$ & 14.5$_{\pm 1.5}$ & 21.7$_{\pm 1.5}$ \\
Adapter$_{MAS}$ & 17.3$_{\pm 2.0}$ & 20.2$_{\pm 0.4}$ & 16.5$_{\pm 1.3}$ & 23.5$_{\pm 2.3}$ & 20.3$_{\pm 2.5}$ & 19.6$_{\pm 1.4}$ & 16.7$_{\pm 2.1}$ & 20.4$_{\pm 2.5}$ & 34.1$_{\pm 2.3}$ & 14.2$_{\pm 2.0}$ & 21.4$_{\pm 2.0}$ \\
PT & 13.7$_{\pm 0.3 }$ & 19.6$_{\pm 0.3 }$ & 8.3$_{\pm 0.2 }$ & 21.0$_{\pm 1.3 }$ & 15.6$_{\pm 0.6 }$ & 15.7$_{\pm 0.2 }$ & 14.9$_{\pm 1.2 }$ & 17.2$_{\pm 0.8 }$ & 31.9$_{\pm 1.3 }$ & 13.2$_{\pm 1.0 }$ & 19.3$_{\pm 0.5 }$ \\
PT$_{EWC}$ & 13.7$_{\pm 0.4}$ & 19.7$_{\pm 0.2}$ & 9.2$_{\pm 1.5}$ & 21.9$_{\pm 0.5}$ & 15.8$_{\pm 1.1}$ & 16.1$_{\pm 0.5}$ & 14.7$_{\pm 0.8}$ & 18.5$_{\pm 1.9}$ & 33.0$_{\pm 1.3}$ & 14.0$_{\pm 1.5}$ & 20.0$_{\pm 1.0}$ \\
PT$_{MAS}$ & 25.3$_{\pm 6.0}$ & 21.9$_{\pm 3.9}$ & 20.0$_{\pm 13.4}$ & 27.6$_{\pm 7.9}$ & 23.8$_{\pm 5.3}$ & 23.7$_{\pm 6.2}$ & 26.1$_{\pm 3.1}$ & 20.7$_{\pm 2.5}$ & 22.3$_{\pm 4.2}$ & 31.9$_{\pm 7.8}$ & 25.3$_{\pm 3.8}$ \\
PT$_{CL}$ & 25.7$_{\pm 5.9 }$ & 27.1$_{\pm 5.5 }$ & 21.9$_{\pm 5.5 }$ & 29.1$_{\pm 7.3 }$ & 33.9$_{\pm 4.8 }$ & 27.5$_{\pm 2.8 }$ & 28.1$_{\pm 4.3 }$ & 34.7$_{\pm 4.8 }$ & 30.5$_{\pm 6.0 }$ & 28.2$_{\pm 7.9 }$ & 30.4$_{\pm 5.1 }$ \\[0.5ex]
\hline
Finetune$^*_{MAS}$ & 47.9$_{\pm 2.4}$ & 49.7$_{\pm 5.5}$ & 55.8$_{\pm 4.7}$ & 52.4$_{\pm 2.5}$ & 58.2$_{\pm 4.9}$ & 52.8$_{\pm 2.2}$ & 23.3$_{\pm 2.8}$ & 29.3$_{\pm 1.8}$ & 22.3$_{\pm 1.7}$ & 28.3$_{\pm 2.0}$ & 25.8$_{\pm 1.7}$ \\
PT$^*_{CL}$ & 56.1$_{\pm 6.3}$ & 62.5$_{\pm 4.7}$ & 57.5$_{\pm 6.6}$ & 55.8$_{\pm 9.4}$ & 55.5$_{\pm 2.0}$ & 57.5$_{\pm 5.2}$ & 33.1$_{\pm 4.0}$ & 37.4$_{\pm 1.4}$ & 28.2$_{\pm 4.9}$ & 38.6$_{\pm 2.0}$ & 34.3$_{\pm 2.4}$ \\[0.5ex]
\hline
ModularPT & \textbf{71.6}$_{\pm 3.0 }$ & \textbf{75.8}$_{\pm 4.0 }$ & \textbf{76.5}$_{\pm 2.0 }$ & \textbf{79.1}$_{\pm 3.3 }$ & \textbf{71.0}$_{\pm 1.6 }$ & \textbf{74.8}$_{\pm 1.7 }$ & \textbf{62.8}$_{\pm 4.0 }$ & \textbf{60.7}$_{\pm 1.1 }$ & \textbf{61.5}$_{\pm 2.5 }$ & \textbf{61.5}$_{\pm 4.4 }$ & \textbf{61.6}$_{\pm 2.2 }$ \\
w/o transfer & 67.8$_{\pm 3.9}$ & 69.7$_{\pm 3.0}$ & 66.7$_{\pm 5.3}$ & 63.8$_{\pm 3.3}$ & 56.6$_{\pm 5.3}$ & 64.9$_{\pm 1.7}$ & 56.0$_{\pm 4.5}$ & 51.2$_{\pm 7.6}$ & 61.3$_{\pm 1.6}$ & 61.2$_{\pm 2.7}$ & 57.4$_{\pm 2.3}$ \\
w/o subset\_inv & 61.3$_{\pm 7.7}$ & 55.9$_{\pm 11.8}$ & 60.4$_{\pm 5.2}$ & 61.0$_{\pm 3.0}$ & 53.7$_{\pm 7.2}$ & 58.5$_{\pm 3.0}$ & 51.9$_{\pm 9.5}$ & 37.5$_{\pm 3.7}$ & 40.7$_{\pm 7.3}$ & 46.3$_{\pm 4.3}$ & 44.1$_{\pm 2.9}$\\
[0.5ex]
\Xhline{3\arrayrulewidth}
\end{tabular}
}
\caption{Detailed Stage-fused Performance on News Classification and NER}
\label{appendix:fuse:news_ner}
\end{table*}
\begin{table}[H]
\centering
\scalebox{0.58}{
\begin{tabular}{lllllll}
\Xhline{3\arrayrulewidth}
\multirow{2}{*}{\textbf{Methods}} & \multicolumn{5}{c}{RE} &\multirow{2}{*}{\textbf{Mean}}\\ \cline{2-6}
& D1' & D2' & D3' & D4' & D5' \\
\hline
Finetune$_{Multitask}$ & 80.5$_{\pm 2.1 }$ & 90.3$_{\pm 1.6 }$ & 85.4$_{\pm 1.2 }$ & 88.5$_{\pm 0.9 }$ & 85.4$_{\pm 1.0 }$ & 86.0$_{\pm 0.9 }$\\[1ex]
\hline
Finetune & 31.2$_{\pm 2.8 }$ & 49.6$_{\pm 3.5 }$ & 37.4$_{\pm 4.0 }$ & 43.3$_{\pm 3.7 }$ & 42.2$_{\pm 1.3 }$ & 40.7$_{\pm 2.1 }$\\
Finetune$_{EWC}$ & 34.3$_{\pm 4.1 }$ & 57.8$_{\pm 3.6 }$ & 40.6$_{\pm 2.5 }$ & 46.9$_{\pm 6.0 }$ & 46.5$_{\pm 2.1 }$ & 45.2$_{\pm 3.3 }$\\
Finetune$_{MAS}$ & 41.7$_{\pm 3.0 }$ & 60.1$_{\pm 3.4 }$ & 52.2$_{\pm 4.2 }$ & 46.1$_{\pm 3.8 }$ & 34.4$_{\pm 3.7 }$ & 46.9$_{\pm 1.9 }$\\
Adapter & 21.0$_{\pm 0.6 }$ & 33.8$_{\pm 4.6 }$ & 21.3$_{\pm 1.3 }$ & 32.9$_{\pm 2.0 }$ & 32.0$_{\pm 2.6 }$ & 28.2$_{\pm 1.8 }$\\
Adapter$_{EWC}$ & 20.1$_{\pm 0.7}$ & 31.1$_{\pm 3.7}$ & 19.7$_{\pm 0.3}$ & 34.0$_{\pm 2.8}$ & 32.0$_{\pm 3.4}$ & 27.4$_{\pm 1.2}$ \\
Adapter$_{MAS}$ & 20.1$_{\pm 0.5}$ & 32.2$_{\pm 2.1}$ & 22.5$_{\pm 1.6}$ & 31.6$_{\pm 3.1}$ & 32.7$_{\pm 2.4}$ & 27.8$_{\pm 0.6}$ \\
PT & 19.6$_{\pm 0.1 }$ & 20.8$_{\pm 0.7 }$ & 20.3$_{\pm 1.2 }$ & 18.5$_{\pm 0.2 }$ & 19.0$_{\pm 0.3 }$ & 19.6$_{\pm 0.2 }$ \\
PT$_{EWC}$ & 19.8$_{\pm 0.1}$ & 22.2$_{\pm 3.0}$ & 19.9$_{\pm 0.4}$ & 18.5$_{\pm 0.1}$ & 19.8$_{\pm 1.1}$ & 20.0$_{\pm 0.8}$ \\
PT$_{MAS}$ & 18.8$_{\pm 6.9}$ & 25.0$_{\pm 9.1}$ & 22.8$_{\pm 5.9}$ & 32.7$_{\pm 8.1}$ & 25.5$_{\pm 3.7}$ & 24.9$_{\pm 5.1}$ \\
PT$_{CL}$ & 37.6$_{\pm 9.1 }$ & 51.1$_{\pm 4.4 }$ & 37.8$_{\pm 4.4 }$ & 41.4$_{\pm 4.7 }$ & 48.4$_{\pm 6.1 }$ & 43.3$_{\pm 5.2 }$\\[0.5ex]
\hline
Finetune$^*_{MAS}$ & 55.7$_{\pm 3.8}$ & 72.9$_{\pm 2.6}$ & 69.8$_{\pm 3.5}$ & 80.2$_{\pm 2.2}$ & 62.0$_{\pm 2.8}$ & 68.1$_{\pm 1.3}$\\
PT$^*_{CL}$ & 58.8$_{\pm 5.1}$ & 65.1$_{\pm 4.0}$ & 61.1$_{\pm 1.6}$ & 78.3$_{\pm 3.3}$ & 63.3$_{\pm 3.5}$ & 65.3$_{\pm 2.7}$\\[0.5ex]
\hline
ModularPT & \textbf{80.3}$_{\pm 1.6 }$ & \textbf{89.2}$_{\pm 2.5 }$ & \textbf{75.1}$_{\pm 3.9 }$ & \textbf{88.5}$_{\pm 2.7 }$ & \textbf{78.6}$_{\pm 0.8 }$ & \textbf{82.4}$_{\pm 0.8 }$ \\
w/o transfer & 73.5$_{\pm 2.6}$ & 85.1$_{\pm 1.9}$ & 66.9$_{\pm 7.4}$ & 88.2$_{\pm 2.6}$ & 73.7$_{\pm 3.6}$ & 77.5$_{\pm 1.2}$\\
w/o subset\_inv & 45.1$_{\pm 5.1}$ & 50.6$_{\pm 6.1}$ & 48.3$_{\pm 5.9}$ & 46.5$_{\pm 4.8}$ & 48.0$_{\pm 6.7}$ & 47.7$_{\pm 4.1}$\\
[1ex]
\Xhline{3\arrayrulewidth}
\end{tabular}
}
\caption{Detailed Stage-fused Performance on RE}
\label{appendix:fuse:re}
\end{table}
\section{Conclusion}
In this paper, we have proposed \textsc{\small{ModularPrompt}}\xspace, a novel label modular prompt tuning framework for text classification \textit{in-the-wild}. Extensive experiments show that \textsc{\small{ModularPrompt}}\xspace is able to consolidate knowledge learned during sequential training stages for stage-agnostic testing and extract and recompose knowledge for stage-fused testing, while maintaining competitive performance in stage-specific settings. We have also conduct analysis to show that \textsc{\small{ModularPrompt}}\xspace has desirable modular properties of label grounding, low order sensitivity and in-context learning.
Being the first work on modular parameter efficient tuning, we hope for it to spur more research in this area in future towards solving a wider range of tasks under more general non-stationary settings.
\section*{Limitations}
In this section, we discuss limitations and potential future work towards extending \textsc{\small{ModularPrompt}}\xspace to a more generalised method for wider applicability.
\paragraph{On Scalability} In \textsc{\small{ModularPrompt}}\xspace, the input prompt $\T$ grows in proportion to $|S|$, the size of label set of interest. This limits \textsc{\small{ModularPrompt}}\xspace from supporting huge label set (e.g., thousands of labels) as transformers
can only condition on a bounded-length context. With long range transformers like Longformer \cite{Longformer}, Performer \cite{Performer} and LongT5 \cite{LongT5} coming into vogue, this issue is somewhat mitigated. Regardless of that, one potential solution is to formulate a hierarchical version of \textsc{\small{ModularPrompt}}\xspace, which is similar in spirit to hierarchical softmax \cite{hierarchical_softmax}. Hierarchical \textsc{\small{ModularPrompt}}\xspace takes multiple steps for prediction, with each step to predict labels in a specific hierarchy level.
Another potential solution is to treat all label prompts as memory units from which the model learns to select relevant ones for a given data instance, in the spirit of \cite{memorizing_transformers}.
\paragraph{On generation tasks}
As \textsc{\small{ModularPrompt}}\xspace shows SoTA performance and good modular characteristics for text classification \textit{in-the-wild}, it is appealing to extend it to other tasks like Question Answering (QA), Machine Reading Comprehension (MRC) and Summarization. However, it is non-trivial for \textsc{\small{ModularPrompt}}\xspace to incorporate these tasks as their target texts are unstructured without clear class labels. One potential solution is to instead consider attributes or properties of target texts, which are also conditioning factors (e.g., formality, conciseness, topics, aspects, sentiment for summarization). With such definitions, it will be interesting to check if \textsc{\small{ModularPrompt}}\xspace framework can achieve good generalisation and conditional generation on text generation in-the-wild.
\begin{comment}
This document has been adapted by Yue Zhang, Ryan Cotterell and Lea Frermann from the style files used for earlier ACL and NAACL proceedings, including those for
ACL 2020 by Steven Bethard, Ryan Cotterell and Rui Yan,
ACL 2019 by Douwe Kiela and Ivan Vuli\'{c},
NAACL 2019 by Stephanie Lukin and Alla Roskovskaya,
ACL 2018 by Shay Cohen, Kevin Gimpel, and Wei Lu,
NAACL 2018 by Margaret Mitchell and Stephanie Lukin,
Bib\TeX{} suggestions for (NA)ACL 2017/2018 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-Shin 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}.
\end{comment}
\section{Experiments}
In this section, we first introduce datasets used and data construction process (\Cref{sec:exp:tasks}) followed by relevant baselines (\Cref{sec:exp:baselines}), evaluation methods (\Cref{sec:exp:eval}) and implementation details (\Cref{sec:exp:imp}). Through our experiments, we target three research questions:
\begin{enumerate}[leftmargin=*,topsep=2pt,itemsep=2pt,parsep=0pt]
\item Can \textsc{\small{ModularPrompt}}\xspace consolidate knowledge over multi-stage training? $\rightarrow$ answered in \Cref{sec:exp:agnostic} with stage-agnostic setting
\item Can \textsc{\small{ModularPrompt}}\xspace adapt to dynamic label space at inference? $\rightarrow$ answered in \Cref{sec:exp:fuse} with stage-fused setting
\item How competitive is \textsc{\small{ModularPrompt}}\xspace in stage-specific setting? $\rightarrow$ answered in \Cref{sec:exp:specific}
\end{enumerate}
Additionally, we perform ablations (\Cref{sec:exp:ablation}) and quantitative and qualitative analysis (\Cref{sec:exp:quant_analysis}-\Cref{sec:exp:qual_analysis}) to verify modular properties of \textsc{\small{ModularPrompt}}\xspace.
\subsection{Tasks and Datasets} \label{sec:exp:tasks}
We conduct experiments on three types of NLP tasks: News Domain Classification on HuffpostNews \cite{huffpost}, Name Entity Recognition (NER) on fewNERD \cite{fewNERD} and Relation Extraction (RE) on FewRel \cite{fewrel}. We formulate all tasks as a text-to-text problem, as defined in \Cref{in-the-wild}.
For News Domain Classification and NER, we construct target text following \citet{lfpt5}.
For RE, we concatenate the original text and entities with a seperator '|' as the input sequence, and use the relation type as the target. (Example data can be found at \cref{appendix:dataset})
For HuffpostNews, we subsample 100 shots per class for training and validation and split it into 5 stages of disjoint labels. For FewNERD and FewRel, we subsample 50 shots for training and validation and split into 4 and 5 stages, respectively. For testing, we subsample 200, 50, and 50 shots per class for HuffpostNews, FewNERD and FewRel, respectively. The total number of labels for \{HuffpostNews,FewNERD,FewRel\} is \{41,64,80\} respectively, and resulting label size per stage is \{8-9,16,16\} respectively.
For stage-specific testing, we follow the stages defined for training and construct a corresponding test data for each stage. For stage-agnostic testing, we combine stage-specific test data for current stage and all previously seen stages to construct the test data. For stage-fused testing, we construct label-sets for each fused stage such that it is not a subset of any single \text{prior} training stage, but rather contains labels from `all' {prior} training stages.
We construct \{5,4,5\} fused stages for \{HuffpostNews,FewNERD,FewRel\}. We conduct 5 randomised trials with different data sampling and experiment seed for all of the above settings.
\begin{comment}
\end{comment}
\subsection{Baselines} \label{sec:exp:baselines}
We use T5-large \cite{T5} as the backbone PLM for all methods, and consider the following baselines to compare with our \textsc{\small{ModularPrompt}}:
\noindent
\begin{itemize}[leftmargin=*]
\vspace{-0.5em}
\item \textsc{\small{ModelTuning}} (Finetune), which tunes all parameters of the backbone PLM.
\vspace{-0.5em}
\item (i) \textsc{\small{PromptTuning}} (PT) from \Cref{soft-prompt}, (ii) PT$_{\text{CL}}$ - An extension of PT to continual learning (CL) setting, which trains separate PT models for each stage and concatenates the learned soft-prompts during inference, based on the test label-set.
\vspace{-0.5em}
\item Adapter, a parameter efficient tuning alternative introduced in \cite{adapter}, which inserts light adapter layers into the backbone PLM and only tune them.
\end{itemize}
\vspace{-0.5em}
As text classification \textit{in-the-wild} overlaps with continual learning, we also compare with versions of the above baselines that use architecture-agnostic methods and settings relevant to the latter.
\noindent
\begin{itemize}[leftmargin=*]
\vspace{-0.5em}
\item Online regularization based methods: (i) A scalable online version of EWC \cite{EWC} proposed in \cite{onlineEWC}, and (ii) Online MAS \cite{MAS}. These methods measure the importance of parameters to previous tasks by fisher information, and restrict updating previously important parameters when learning a new task, to mitigate catastrophic forgetting.
\vspace{-0.5em}
\item Multitask model, which involves training on all stages simultaneously, not sequentially. This is infact an oracle method for stage-agnostic testing and can be considered as an upper bound of memory-based methods in continual learning.
\end{itemize}
\subsection{Evaluation Methods} \label{sec:exp:eval}
For all the three NLP tasks, we consider an \emph{exact match} as a correct prediction and report accuracy for News Classification and RE, and compute F1-score over the BIO format for the NER task. By default, we do not apply any other post-processing or verbalizer, though these are orthogonal methods that can be separately used to enhance any of the discussed models. In the stage-fused setting, we apply constrained decoding similar to \cite{constrained_decode} to selected baselines, marked by special indicator * (e.g., Finetune$^*_{\text{MAS}}$). For \textsc{\small{ModularPrompt}}, we use all seen label prompts for stage-agnostic testing and specific set of label prompts for stage-specific and stage-fused testing. Since other baselines do not have label-level modularity, for stage-agnostic and stage-fused testing, we use the checkpoint after the final stage and for stage-specific testing we take their checkpoints after each training stage. We show average performance in the main paper and relegate detailed results to Appendix \ref{sec:appendix_results}.
\subsection{Implementation Details} \label{sec:exp:imp}
We set the learning rate to 0.5 for \textsc{\small{PromptTuning}} and \textsc{\small{ModularPrompt}} and 5e-5 for \textsc{\small{ModelTuning}} and Adapter, using Adafactor \cite{adafactor} optimizer. We adopt implementation of Adapter from OpenDelta \cite{OpenDelta} and use the default bottleneck dimension of 24. For online EWC and MAS, we report best results obtained over different regularization constant. For all methods, we set maximum training epochs to 256 for FuffpostNews and FewNERD, and to 512 for FewRel. For \textsc{\small{ModularPrompt}}, the number of soft tokens per label prompt is set to 10, the selection probability $p$ is set to 50\% and number of label transfer candidates K in \Cref{sec:mprompt_in_the_wild} is set to 3.
\subsection{Results on Stage-agnostic Setting} \label{sec:exp:agnostic}
In Table \ref{table:agnostic:all}, we show the stage-agnostic testing results.
We observe that across all three tasks, \textsc{\small{ModularPrompt}} significantly outperforms all other baselines by a large margin. This empirically justifies that \textsc{\small{ModularPrompt}} is indeed able to dynamically combine the label-specific knowledge learned across different training stages in order to infer over the \emph{unseen} combined label-space. Amongst the baselines, \textsc{\small{ModelTuning}} performs relatively better, while the limited trainable parameters make the parameter efficient models more susceptible to catastrophic forgetting.
{For CL methods, MAS improves \textsc{\small{ModelTuning}} and \textsc{\small{PromptTuning}} by 4\% and 8\% on average respectively, but fails on Adapter. EWC is less effective in addressing forgetting across all baselines.}
Also note that the PT$_{\text{CL}}$ extension is able to improve by 10-20\% over vanila PT. This shows that soft prompts, behaving like language tokens, have a compositional nature and can be concatenated to support multi-tasking. \textsc{\small{ModularPrompt}}, in addition to exploiting this implicit language prior, also explicitly imposes subset-invariant loss to adapt to dynamic label spaces, further boosting stage-agnostic performance by 14\%-18\% over PT$_{\text{CL}}$.
\begin{table}
\centering
\scalebox{0.75}{
\begin{tabular}{llccc}
\toprule
\textbf{Methods} & \textbf{Size} & News & NER & RE\\
\toprule
Finetune$_{\text{multitask}}$ & 770M & 60.6$_{\pm 5.0 }$ & 64.5$_{\pm 0.2 }$ & 87.9$_{\pm 0.6 }$\\[0.5ex]
\midrule
Finetune & 770M & 23.0$_{\pm 0.6 }$ & 25.0$_{\pm 2.7 }$ & 40.8$_{\pm 2.2 }$\\
Finetune$_{\text{EWC}}$ & 770M & 22.5$_{\pm 1.2 }$ & 26.6$_{\pm 2.8 }$ & 45.4$_{\pm 3.2 }$ \\
Finetune$_{\text{MAS}}$ & 770M & 29.2$_{\pm 2.9}$ & 25.4$_{\pm 2.9 }$ & 46.2$_{\pm 1.8 }$\\
Adapter & 4.8M & 19.3$_{\pm 0.3 }$ & 21.2$_{\pm 2.0 }$ & 28.6$_{\pm 1.9 }$\\
Adapter$_{\text{EWC}}$ & 4.8M & 18.6$_{\pm 1.0}$ & 20.5$_{\pm 1.3}$ & 27.8$_{\pm 1.2}$ \\
Adapter$_{\text{MAS}}$ & 4.8M & 20.1$_{\pm 1.5}$ & 21.1$_{\pm 2.0}$ & 28.3$_{\pm 0.5}$ \\
PT & 0.13M & 16.1$_{\pm 0.3}$ & 18.8$_{\pm 0.1 }$ & 19.6$_{\pm 0.1 }$ \\
PT$_{\text{EWC}}$ & 0.13M & 16.5$_{\pm 0.5}$ & 19.0$_{\pm 0.5}$ & 20.1$_{\pm 0.8}$ \\
PT$_{\text{MAS}}$ & 0.13M & 23.8$_{\pm 5.9}$ & 29.3$_{\pm 4.6}$ & 25.1$_{\pm 4.9}$ \\
PT$_{\text{CL}}$ & 0.13M & 28.1$_{\pm 2.9 }$ & 30.9$_{\pm 5.4 }$ & 43.1$_{\pm 4.9 }$\\[0.5ex]
\hline
ModularPT & 0.13M & \textbf{43.2}$_{\pm 0.6 }$ & \textbf{44.8}$_{\pm 4.9 }$ & \textbf{61.8}$_{\pm 1.8 }$\\
\bottomrule
\end{tabular}
}
\caption{\textbf{Stage-agnostic} performance on News Classification, NER and Relation Extraction (RE). \textbf{Size} denotes average number of tunable parameters per training stage}
\label{table:agnostic:all}
\end{table}
\subsection{Results on Stage-fused Setting} \label{sec:exp:fuse}
We present results on our novel stage-fused setting in Table \ref{table:fuse:all}. We observe that none of the baselines are capable of handling this setting, as is evident from their abysmal performance across all testing stages. In absence of any label-modular representation, they are unable to utilize any information about the desired label-space. On the other hand, \textsc{\small{ModularPrompt}} not only outperforms all baselines by an average margin of 37.5\%, it also achieves 4\%-14\% better performance than the oracle multi-task \textsc{\small{ModelTuning}} on News Classification and NER.
We select the top performing baselines in this setting and apply constrained decoding to them (marked with *), which improves their performance by 20\%-30\% on News and RE, 2\%-4\% on NER. However, \textsc{\small{ModularPrompt}}\xspace still outperforms these baselines by 14\%-27\%. This significant improvement is evident of the fact that \textsc{\small{ModularPrompt}}, by learning label-modular representations, can effectively combine partial knowledge from different training stages and condition the PLM on any target set of label prompts. This allows it to seamlessly adapt to dynamic unseen label spaces, without applying any post-processing or verbalizer.
\begin{table}[t!]
\centering
\scalebox{0.75}{
\begin{tabular}{llccc}
\toprule
\textbf{Methods} & \textbf{Size} & News & NER & RE\\
\toprule
Finetune$_{\text{multitask}}$ & 770M & 60.7$_{\pm 0.6 }$ & 57.0$_{\pm 0.0 }$ & 86.0$_{\pm 0.9 }$\\[0.5ex]
\hline
Finetune & 770M & 22.4$_{\pm 0.5 }$ & 24.9$_{\pm 2.1 }$ & 40.7$_{\pm 2.1 }$\\
Finetune$_{\text{EWC}}$ & 770M & 22.6$_{\pm 1.0 }$ & 25.1$_{\pm 1.7 }$ & 45.2$_{\pm 3.3 }$\\
Finetune$_{\text{MAS}}$ & 770M & 28.8$_{\pm 3.3 }$ & 23.5$_{\pm 1.3 }$ & 46.9$_{\pm 1.9 }$\\
Adapter & 4.8M & 18.8$_{\pm 0.3 }$ & 21.8$_{\pm 1.7 }$ & 28.2$_{\pm 1.8 }$\\
Adapter$_{\text{EWC}}$ & 4.8M & 18.1$_{\pm 1.0}$ & 21.7$_{\pm 1.5}$ & 27.4$_{\pm 1.2}$ \\
Adapter$_{\text{MAS}}$ & 4.8M & 19.6$_{\pm 1.4}$ & 21.4$_{\pm 2.0}$ & 27.8$_{\pm 0.6}$ \\
PT & 0.13M & 15.7$_{\pm 0.2 }$ & 19.3$_{\pm 0.5 }$ & 19.6$_{\pm 0.2 }$ \\
PT$_{\text{EWC}}$ & 0.13M & 16.1$_{\pm 0.5}$ & 20.0$_{\pm 1.0}$ & 20.0$_{\pm 0.8}$ \\
PT$_{\text{MAS}}$ & 0.13M & 23.7$_{\pm 6.2}$ & 25.3$_{\pm 3.8}$ & 24.9$_{\pm 5.1}$ \\
PT$_{\text{CL}}$ & 0.13M & 27.5$_{\pm 2.8 }$ & 30.4$_{\pm 5.1 }$ & 43.3$_{\pm 5.2 }$\\[0.5ex]
\hline
Finetune$^*_{\text{MAS}}$ & 770M & 52.8$_{\pm 2.2}$ & 25.8$_{\pm 1.7}$ & 68.1$_{\pm 1.3}$\\
PT$^*_{\text{CL}}$ & 0.13M & 57.5$_{\pm 5.2}$ & 34.3$_{\pm 2.4}$ & 65.3$_{\pm 2.7}$\\[0.5ex]
\hline
ModularPT & 0.13M & \textbf{74.8}$_{\pm 1.7 }$ & \textbf{61.6}$_{\pm 2.2 }$ & \textbf{82.4}$_{\pm 0.8 }$ \\
\bottomrule
\end{tabular}
}
\caption{\textbf{Stage-fused} performance on News Classification, NER and relation extraction (RE)}
\label{table:fuse:all}
\end{table}
Note that while PT$_{\text{CL}}$ is able to combine knowledge from multiple training stages to support stage-agnostic testing, it fails to extract and consolidate specific knowledge corresponding to only the target label-set, across different stages.
\subsection{Results on Stage-specific Setting} \label{sec:exp:specific}
While \textsc{\small{ModularPrompt}} has proved to be particularly successful in handling the challenging non-stationary settings of stage-agnostic and stage-fused evaluations, we now want to see how competitive it is under stage-specific settings. From the results in Table \ref{table:specific:all}, we see that the average stage-specific performance of \textsc{\small{ModularPrompt}} is comparable to vanila \textsc{\small{PromptTuning}} on the three tasks.
Note that while MAS regularization boosts stage-agnostic performance somewhat for \textsc{\small{ModelTuning}} and \textsc{\small{PromptTuning}}, it infact degrades their stage-specific performance by 10\%-40\%. Similarly applying EWC regularization fails to improve over the vanila models in this setting while also proving less effective on stage-agnostic evaluation. This shows the lack of robustness of these techniques across the different non-stationary settings. But \textsc{\small{ModularPrompt}} is able to achieve state-of-the-art in stage-agnostic and stage-fused settings while remaining comparable to \textsc{\small{PromptTuning}} in stage-specific evaluation.
{Besides, \cite{soft-prompt} showed that the performance gap between \textsc{\small{PromptTuning}} and \textsc{\small{ModelTuning}} will gradually close as the size of backbone PLMs scales up.}
We posit that \textsc{\small{ModularPrompt}}, being an extension of \textsc{\small{PromptTuning}} can similarly benefit from scaling-up of the PLM, but we leave this as future work owing to resource limitations.
\begin{table}[t!]
\centering
\scalebox{0.70}{
\begin{tabular}{llccc}
\toprule
\textbf{Methods} & \textbf{Size} & News & NER & RE \\
\toprule
Finetune$_{\text{multitask}}$ & 770M & 60.6$_{\pm 5.0 }$ & 64.5$_{\pm 0.2 }$ & 87.9$_{\pm 0.6 }$ \\[0.5ex]
\hline
Finetune & 770M & 83.1$_{\pm 0.4 }$ & 77.9$_{\pm 0.4 }$ & 94.5$_{\pm 0.7 }$ \\
Finetune$_{\text{EWC}}$ & 770M & 82.5$_{\pm 0.4 }$ & 77.3$_{\pm 0.4 }$ & 94.5$_{\pm 0.3 }$\\
Finetune$_{\text{MAS}}$ & 770M & 59.7$_{\pm 9.8}$ & 60.4$_{\pm 3.8 }$ & 74.0$_{\pm 6.5 }$ \\
Adapter & 4.8M & 81.4$_{\pm 0.5 }$ & 77.4$_{\pm 0.4 }$ & 94.6$_{\pm 0.5 }$ \\
Adapter$_{\text{EWC}}$ & 4.8M & 81.5$_{\pm 0.4 }$ & 77.3$_{\pm 0.4 }$ & 94.8$_{\pm 0.8 }$ \\
Adapter$_{\text{MAS}}$ & 4.8M & 81.0$_{\pm 0.2 }$ & 77.2$_{\pm 0.5 }$ & 94.9$_{\pm 0.6 }$ \\
PT & 0.13M & 79.7$_{\pm 0.3 }$ & 75.4$_{\pm 0.2 }$ & 94.3$_{\pm 0.9 }$ \\
PT$_{\text{EWC}}$ & 0.13M & 79.9$_{\pm 0.6 }$ & 74.8$_{\pm 0.6}$ & 94.5$_{\pm 0.6 }$ \\
PT$_{\text{MAS}}$ & 0.13M & 49.6$_{\pm 4.8 }$ & 44.4$_{\pm 2.3 }$ & 84.3$_{\pm 3.8 }$ \\[0.5ex]
\hline
ModularPT & 0.13M & 80.4$_{\pm 0.6 }$ & 74.5$_{\pm 0.6 }$ & 93.6$_{\pm 0.4 }$ \\[0.5ex]
\bottomrule
\end{tabular}
}
\caption{\textbf{Stage-specific} performance on News Classification, NER and RE (averaged over stages)}
\label{table:specific:all}
\end{table}
\subsection{Ablation Study} \label{sec:exp:ablation}
We now analyze the contribution of different components of \textsc{\small{ModularPrompt}}\xspace towards its SoTA performance. From the results in Table \ref{table:ablation}, we see that in stage-agnostic setting, both label prompt transfer and subset invariant loss provide a boost, though the role of the former is seemingly more significant. On the contrary, removing subset invariant loss has a more debilitating effect on stage-fused performance. This evinces that subset invariant loss is indeed critical in learning label modular representations. This is essential to the stage-fused evaluation which needs to extract and dynamically re-compose label-specific knowledge.
\begin{table}[t!]
\setlength{\tabcolsep}{2.2pt}
\centering
\scalebox{0.65}{
\begin{tabular}{lccc|ccc}
\Xhline{3\arrayrulewidth}
\multirow{2}{*}{\textbf{Methods}} & \multicolumn{3}{c|}{Stage-agnostic} & \multicolumn{3}{c}{Stage-fused} \\ \cline{2-7}
& News & NER & RE & News & NER & RE \\
\hline
\textsc{\small{ModularPrompt}}\xspace & 43.2$_{\pm 0.6}$ & 44.8$_{\pm 4.9}$ & 61.8$_{\pm 1.8}$ & 74.8$_{\pm 1.7}$ & 61.6$_{\pm 2.2}$ & 82.4$_{\pm 0.8}$ \\
w/o transfer & 35.4$_{\pm 2.7}$ & 43.0$_{\pm 3.6}$ & 54.8$_{\pm 2.7}$ & 64.9$_{\pm 1.7}$ & 57.4$_{\pm 2.3}$ & 77.5$_{\pm 1.2}$ \\
w/o subset-inv & 41.1$_{\pm 2.4}$ & 40.0$_{\pm 4.6}$ & 58.2$_{\pm 2.6}$ & 58.5$_{\pm 3.0}$ & 44.1$_{\pm 2.9}$ & 47.7$_{\pm 4.1}$ \\[0.5ex]
\Xhline{3\arrayrulewidth}
\end{tabular}
}
\caption{\textbf{Ablation study} of \textsc{\small{ModularPrompt}}\xspace: average performance on stage-agnostic and stage-fused settings}
\label{table:ablation}
\end{table}
\begin{table}[t!]
\centering
\scalebox{0.75}{
\begin{tabular}{lccc}
\Xhline{3\arrayrulewidth}
\textbf{Methods} & News & NER & RE\\
\hline
ModularPT & 74.8$_{\pm 1.7 }$ & 61.6$_{\pm 2.2 }$ & 82.4$_{\pm 0.8 }$ \\[0.5ex]
\hline
drop ground-truth label prompt & 1.5$_{\pm 0.5 }$ & 4.1$_{\pm 0.8 }$ & 0.5$_{\pm 0.4 }$ \\
drop one random label prompt & 74.9$_{\pm 1.4 }$ & 61.8$_{\pm 2.1 }$ & 83.2$_{\pm 0.6 }$ \\
permute label prompt order & 72.4$_{\pm 1.3 }$ & 61.5$_{\pm 2.3 }$ & 82.2$_{\pm 0.9 }$ \\[0.5ex]
\Xhline{3\arrayrulewidth}
\end{tabular}
}
\caption{Mean Stage-fused performance for different inference schemes
\label{table:analysis}
\end{table}
\subsection{Quantitative Analysis} \label{sec:exp:quant_analysis}
Apart from achieving SoTA, does \textsc{\small{ModularPrompt}}\xspace possess the desirable characteristics of a modular model? According to Algorithm \ref{alg:cl}, \textsc{\small{ModularPrompt}}\xspace set $S=\SSS^{ts}_{i}$ during inference. We experiment with different strategies of input prompt construction including dropping label prompt(s) either corresponding to ground truth label(s) or one other random label,
and permuting the default order of label prompts; see Table \ref{table:analysis} for the results.
Indeed we observe that dropping the ground truth label prompt during inference degrades the mean performance by 57\%-82\% while dropping any other random label prompt boosts performance slightly. This strongly demonstrates the \emph{label grounding} property of \textsc{\small{ModularPrompt}}\xspace, i.e. the knowledge of a class label is exclusively embedded in its corresponding label prompt. \textsc{\small{ModularPrompt}}\xspace also shows low sensitivity to the order of label prompts during inference - a yet another favourable property of label modular models
\subsection{Qualitative Analysis} \label{sec:exp:qual_analysis}
Revisiting Figure \ref{fig:case_study} presented in \Cref{sec:intro}, we observe that \textsc{\small{ModularPrompt}}\xspace is able to predict correctly on a testing regime that is unseen during training, by extracting and consolidating label specific knowledge from multiple training stages. More example predictions are shown in Figure \ref{fig:case_study_1} (and \cref{appendix:qual}), which indicate that \textsc{\small{ModularPrompt}}\xspace is able to exploit in-context learning over label-prompts to generalize to unseen label-combinations during inference.
For example, \textsc{\small{ModularPrompt}}\xspace tags ``Gilbert'' as politician as he was ``a delegate to'' a government. In the same spirit, \textsc{\small{ModularPrompt}}\xspace wrongly tags ``Bert Bell'' and ``Rozelle'' as athletes (true label being \emph{person\_other}) because they are associated with the sports league ``NFL''. Such qualitative findings demonstrate \textsc{\small{ModularPrompt}}\xspace's capabilities to learn label modular representations and integrate them dynamically during inference.
\begin{figure}[t!]
\centering
\includegraphics[width=0.48\textwidth]{image/case_study_4.png}
\caption{\darkBlue{Successful} (blue) and \red{failure} (red) cases of \textsc{\small{ModularPrompt}}\xspace predictions for stage-fused NER}
\label{fig:case_study_1}
\end{figure}
\section{Introduction} \label{sec:intro}
While NLP research has received a significant boost in performance by employing large-scale pretrained language models (PLMs), finetuning an entire dedicated model for each task is not always practical or even feasible, especially as model size continues to grow. To alleviate this, recently there has been increased interest in parameter-efficient methods such as {Adapter} \cite{adapter} and Prompt-based tuning methods \cite{soft-prompt,Mix_soft_prompts,p_tuning,prefix_tuning}. When training on a downstream task, these methods keep the PLM frozen and only update a small set of parameters that are added to the network. Among these methods, \textsc{\small{PromptTuning}} \cite{soft-prompt} proposes \emph{tunable prompts} -- a sequence of learnable soft tokens, and show impressive results, even competitive to full-model finetuning with a large PLM.
While these prompt-based methods have proven quite effective on popular benchmarks, these standard tasks typically assume only independently and identically distributed (i.i.d) data during training and testing. However, practical cognitive tasks in the real world are usually more complex involving changing contexts or non-stationary environments. Talking about what is next for NLP, Kathleen McKeown in a recent interview (\href{https://www.amazon.science/blog/acl-what-comes-next-for-natural-language-processing}{source}) said:
``Most models are static. But the world changes every minute, every second. Dealing with a dynamic world is a new area that's up and coming.''
\begin{figure}
\centering
\includegraphics[width=0.48\textwidth]{image/case_study.png}
\caption{\small Example of \textsc{\small{ModularPrompt}}\xspace for stage-fused NER. \textbf{Top 2 blocks}: training stages covering disjoint sets of entity types {(e.g., \emph{event, person})}. \textbf{Bottom block}: fused test stage covering entity types of \emph{person} and \emph{organization} from two training stages. \colorbox{lightPink}{Coloured boxes} denote label prompts. \underline{Underlining} and \textit{\darkBlue{italic blue}} denotes named entity and its type.}
\label{fig:case_study}
\end{figure}
Our work in this paper particularly concerns text classification settings where a model is trained on sequence of tasks and evaluated on an arbitrary subset of seen labels of interest.
We formalize this as a novel \textbf{text classification \textit{in-the-wild}} task (defined in \Cref{sec:method}), which emulates the transient learning environment of real world, e.g., for a service requiring classification, the label set might gradually change over time to include new labels or remove obsolete ones. Such scenarios typically result in a sequence of non-stationary low-resource training and evaluations over different label sets (e.g., train on \{\emph{chemistry, physics}\} and \{\emph{basketball, football}\} in succession and then test on \{\emph{physics, football}\}).
This requires handling non-stationary data distribution which humans are quite adept at, partly because we can decompose a complex task in a modular fashion \cite{Berwick}. For example, when learning to classify objects, we acquire modular knowledge exclusive to each class. This allows us to robustly classify irrespective of any label space manipulations such as label omission or learning over new label spaces. This notion of modularity at the level of each class label is what we call \emph{label modularity} and is a desirable quality for NLP models to generalize to practical non-stationary classification settings.
Contemporary modular model designs for complex NLP tasks typically use a routing network or programmer \cite{RecursiveRouting,RoutingNetworks,TextModular,ModularInstruction,ModularMultiHop,ModularNMNtree,StackNMN,TextNMN,NMN} which learns a meaningful decomposition of the task into sub-tasks and executes it by applying a chain of specialised modules designed for each sub-task.
For classification tasks, this can entail learning a specialized module for each label in the target label-space. While there has been limited research on utilizing modular architectures for PLMs \cite{NMN, NeRD}, the main research gap that we explore in this work is that of a modular design of parameter efficient tuning of large PLMs, in particular, \textsc{\small{PromptTuning}}.
Although \textsc{\small{PromptTuning}} can be considered modular at task level in that it learns soft-prompts for each task to support multitasking, it is not able to learn modular decomposition within a particular task. For non-modular designs like \textsc{\small{PromptTuning}} or model-finetuning, text classification \textit{in-the-wild} is challenging to handle, as it requires combining partial information from different label spaces. In contrast, a label-modular approach should learn exclusive knowledge for each label and generalise to any subset of the label set. We thus postulate two main objectives of a label-modular model:
\begin{objective} \label{obj:sl}
\textbf{Separable Label Representation}: Each class label should have its own representation which compactly encodes the information from the data belonging to that label.
\end{objective}
\begin{objective} \label{obj:cl}
\textbf{Prediction over Controllable Label Space}: Models should perform robustly over any subset of the learnt label space during inference.
\end{objective}
%
\noindent To meet these objectives, we propose a modular design of Prompt Tuning -- \textbf{Label-modular Prompt Tuning} (\textsc{\small{ModularPrompt}}\xspace). It decomposes the prompt sequence into label-modular components called \emph{label prompts}, each encoding specific knowledge corresponding to a class label. Thus in each forward pass, we can select desired label prompts to construct the input prompt, based on the target label-set. To ensure that the learned knowledge is encoded in a modular fashion during training, we introduce a novel subset-invariant loss over dynamic label-sets.
To evaluate generalizability of \textsc{\small{ModularPrompt}}\xspace\, we construct some practical scenarios of text classification \textit{in-the-wild}.
We train in multiple stages over non-overlapping label spaces and evaluate the model on label-sets that (i) correspond to each training stage (stage-specific),
(ii) is accumulated over all learned labels (stage-agnostic), and (iii) is comprised of labels across multiple training stages (stage-fused).
We show an example of \textsc{\small{ModularPrompt}}\xspace on stage-fused NER setting in \Cref{fig:case_study}.
The stage-agnostic and stage-fused settings are the most challenging scenarios for typical fine-tuned or prompt-tuned models, and specifically on those settings we find that \textsc{\small{ModularPrompt}}\xspace\ outperforms all relevant baselines
by a significant margin. This alludes towards its ability to learn robust prompt representations that is generalizable to different non-stationary learning environments.
We further empirically justify that \textsc{\small{ModularPrompt}}\xspace\ indeed showcases modular properties by analyzing its behavior when either the ground truth or other random labels are removed from the input or the order of label prompts is permuted.
\begin{comment}
In summary, the contribution of our work is two-fold:\todo{this might be omitted as the intro is already too long}
\begin{itemize}[leftmargin=*]
\setlength\itemsep{0.2em}
\item We propose \textsc{\small{ModularPrompt}}\xspace\ which brings a label-modular design into the space of prompt tuning over large-scale PLMs and we empirically verify that it effectively achieves separable label representation and the ability to predict over controllable label spaces.
\item We propose text classification \textit{in-the-wild}, a commonly observed real-world yet challenging problem to evaluate generalization capability of models in learning with non-stationary data and predicting over controllable label spaces.
\end{itemize}
\end{comment}
\section{Methodology} \label{sec:method}
In this section, we first formally define the problem and subsequently present our \textsc{\small{ModularPrompt}}\xspace model, introduce subset invariant loss and explain the framework under text classification \textit{in-the-wild}.
\begin{figure*}[htbp]
\centering
\vspace{-5pt}
\small
\setlength{\abovecaptionskip}{2pt}
\setlength{\belowcaptionskip}{-10pt}
\includegraphics[width=1.0\textwidth]{image/StPT_main_2.png}
\caption{\textbf{Left}: \textsc{\small{PromptTuning}}, where consecutive soft tokens are concatenated with the input to a frozen PLM. \textbf{Right}: Our proposed \textsc{\small{ModularPrompt}}\xspace, where multiple label prompts are concatenated together with the input to a frozen PLM. Each label prompt consists of a label name and consecutive sequence of soft tokens.}
\label{fig:model}
\end{figure*}
\subsection{Problem Definition}
\paragraph{Single stage text classification} \label{single-domain}
Assume a single text classification domain (or dataset) $\D$. Let $(X, Y) \sim \D$ be a sample, where $X=\{x_t\}_{t=1}^L$ represents a text input sequence of length $L$ and $Y=\{y_t\}_{t=1}^M$ represents the corresponding classification label name of length $M$ (in tokens). Let $\Omega$ denote the set of all possible class labels of interest, for which we have $\forall (X,Y) \sim \D, \text{cls}(Y) \subseteq \Omega$. Note that $\text{cls}(Y)$ is a mapping which returns the class label(s) in $Y$. In case of single class classification, $\text{cls}(Y)$ returns $\{Y\}$. In case of sequence labelling which is token-level classification, $\text{cls}(Y)$ returns the set of all unique target tags in $Y$.
\vspace{-0.5em}
\paragraph{Text classification in-the-wild} \label{in-the-wild}
Assume a sequence of $n$ text classification stages with the corresponding training datasets $\DD^{tr}=\{\D^{tr}_1, ...,\D^{tr}_n\}$.
Each stage represents a different task in temporal dimension, with $(X_k, Y_k) \sim \D^{tr}_k$ denoting a sample at the k-th training stage and $\Omega_k$ denoting the set of all possible class labels for $\D^{tr}_k$. Similarly, the testing could consist of $m$ such datasets $\DD^{ts}=(\D^{ts}_1, ...,\D^{ts}_m)$ with $\Omega^{ts}_{j}$ denoting the set of possible class labels for $\D^{ts}_j$. For classification \textit{in-the-wild}, we examine three challenging yet very practical settings. First, when $m = 1$ and $\Omega^{ts}_{1} = \cup_{k=1}^n\{\Omega^{tr}_k\}$, we have one test dataset covering all seen labels. We refer it as \textbf{stage-agnostic} testing as the test label can come from any of the training stages (or tasks). Second, when $m = n$ and $\Omega^{ts}_{j} = \Omega^{tr}_j, \forall j =\{1,...,n\}$, we have one test dataset corresponding to each training stage with the same label set. We denote this setting as \textbf{stage-specific} testing as each test set evaluates the model's performance on a particular task in which it was trained. Finally, a more challenging setting where $m >1$ and $\Omega^{ts}_{j}\notin \{\Omega^{tr}_1,...,\Omega^{tr}_n\}, \forall j =\{1,...,m\}$, rather $\Omega_j^{ts} \in \mathcal{P}(\cup_{k=1}^n\{\Omega^{tr}_k\}) - \cup_{i=1}^n\{\mathcal{P}(\Omega^{tr}_i)\}$, where $\mathcal{P}(S)$ denotes the power-set of a given set $S$. That is, the label set of a test stage does not correspond to any one training stage, but is composed of partial label sets from multiple training stages (or tasks). We refer it as \textbf{stage-fused} testing. Note that the stage-agnostic and stage-specific scenarios are closely related to \emph{continual learning} \cite{Thrun96}, though the latter considers access to task-id instead of intra-task information (i.e., task label set).
\subsection{Soft Prompt Tuning} \label{soft-prompt}
Let $X = \{x_1, ..., x_L\}$ be an input text sequence, where $x_t$ is the $t$-{th} token, and $M$ be a pretrained language model. The input text is mapped to a sequence of embeddings $H = \{\bm{h}_1, ..., \bm{h}_L\}$ with $\bm{h}_t \in \R^d$. A soft prompt is a sequence of $N$ tunable tokens $\T = \{\bm{p}_1, ..., \bm{p}_N\}$ with $p_i \in \R^d$, that is concatenated with the text embedding as the final input to $M$: $\bar{H} = \{\T \oplus H\}=\{\bm{p}_1, ..., \bm{p}_N, \bm{h}_1, ..., \bm{h}_L\}$. The model prediction is defined as $P(Y|\bar{H};M)=P(Y|\T,X;M)$. During training, $M$ is kept frozen and only $\T$ is updated.
\subsection{Label Modular Prompt Model} \label{sec:mprompt}
We visualise the architecture of \textsc{\small{PromptTuning}} \cite{soft-prompt} and our proposed \textsc{\small{ModularPrompt}}\xspace\ in \Cref{fig:model}. In contrast to \textsc{\small{PromptTuning}}, \textsc{\small{ModularPrompt}}\xspace's prompt consists of a sequence of label prompts, where each label prompt contains the corresponding label name and a sequence of tunable soft tokens similar to soft prompt. Formally, we denote $\bm{l}_{k} = \bm{e_k} \oplus \{\bm{p}^k_1, ..., \bm{p}^k_m\}$ as label prompt for label $k$, where $\bm{e_k}$ is the embedding of label $k$'s text or sequence of token-embeddings for multi-token labels, $\oplus$ denotes concatenation and $m$ is the number of tunable tokens per label prompt. The final input prompt is $\T = \oplus_{k \in S} \bm{l}_{k}$ with $S$ being the set of labels of interest.
\vspace{-0.5em}
\paragraph{Prompt formulation}
The key mechanism of \textsc{\small{ModularPrompt}}\xspace is prompt formulation $\{R, S\} \rightarrow \T$, where $R$ denotes the learned representation space of all labels prompts. In \textsc{\small{PromptTuning}}, variables $S$ and $R$ do not exist and the model training tunes $\T$ directly. In \textsc{\small{ModularPrompt}}\xspace, given $S$ as a set of class labels of interest, we select the corresponding label prompts representation from $R$ and concatenate these to form the final input prompt $\T$.
The training loss is back-propagated through $Y \rightarrow \T \rightarrow R$ to learn the soft label prompts.
\begin{comment}
\paragraph{Causal interpretation}
To clarify the mechanism and motivation behind \textsc{\small{ModularPrompt}}\xspace, we formalise it with a causal graph.
The key variables in the causal graph are: 1) $X$: input text data, 2) $S$: set of class labels to construct input label prompt, 3) $R$: the learned representation space of all labels prompts, 4) $\T$: the input label prompt, 5) $M$: pre-trained LM, and 6) $Y$: class label of text data. The key causal paths of \textsc{\small{ModularPrompt}}\xspace\ are:
\begin{itemize}[leftmargin=*]
\setlength\itemsep{0.2em}
\item \textbf{Prompt formulation~} The path $\{R, S\} \rightarrow \T$ represents the unique process of \textsc{\small{ModularPrompt}}\xspace\ to construct input prompt per data example. In \textsc{\small{PromptTuning}}, variables $S$ and $R$ do not exist and the model training tunes $\T$ directly. In \textsc{\small{ModularPrompt}}\xspace, given $S$ as a set of label classes of interest, we select the corresponding label prompts representation from $R$ and concatenate these label prompts to form the final input prompt $\T$. $\T$ is thus an intermediate variable and the loss back-propagates through $Y \rightarrow \T \rightarrow R$ to learn the representation of the label prompts.
\item \textbf{Model prediction~} The path $\{X,\T,M\} \rightarrow Y$ represents prediction process of any prompt based model. Note that the PLM $M$ (marked in grey) is frozen throughout training and testing.
\end{itemize}
\end{comment}
\paragraph{Subset invariant loss}
The prompt formulation $\{R, S\} \rightarrow \T$ aims to achieve Objective \ref{obj:cl}: prediction over controllable label space (\Cref{sec:intro}). In single domain setting, $\SSS^{tr}$ is the set of all possible class labels during training as defined by Section \ref{single-domain}.
However fixing $S$ to a constant $\SSS^{tr}$ throughout training will make the model susceptible to data discrepancy between train and inference as $\SSS^{ts} \neq \SSS^{tr}$. Thus to ensure Objective \ref{obj:cl}, we propose to vary $S$ during training. We first uniformly sample the size of $S$, $|S|$ from $\{1, \ldots, (|\Omega^{tr}|-1) \}$ and then randomly choose $|S|$ labels from $\Omega^{tr}$ to construct $S$. Such sub-sampling of {$\Omega^{tr}$} encourages a fair exploration of different lengths of prompt sequences as input during training, thus enabling representations to be robust to a dynamic $\Omega^{ts}$ at inference. For each training instance, with probability $p$ we fix $S=\Omega^{tr}$ and vary $S$ as above with $(1-p)$ chance.
\begin{comment}
The resulting probability density function is:
\vspace{-.5em}
\begin{equation} \label{eq:sub_sample}
\begin{split}
P(S) &= \begin{cases}
p ,& \text{if } S = \Omega^{tr} \\
\frac{1}{\binom{|\Omega^{tr}|}{|S|}}\frac{1}{|\Omega^{tr}|-1}(1-p) ,& \text{otherwise}
\end{cases}
\end{split}
\end{equation}
where $\binom{n}{k}$ denotes the binomial coefficient.
\end{comment}
We refer such sampling process as $S \sim \hat{\mS}$.
The subset invariant loss is then defined as:
\begin{equation}\small
\LL^{\text{inv}}_{R} (\D) = \mathbb{E}_{\substack{(X,Y) \sim \D \\ S \sim \hat{\mS}}} \big[ - \mathbbm{1}_{\text{cls}(Y) \subseteq S} \log P(Y|X, R, S; M) \big]
\label{eq:subset_inv}
\end{equation}
where $\mathbbm{1}$ is the Indicator function;
$\mathbbm{1}_{\text{cls}(Y) \subseteq S} = 1$ if $\text{cls}(Y) \subseteq S$, otherwise $0$. According to Objective \ref{obj:sl}, we expect our model to make predictions grounded by the relevant label prompts. When $S$ does not contain ground truth class label(s) in $Y$, the model should not be able to predict $Y$ as output. Thus we set the loss to be zero when $\text{cls}(Y) \nsubseteq S$ to avoid encouraging ungrounded predictions.
\begin{comment}
We refer $\LL^{\text{inv}}_{R}$ as subset invariant loss since we randomly sample subsets of $\SSS^{tr}$ as $S$ during training. In contrast, the vanilla loss $\LL_{R}$ is simply defined with $S=\SSS^{tr}$ constantly as:
\begin{equation}\small
\begin{split}
\LL_{R} (\D) &= \mathbb{E}_{(X,Y) \sim \D} - \log P(Y|X, R, \SSS^{tr}; M)\\
\end{split} \label{eq:vanilla}
\end{equation}
\end{comment}
\begin{comment}
the log-probability is multiplicatively combined with the weight term $\lambda_{S, Y}$, defined as:
\[
\lambda_{S, Y} =
\begin{cases}
1 ,& \text{if } Y \in S \\
0 ,& \text{otherwise}
\end{cases}
\]
\end{comment}
\subsection{\hspace{-0.5em} Classification \textit{in-the-wild} with \textsc{\small{ModularPrompt}}\xspace } \label{sec:mprompt_in_the_wild}
So far, we have introduced \textsc{\small{ModularPrompt}}\xspace\'s functionality under a single domain classification setting. To verify our Objective \ref{obj:cl}, we wish to examine it under text classification \textit{in-the-wild} defined in \Cref{in-the-wild}. Given training datasets $\DD^{tr} = \{\D^{tr}_1, ..., \D^{tr}_n\}$, the model is trained on each dataset $\D^{tr}_i$ sequentially, and then evaluated on three classification \textit{in-the-wild} testing settings. The pseudocode of \textsc{\small{ModularPrompt}}\xspace\ under the continual learning setting is given in \Cref{alg:cl}. Note that $R_{\SSS^{tr}_{i}}$ in step 3 denotes label prompt representation of labels in $\SSS^{tr}_{i}$, i.e., $R_{\SSS^{tr}_{i}} \coloneqq \{\bm{l}_k \in R | k \in \SSS^{tr}_{i}\}$
and $R_{\SSS^{tr}_{<i}}$ is similarly defined as $R_{\SSS^{tr}_{<i}} \coloneqq \{\bm{l}_m \in R | m \in \underset{t<i}{\cup} \SSS^{tr}_t\}$.
\begin{algorithm}[t]
\caption{Text Classification \textit{in-the-wild} with \textsc{\small{ModularPrompt}}\xspace.}\label{alg:cl}
\small
\begin{algorithmic}[1]
\Require Training datasets $\DD^{tr} = \{\D^{tr}_1, ..., \D^{tr}_n\}$, testing datasets $\DD^{ts}=(\D^{ts}_1, ...,\D^{ts}_m)$, pretrained language model $M$
\For{ $\D^{tr}_i$ in $\DD^{tr}$} \Comment{Training}
\State $\SSS^{tr} \leftarrow \SSS^{tr}_{i}$
\State INITIALIZE $R_{\SSS^{tr}_{i}}$ from
$R_{\SSS^{tr}_{<i}}$ \Comment{Transfer}
\For{$step = 1,..., iter$}
\State UPDATE $R_{\SSS^{tr}_{i}}$ with SGD on $\LL^{\text{inv}}_R (\D^{tr}_i)$
\EndFor
\EndFor
\For{ $\D^{ts}_i$ in $\DD^{ts}$} \Comment{Testing}
\State EVALUATE $P(\cdot|X, S=\SSS^{ts}_{i},R; M)$ on $X \sim \D^{ts}_i$
\EndFor
\end{algorithmic}
\end{algorithm}
\paragraph{Label prompt transfer}
In step 3, for learning the label prompt representation $R_{\SSS^{tr}_i}$ at any training stage $i$, we first aim to transfer the label-modular knowledge, $R_{\SSS^{tr}_{<i}}$ learned over the previous training stages through prompt initialization. This is a unique learning characteristic that is facilitated by our label-modular architecture and allows the model to exploit semantic relatedness between labels across training stages when initializing the label prompt representation. Intuitively, if `bistro' $\in \SSS^{tr}_{<i}$ and `restaurant' $\in \SSS^{tr}_i$, then initializing the label prompt representation of `restaurant' with the knowledge encoded in the learned label prompt representation of `bistro' should be helpful to the model. To compute the similarity between labels $\bm{l}_j$ and $\bm{l}_k$ with $j \in \SSS^{tr}_i$ and $k \in \SSS^{tr}_{<i}$, we use per-token average cosine similarity $sim(\bm{e}_{j}, \bm{e}_{k})$ based on the embeddings of the label texts. For each label $j \in \SSS^{tr}_{i}$, we select the top-$K$ most similar labels $\SSS^{tr}_{\text{top-}K{(j)}} \subset \SSS^{tr}_{<i}$. We then initialize $\bm{l}_j$ by averaging the top-$K$ similar label prompt representations, weighted by their normalized similarity score: $\bm{l}_j \leftarrow \sum_{k \in \SSS^{tr}_{\text{top-}K{(j)}}} \alpha_{k} \bm{l}_k $, where $\alpha_{k} = {sim(\bm{e}_{j}, \bm{e}_{k})} / {\sum_{m \in \SSS^{tr}_{\text{top-}K{(j)}}} sim(\bm{e}_{j}, \bm{e}_{m})}$. This method is similar in spirit to \cite{SPoT}, which shows good transfer for task level prompts with training overheads, while we transfer at a finer-grained level over label prompts with no overheads.
\section{Related Work}
We now review methods from the literature that are relevant to ours from different perspectives.
First, many parameter efficient tuning methods have been proposed such as Adapter \cite{adapter}, \textsc{\small{PromptTuning}} \cite{soft-prompt}, \textsc{\small{PrefixTuning}} \cite{prefix_tuning}, BitFit \cite{bitfit}, LoRA \cite{lora} and COMPACTER \cite{compacter}. They either finetune a parameter subset or introduce new layers or embeddings.
Transfer learning over prompts \cite{SPoT} and Adapters \cite{adapterFusion} and multi-tasking over the latter \cite{hyperadapter} have also been explored, but they are not comparable to ours due to difference in task/problem settings.
Second, continual learning (CL) methods are relevant as they also have sequential training stages. Architecture based CL methods adjust model architecture for each task \cite{Net2Net,progressiveNN,piggyback}, but require task identities for inference. Regularization based CL methods restrain updating parameters critical to previous tasks \cite{EWC,synapticCL,MAS}. Memory based CL methods retain key examples from prior tasks \cite{GEM, AGEM, episodic_memoty, continualPT} while Memory generator models learn to generate and use pseudo-data from prior tasks \cite{LAMOL,lfpt5}.
These methods are not comparable to ours as we do not use any memory or pseudo memory in our sequential training
Third, modular networks have been shown to perform well on out-of-domain data \cite{ModularNetworks,LatentMTAL,ModularMeta} and mitigate forgetting in continual learning \cite{ModularCL}. Apart from routing network approaches introduced in \Cref{sec:intro}, mixture-of-experts (MoE) selects a soft subset of modules based on model input \cite{SparseMoE,SwitchTransformers,RIM}. Similar to ours, \citet{{TaskMoE,AttentiveTransfer,FactorZeroShot,ModularCL}} consider task level routing and support new tasks by combining learned modules. By contrast, \textsc{\small{ModularPrompt}}\xspace utilises parameter efficient finetuning of large PLMs and support low resource settings. | {'timestamp': '2022-12-01T02:18:55', 'yymm': '2211', 'arxiv_id': '2211.17142', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17142'} | arxiv |
\section{Additional Qualitative Examples}
This section includes some additional qualitative examples that were not included in the main paper for lack of space. Figure \ref{fig:nyu_qualitative_1} contains examples from the NYUv2 test split, and figure \ref{fig:kitti_qualitative_1} contains examples from the KITTI test split.
\begin{figure*}
\centering
\includegraphics[width=\textwidth]{figures/nyu_objcavit_comparison.png}
\caption{Qualitative results from running inference on the NYUv2 test set. Test-time augmentation is not used here, but is used for computations of the metrics reported in the paper (as is standard in the existing literature \cite{bhat_adabins_2020, lee_big_2019}). ``Pred (Baseline)" results were produced by the reimplemented AdaBins (denoted as ``AdaBins (reimpl.)" in the main paper. ``Pred (Ours)" results were produced by our best model, which used a positional encoder with both position and object bounding box dimensions provided as input (\textit{pos+bbox wh}) and used only the WordNet definition as the language input for detected objects (\textit{def.}).}
\label{fig:nyu_qualitative_1}
\end{figure*}
\begin{figure*}
\centering
\includegraphics[width=\textwidth]{figures/kitti_objcavit_comparison.png}
\caption{Qualitative results from running inference on the KITTI test set. Object detections are not shown to allow predictions to be shown larger. Inference settings and models used are as described in the caption of figure \ref{fig:nyu_qualitative_1}.}
\label{fig:kitti_qualitative_1}
\end{figure*}
\section{Introduction}
\label{sec:introduction}
\begin{figure}[h]
\centering
\includegraphics[width=\linewidth]{figures/eg_output.png}
\caption{Example inputs, ground-truth depth maps, and predicted depth outputs from our best model running on the NYUv2 dataset, including the YOLOv7 detections that we use as auxiliary information to improve performance. By using object semantics and modelling the relationships \textit{between} objects, our model is able to improve depth estimation performance.}
\label{fig:eg_output}
\end{figure}
Monocular depth estimation (MDE) is an important problem in the field of computer vision, but is fundamentally ill-posed: a 2D image may have been taken from a number of 3D scenes. Because of this ambiguity, all MDE systems must inherently make assumptions about the world, aiming to estimate the most likely depth values, given the set of assumptions that they hold, from the input image. In the biological domain, many of these assumptions about the input and the world have been identified, and are known as depth ``cues". These cues range from the obvious, for example the effect of perspective on the apparent size of an object, to the more implicit or reasoning-based, such as the inference of the likely true size of an unknown object based on the semantic relationship it appears to have with the objects in its vicinity.
Many works in the literature have tackled the problem of MDE with good results, but almost all assume that the information required to make assumptions about scene geometry will be learned implicitly. Because the poorly-posed nature of the problem demands that assumptions of some description be made to resolve ambiguity, the implication is that any MDE system must be expending effort on working out an appropriate set of assumptions before it can begin to detect those assumptions in an input image and learn appropriate mappings from them to the likely output depth values. This presents an obvious inefficiency, wasting limited model capacity and training data on learning the \textit{existence} of relevant assumptions, rather than how to \textit{exploit} them for the end problem. Being able to incorporate prior information that is known already to be useful for MDE to an MDE model would therefore be expected to produce a boost in performance as the model no longer has to expend capacity learning these cues, provided that the assumptions that the model is guided towards by design are at least as useful as those it may learn on its own.
The mechanism of cross-attention has been used to great effect to enhance performance in other tasks, but has not (to the best of our knowledge) been exploited to introduce non-image features for MDE. It provides a means to modify one set of features based on another set of features, for instance fine-grained image features based on coarse-grained image features \cite{chen_crossvit_2021}, or images of text with actual text \cite{li_selfdoc_2021}. In the motivation for our work, we consider the role that inter-object relationships may play in improving the way in which image features are represented for the task of MDE.
Modifying image features based on object and inter-object-relationship semantics fits perfectly with the purpose and intuition behind cross-attention. The ambiguity of the MDE problem requires layers of interpretation to resolve: first interpreting form and semantic meaning from objects in a scene, then comparing them to previous understanding of their likely shapes, sizes, and co-occurrences, and finally relating them to the image in which they are observed to give further context on their likely position in the scene. This interpretation of the semantics and the relationships between objects, their known sizes, their apparent sizes, and relationships to each other, has been shown to be present in animal vision systems \cite{sousa_judging_2011, hershenson_pictorial_1998} and, to an extent, in machine vision systems \cite{auty_monocular_2022}. Our work makes use of the cross-attention mechanism to allow the model to learn these known-useful relationships.
In this work, we introduce a novel method to \textit{explicitly} leverage known-useful information about the world for the problem of MDE. In particular, we introduce a language and transformer attention mechanism by which the model is encouraged to focus on not only the visual features of an image, but the semantics of the objects contained within it.
Our main contributions are:
\begin{enumerate}
\item We introduce a novel method of incorporating auxiliary object detection information to an MDE pipeline with our \textbf{Object Cross-Attention Vision Transformer (ObjCAViT block)}, which allows the model to learn about both the semantic roles of an object in the world and the relationships between those objects that appear in an input scene,
\item We demonstrate the novel use of joint size-and-position embeddings for object and image patch self-attention with transformers, showing an improvement in depth inference by making use of apparent object sizes,
\item Our method is able to exploit auxiliary information from frozen off-the-shelf language models and object detectors to improve depth estimation,
\item We demonstrate clear improvement in performance over the baseline on both the indoor and outdoor domains using the NYUv2 and KITTI datasets respectively.
\end{enumerate}
\section{Experiments}
\label{sec:experiments}
In this section, we detail our experiments. In section \ref{sec:setup}, we describe our baseline, datasets, hyperparameters and training procedures, and evaluation metrics. In section \ref{sec:results}, we present our results, and include ablation studies to demonstrate the effectiveness of our use of language embeddings, our use of self-attention between object features to allow the model to learn the relationships between the different objects detected in the scene, and finally to prove the efficacy of our positional embedding strategy. We show qualitative results on KITTI from our best model in figure \ref{fig:pred1-kitti}, and from NYUv2 in figure \ref{fig:eg_output}.
\subsection{Experimental Setup}
\label{sec:setup}
\subsubsection{Baseline}
\label{sec:baseline}
Our baseline architecture mirrors that of AdaBins, with identical image extractors and treatment of image patch features, but without any object detections, language embeddings, object features/self-attention, or cross-attention between image patch and object features. We report baseline results using our own reimplementation of AdaBins for consistency. Our method may be considered an extension of AdaBins, and our experiments will show the effect of progressively adding each part of our method.
\subsubsection{Datasets}
\label{sec:datasets}
Our experiments are performed on two datasets, to show applicability across domains: NYUv2 \cite{silberman_indoor_2012} for indoor and KITTI \cite{geiger_vision_2013} for outdoor. We use the same split of these datasets as used in \cite{bhat_adabins_2020}, and we use the same training and testing crops and augmentations as that work also. Our model outputs images at half-resolution relative to the input image dimensions; we therefore perform bilinear upsampling back to the input resolution as a final step after output.
\textbf{NYUv2} is an indoor dataset across a variety of different indoor scenes, with (mostly) dense depth ground-truth captured with a Microsoft Kinect. We use 24231 training examples and the official test split of 654 examples. We train on random crops of size $[416\times544]$, and evaluate on the Eigen crop \cite{eigen_depth_2014}. The input images at test time have dimensions $[480\times640]$. When evaluating, we follow convention \cite{bhat_adabins_2020, lee_big_2019}: we take predictions from each input image and its mirror. We then re-mirror the mirror prediction and average it with the non-mirrored prediction to give the final result.
\textbf{KITTI} is an outdoor driving dataset with sparse depth ground-truth captured using LiDAR. We use 23157 training and 696 test examples. Following \cite{bhat_adabins_2020}, during training we take a random crop of size $[352\times704]$, and during evaluation we follow the cropping strategy from \cite{garg_unsupervised_2016}. We perform the same mirror-image prediction and averaging for KITTI as we do for NYUv2.
\subsubsection{Training Procedure}
We implement all our experiments using PyTorch. All results are reported after 25 epochs of training on two GPUs with 24Gb+ of VRAM (either 2x Quadro RTX6000s or 1x RTX A5000 + 1x RTX A6000, all by NVIDIA), using a batch size of 8. Following the procedure detailed in \cite{bhat_adabins_2020}, we use the AdamW optimizer with a learning rate of 0.000357 and a OneCycleLR learning rate scheduler, with max\_lr=0.000357, cycle\_momentum=True, base\_momentum=0.85, max\_momentum=0.95, div\_factor=25, and final\_div\_factor=100.
\subsubsection{Evaluation Metrics}
\label{sec:metrics}
The metrics used for evaluation are those defined by \cite{eigen_depth_2014}: Abs relative difference (Abs or Abs Rel): $\frac{1}{T}\sum_{i=1}^{T} \frac{|d_i - d_i^*|}{d_i^*}$, Squared relative difference (Sq or Sq Rel): $\frac{1}{T}\sum_{i=1}^{T} \frac{\|d_i - d_i^*\|}{d_i^*}$, lin. RMSE (RMS): $\sqrt{\frac{1}{T}\sum_{i=0}^{T}\|d_i - d_i^*\|^2}$, log RMSE (RMSL): $\sqrt{\frac{1}{T}\sum_{i=0}^{T}\|log(d_i) - log(d_i^*)\|^2}$, and the threshold accuracy $\delta_n$: \(\%\) of \(d_i\) s.t. $max(\frac{d_i}{d_i^*}, \frac{d_i^*}{d_i}) = \delta < thr$, where $\delta_n$ denotes that $thr = 1.25^n$ (we use $n \in \{1, 2, 3\}$).
We follow the accepted convention in other works \cite{bhat_adabins_2020, lee_big_2019} of computing a running average of each of these metrics. We run inference on a single GPU one example at a time from the evaluation split. Each metric has a running average accumulator $ave_n$, where $n$ is the number of examples seen thus far. We run inference for image $n$ and compute a metric $val_n$. We then update $ave$ according to $ave_{n+1} = \frac{(ave_n \times n) + val_n }{n+1}$.
\subsection{Results}
\label{sec:results}
\begin{table*}[h!]
\centering
\resizebox{0.925\textwidth}{!}{%
\begin{tabular}{c|ll|ccccc|ccc}
\multicolumn{1}{l|}{Dataset} & Model & Pos. embedding & $\downarrow$ Abs. Rel & $\downarrow$ Sq. Rel & $\downarrow$ RMS & $\downarrow$ RMSL & $\downarrow$ Log10 & $\delta ^1$ & $\delta ^2$ & $\delta ^3$ \\ \hline
\multirow{4}{*}{\textbf{NYUv2}} & \textit{Baseline (AdaBins reimpl.)} & & 0.123 & 0.077 & 0.428 & 0.028 & 0.052 & 0.858 & 0.978 & 0.995 \\
& \textit{Ours (ctrl. zeros)} & pos+bbox\_wh & 0.104 & 0.058 & \textbf{0.367} & \textbf{0.021} & \textbf{0.044} & 0.898 & \textbf{0.985} & \textbf{0.997} \\
& \textit{Ours (def. $+$ sz\_rel)} & pos+bbox\_wh & 0.104 & 0.059 & 0.373 & 0.022 & \textbf{0.044} & 0.898 & 0.984 & \textbf{0.997} \\
& \textit{Ours (def. only)} & pos+bbox\_wh & \textbf{0.103} & \textbf{0.056} & 0.368 & \textbf{0.021} & \textbf{0.044} & \textbf{0.902} & \textbf{0.985} & \textbf{0.997} \\ \hline
\multirow{4}{*}{\textbf{KITTI}} & \textit{Baseline (AdaBins reimpl.)} & & \textbf{0.058} & 0.192 & 2.355 & 0.009 & \textbf{0.025} & 0.965 & 0.995 & \textbf{0.999} \\
& \textit{Ours (ctrl. zeros)} & pos+bbox\_wh & 0.059 & 0.200 & 2.397 & 0.009 & 0.026 & 0.962 & 0.994 & \textbf{0.999} \\
& \textit{Ours (def. $+$ sz\_rel)} & pos+bbox\_wh & \textbf{0.058} & 0.188 & 2.304 & 0.009 & \textbf{0.025} & 0.965 & 0.995 & \textbf{0.999} \\
& \textit{Ours (def. only)} & pos+bbox\_wh & \textbf{0.058} & \textbf{0.183} & \textbf{2.286} & \textbf{0.008} & \textbf{0.025} & \textbf{0.966} & \textbf{0.996} & \textbf{0.999} \\
\end{tabular}%
}
\caption{\textbf{Ablation results across different language embedding strategies}. All experiments in this table use the ``pos$+$bbox\_wh" positional embedding, which is a simple MLP that accepts the bounding box centre coordinates, width, and height as inputs. \textit{Ctrl. zeros} is a control experiment that replaces each object's features with zeros, \textit{def. only} uses just the synset definition for that object's label, and \textit{def $+$ sz\_rel} additionally includes a relative size clause (see section \ref{sec:object-encoder} for details).}
\label{tab:language-ablation}
\end{table*}
\subsubsection{Language Embedding Ablation}
\label{sec:language-ablation}
To show the effectiveness of using language embeddings as a means of incorporating useful information to the model, we perform an ablation study across two different constructions of the phrasing passed to the language embedding module, which form the features used for the detected objects. The results are shown in table \ref{tab:language-ablation}.
All results beat the baseline method, and the ablation shows a clear improvement in performance when using the definition of an object label only. Surprisingly, the use of a more detailed phrase containing the relative size clause is not successful in improving performance significantly compared to the control experiment. We hypothesise that this may be due to CLIP not having encountered such comparative phrases in its training dataset of image captions, and that image captions that directly relate the apparent size of objects specifically are rare. Instead, our results show that CLIP is better suited to the task of providing world knowledge about objects rather than understanding of the specific relationships between them, with the latter being better captured by the inclusion of object self-attention within our ObjCAViT block (see section \ref{sec:obj-sa-ablation}).
\subsubsection{Positional Embedding Ablation}
\label{sec:positional-embedding-ablation}
As outlined in section \ref{sec:background}, research into monocular depth perception in the biological domain has shown a variety of different depth cues that are known to be helpful. In particular, the relative and familiar size cues, which compare the apparent sizes of objects to either a prior model of the object's true size or the apparent size of other objects in the scene, provide useful information, and have been directly leveraged for computer monocular depth estimation \cite{auty_monocular_2022}.
To permit the model to make use of these cues, we alter our positional embedding model. Following \cite{sarlin_superglue_2020}, we use a simple MLP to transform 2-dimensional x/y bounding box centre coordinates to 128-dimensional positional embeddings, that get added to the object or patch embeddings. We then extend this to include apparent size information by providing the bounding box width and height to the positional encoder as a further two channels alongside the centre coordinates.
\begin{table*}[]
\centering
\resizebox{0.925\textwidth}{!}{%
\begin{tabular}{c|ll|ccccc|ccc}
\multicolumn{1}{l|}{Dataset} & Lang. & Pos. emb. & $\downarrow$ Abs. Rel & $\downarrow$ Sq. Rel & $\downarrow$ RMS & $\downarrow$ RMSL & $\downarrow$ Log10 & $\delta ^1$ & $\delta ^2$ & $\delta ^3$ \\ \hline
\multirow{5}{*}{\textbf{NYUv2}} & \multicolumn{2}{c|}{\textit{Baseline (AdaBins Reimpl.)}} & 0.123 & 0.077 & 0.428 & 0.028 & 0.052 & 0.858 & 0.978 & 0.995 \\ \cdashline{2-11}
& def. & pos & 0.105 & 0.059 & 0.370 & \textbf{0.021} & \textbf{0.044} & 0.900 & \textbf{0.986} & 0.996 \\
& def. & pos+bbox\_wh & \textbf{0.103} & \textbf{0.056} & \textbf{0.368} & \textbf{0.021} & \textbf{0.044} & \textbf{0.902} & 0.985 & \textbf{0.997} \\ \cdashline{2-11}
& def.+sz & pos & 0.105 & \textbf{0.059} & \textbf{0.371} & \textbf{0.022} & \textbf{0.044} & 0.897 & \textbf{0.984} & 0.996 \\
& def.+sz & pos+bbox\_wh & \textbf{0.104} & \textbf{0.059} & 0.373 & \textbf{0.022} & \textbf{0.044} & \textbf{0.898} & \textbf{0.984} & \textbf{0.997} \\ \hline
\multirow{5}{*}{\textbf{KITTI}} & \multicolumn{2}{c|}{\textit{Baseline (AdaBins Reimpl.)}} & 0.058 & 0.192 & 2.355 & 0.009 & 0.025 & 0.965 & 0.995 & 0.999 \\ \cdashline{2-11}
& def. & pos & 0.060 & 0.197 & 2.443 & 0.010 & 0.026 & 0.960 & 0.994 & \textbf{0.999} \\
& def. & pos+bbox\_wh & \textbf{0.058} & \textbf{0.183} & \textbf{2.286} & \textbf{0.008} & \textbf{0.025} & \textbf{0.966} & \textbf{0.996} & \textbf{0.999} \\ \cdashline{2-11}
& def.+sz & pos & \textbf{0.057} & 0.190 & 2.357 & \textbf{0.009} & \textbf{0.025} & 0.964 & \textbf{0.995} & \textbf{0.999} \\
& def.+sz & pos+bbox\_wh & 0.058 & \textbf{0.188} & \textbf{2.304} & \textbf{0.009} & \textbf{0.025} & \textbf{0.965} & \textbf{0.995} & \textbf{0.999}
\end{tabular}%
}
\caption{\textbf{Ablation study} for \textbf{different positional embedding methods}. We find that the inclusion of size information as an input to the positional embedding model (``pos+bbox\_wh") is an important factor in improving performance, in comparison to the position-only positional embeddings (``pos"). Best results of the positional embedding strategies tried for each language embedding and dataset used are highlighted in bold.}
\label{tab:positional-ablation}
\end{table*}
The results of this ablation can be seen in table \ref{tab:positional-ablation}. We find that for most metrics, the inclusion of object size as an input to the positional embedding MLP (``pos+bbox\_wh") improves performance, in both the indoor and outdoor domains (NYUv2 and KITTI respectively). This is particularly significant when using only the definition of the object as the input to the language model, and not the relative size clause. As shown in section \ref{sec:language-ablation}, the use of the relative size clause is too complex for the language model to represent, and it confounds performance.
Additionally, the addition of the bounding box dimensions has an increased effect in the KITTI benchmark. We hypothesise that this is due to the subject matter and depth range captured in KITTI: perspective, and the resultant changes in apparent size, are much more noticeable over KITTI's larger depth range of $0.001m - 80m$, compared to NYUv2's range of $0.001m-10m$.
\subsubsection{Object Self-Attention ablation}
\label{sec:obj-sa-ablation}
A large part of our motivation is the idea that the semantic relationships between objects are relevant to depth. As discussed in section \ref{sec:language-ablation}, we hypothesise that the CLIP language model is not able to adequately capture the relationships between specific objects in a scene, leaving that task instead to the self-attention between objects.
Table \ref{tab:obj-sa-ablation} shows results both with and without the use of object self-attention within the ObjCAViT module.
When self-attention is not used, the input features and their positional embeddings are simply forwarded to the cross-attention layer.
\begin{table}[]
\resizebox{\linewidth}{!}{%
\begin{tabular}{lll|ccc|ccc}
Pos. emb. & Lang. & SA? & $\downarrow$ Abs. Rel & $\downarrow$ RMS & $\downarrow$ Log10 & $\delta ^1$ & $\delta ^2$ & $\delta ^3$ \\ \hline
\multicolumn{3}{l|}{\textit{Baseline (AdaBins Reimpl.)}} & 0.123 & 0.428 & 0.052 & 0.858 & 0.978 & 0.995 \\ \hline
\multirow{2}{*}{pos} & \multirow{2}{*}{def.} & Y & \textbf{0.105} & 0.370 & \textbf{0.044} & \textbf{0.900} & \textbf{0.986} & 0.996 \\
& & N & \textbf{0.105} & \textbf{0.368} & \textbf{0.044} & 0.899 & 0.985 & \textbf{0.997} \\ \hline
\multirow{2}{*}{pos} & \multirow{2}{*}{def.+sz} & Y & \textbf{0.105} & 0.371 & \textbf{0.044} & 0.897 & 0.984 & \textbf{0.996} \\
& & N & \textbf{0.105} & \textbf{0.367} & \textbf{0.044} & \textbf{0.900} & \textbf{0.985} & \textbf{0.996} \\ \hline
\multirow{2}{*}{pos+bbox\_wh} & \multirow{2}{*}{def.} & Y & \textbf{0.103} & \textbf{0.368} & \textbf{0.044} & \textbf{0.902} & \textbf{0.985} & \textbf{0.997} \\
& & N & 0.106 & 0.371 & 0.045 & 0.899 & \textbf{0.985} & \textbf{0.997} \\ \hline
\multirow{2}{*}{pos+bbox\_wh} & \multirow{2}{*}{def.+sz} & Y & \textbf{0.104} & 0.373 & \textbf{0.044} & \textbf{0.898} & 0.984 & \textbf{0.997} \\
& & N & 0.106 & \textbf{0.368} & \textbf{0.044} & \textbf{0.898} & \textbf{0.986} & \textbf{0.997}
\end{tabular}%
}
\caption{\textbf{Object self-attention ablation} on \textbf{NYUv2} with each of the different positional embeddings and language phrasings tried, showing results both with and without object self-attention (``SA?"). Notable is that the difference is only significant for \textbf{one configuration} of model: using both position and size in computing positional embeddings, and using only definitions for phrases. We discuss this more in section \ref{sec:obj-sa-ablation}.}
\label{tab:obj-sa-ablation}
\end{table}
Our results show that the difference with and without the use of the object self-attention is only significant when the correct language and positional model is used: using the combined location + bounding box dimension input for the positional encoder, and using only the definition (without relative size clause) for the input to the language model for a given object. As shown in section \ref{sec:language-ablation}, CLIP hurts performance if used to relate multiple objects together. When using only the position of the object bounding box as the input to the positional encoder, we observe that there is little to no difference when adding the object self-attention, (see sec. \ref{sec:positional-embedding-ablation}). This implies that the relationships modelled by the self-attention depend significantly on the apparent size as well as the position of an object in a scene, mirroring the observations of MDE in the biological domain (see section \ref{sec:background}).
\subsubsection{Comparison to SOTA}
\label{sec:sota-comparison}
We provide a comparison with SOTA methods on NYUv2 in table \ref{tab:sota-nyu}. We observe that our performance matches or exceeds previous methods that use standard convolutional backbones, including our re-implementation of AdaBins that uses the same batch size as our method. We also note that our $\sim 30M$ param EfficientNet-B5 \cite{tan_efficientnet_2019} backbone is considerably smaller than the $197M$ to $220M$ or more params of the BinsFormer \cite{li_binsformer_2022}, PixelFormer \cite{agarwal_attention_2022} and DepthFormer \cite{li_depthformer_2022} backbones, and that our method is more modular and may therefore be easily applied to any dense feature extractor.
\begin{table}[]
\resizebox{\linewidth}{!}{%
\begin{tabular}{l|ccc|ccc}
Model & $\downarrow$ Abs. Rel & $\downarrow$ RMS & $\downarrow$ Log10 & $\delta ^1$ & $\delta ^2$ & $\delta ^3$ \\ \hline
Eigen et al. \cite{eigen_depth_2014} & 0.158 & 0.641 & - & 0.769 & 0.950 & 0.988 \\
Laina et al. \cite{laina_deeper_2016} & 0.127 & 0.573 & 0.055 & 0.811 & 0.953 & 0.988 \\
DORN \cite{fu_deep_2018} & 0.115 & 0.509 & 0.051 & 0.828 & 0.965 & 0.992 \\
BTS \cite{lee_big_2019} & 0.110 & 0.392 & 0.047 & 0.885 & 0.978 & 0.994 \\
AdaBins (reported, bs=16) & 0.103 & 0.364 & 0.044 & 0.903 & 0.984 & {\ul 0.997} \\
AdaBins (reimpl., bs=8) & 0.123 & 0.428 & 0.052 & 0.858 & 0.978 & 0.995 \\
DepthFormer \cite{li_depthformer_2022} & 0.096 & 0.339 & 0.041 & 0.921 & {\ul 0.989} & \textbf{0.998} \\
BinsFormer (Sw-L) \cite{li_binsformer_2022} & {\ul 0.094} & {\ul 0.330} & {\ul 0.040} & {\ul 0.925} & {\ul 0.989} & {\ul 0.997} \\
PixelFormer \cite{agarwal_attention_2022} & \textbf{0.090} & \textbf{0.322} & \textbf{0.039} & \textbf{0.929} & \textbf{0.991} & \textbf{0.998} \\ \hline
\textbf{Ours (def, pos+bbox\_wh)} & 0.103 & 0.368 & 0.044 & 0.902 & 0.985 & {\ul 0.997}
\end{tabular}%
}
\caption{Comparison of our method to SOTA methods from the literature on NYUv2, best and 2nd-best results in bold and underlined respectively. We note that our performance exceeds our reimplementation of AdaBins that was retrained with the same batch size as our method, and gives competitive results with other methods in the literature that use considerably larger backbones than ours. Numbers are sourced from the respective source papers.}
\label{tab:sota-nyu}
\end{table}
\section{Conclusion \& Future Work}
\label{sec:conclusion}
In this work, we have introduced ObjCAViT, a novel method for improving monocular depth estimation by using auxiliary information provided by frozen off-the-shelf object detection and language models. We compel the network to pay attention to objects in a scene, sourcing assumptions about the nature of the objects from general-purpose language models and then using self-attention to learn to model the relationships of those objects to one another. Our ObjCAViT block permits the model to relate the object and inter-object semantics to the visual features in the image, and we achieve excellent results that exceed our baseline and are competitive with models much larger than ours. We also find that incorporating the apparent size of objects to their feature representation contributes significantly to the improvement. Our ablation studies confirm that each component of our final model contributes to the performance, though we acknowledge the limitations of enforcing a specific bias on the model and of relying on the accuracy of an off-the-shelf model to provide object information that is assumed to be reliable.
Our future work will aim to alter the architecture of the backbone used to extract the dense image features. Very recent work \cite{agarwal_attention_2022} has begun to use all-transformer architectures for visual feature extraction; we expect that combining object and visual features at multiple stages of the image encoding process will allow the extraction of more depth-relevant image features, which will in turn lead to further increases in performance. While the CLIP model used in our work is general-purpose, we hypothesise that the use of language models trained for reasoning-like tasks will further improve performance.
\section{Positional Encoder Architecture}
\label{app:positional-architecture}
The positional encoders used are simple MLPs with LeakyReLU activations. The position-only positional encoder (``pos") is adapted from the positional encoder used in SuperGlue \cite{sarlin_superglue_2020}, and has the following structure (using PyTorch notation):
\begin{verbatim}
nn.Sequential(
nn.Linear(2, 32, bias=True),
nn.LeakyReLU(),
nn.Linear(32, 64, bias=True),
nn.LeakyReLU(),
nn.Linear(64, 128, bias=True),
nn.LeakyReLU(),
nn.Linear(128, 256, bias=True),
nn.LeakyReLU(),
nn.Linear(256, 128, bias=True)
)
\end{verbatim}
The joint position-and-apparent size positional encoder (``pos+bbox\_wh") additionally accepts the width and height, in pixels, of the object bounding boxes. It has the following structure:
\begin{verbatim}
nn.Sequential(
nn.Linear(4, 32, bias=True),
nn.LeakyReLU(),
nn.Linear(32, 64, bias=True),
nn.LeakyReLU(),
nn.Linear(64, 128, bias=True),
nn.LeakyReLU(),
nn.Linear(128, 256, bias=True),
nn.LeakyReLU(),
nn.Linear(256, 128, bias=True)
)
\end{verbatim}
\section{Method}
\label{sec:method}
In this section, we describe our method in detail. We begin by motivating the approach taken, then describe the architecture and novel ObjCAViT block used.
The primary motivation of our method is the known relevance, at least in animal vision systems, of \textbf{object semantics} and \textbf{inter-object relations} to the problem of monocular depth estimation (MDE) as clues for depth prediction disambiguation. Without sufficient information to create a one-to-one mapping between observations and 3D scene geometry,
the input image's contents must be interpreted semantically by the model, in the context of its existing assumptions about the nature of the world, to disambiguate possible depth values.
While there are many different monocular depth cues that have been shown to improve performance in animals, we focus here on the semantics and assumptions that may be made about both (a) objects and (b) the relationships between objects in a scene.
While existing methods make the assumption that their model will implicitly learn the nature of any depth cues present in the target domain, we hypothesise that this is a source of \textbf{inefficiency} in a model: expending the limited resources of model capacity and training data on implicit learning of the \textit{existence} of depth cues means that those resources are not being spent on \textit{interpreting} those depth cues. Models that learn to perform MDE implicitly must first infer that perspective (for instance) exists at all, and only then can they begin learning the functions required to map the perspective-related features they observe to depth predictions. Thus, our method is designed around encouraging a model to focus on learning these known-useful relationships; provided the bias deliberately introduced is at least as useful as that that would be learned by the model implicitly, an improvement in performance would be expected.
Following this motivation, we divide our main model into different sections: the \textbf{visual encoder}, the \textbf{object encoder}, and the \textbf{ObjCAViT block}.
\subsection{Visual Encoder}
\label{sec:visual-encoder}
The visual encoder is responsible for interpreting the raw RGB pixel values from the input image. In our architecture, we use a convolutional encoder-decoder model to extract dense image features. The architecture of this encoder-decoder mirrors that of AdaBins \cite{bhat_adabins_2020}: it comprises an EfficientNet-B5\cite{tan_efficientnet_2019} encoder pretrained on ImageNet \cite{deng_imagenet:_2009}, and a standard upsampling decoder with skip connections from the encoder. The visual encoder outputs features at $0.5\times$ the resolution of the input image. In the style of the vision transformer \cite{dosovitskiy_image_2021}, features are then divided into 16x16 patches and further embedded using a 2d convolution with kernel size and stride both set to 16x16, and the resulting image patch features are flattened for use by the ObjCAViT block.
\subsection{Object Encoder}
\label{sec:object-encoder}
The object encoder is responsible for both extracting and then providing embeddings for the objects in the scene.
\textbf{Object detection.} To simplify the task of the depth estimation network by avoiding having to learn multiple tasks, we use a frozen YOLOv7 object detector\cite{wang_yolov7_2022} to extract object bounding boxes and class labels. In our implementation, we use the segmentation-capable model, first pretrained on the 80-class MS-COCO \cite{lin_microsoft_2015} dataset, and then fine-tuned for 235 epochs on the 1203-class LVIS \cite{gupta_lvis_2019} v1.0 instance and semantic segmentation dataset.
LVIS is used due to the large number of labels available, and because labels are given as Wordnet \cite{miller_wordnet_1995} synsets to remove the problem of polysemy.
\textbf{Language embedding.} The purpose of introducing object information is to make use of a pre-existing model of the underlying nature of that object (e.g. its shape, size, or common co-occurrences with other objects). In our method, this prior world-knowledge is extracted from the language model used in CLIP \cite{radford_learning_2021}. Existing work has shown that CLIP, as well as other language models, encode likely spatial and depth information about an object (see section \ref{sec:background}), and thus we use CLIP language embeddings as a proxy for general world knowledge.
WordNet definitions are extracted for the class label of each detected object\footnote{With one exception, ``stop\_sign.n.01", the definition for which is sourced from the first sentence of the English language Wikipedia article for "stop sign".} in the image. These definitions are then used as the language input to a frozen pretrained CLIP ViT-B/32 language encoder, which outputs a single $512d$ embedding. These are then reduced with a linear layer to match the dimensionality of the image features.
We experiment with two different language templates for a given object label. The first, \textit{def. only}, uses only the WordNet definition for that object's synset label $\{Obj_i\}$ as the language input. The second, \textit{def.+sz\_rel}, aims to extract information about object relationships from the language model using a relative size clause, which selects one other random object $\{Obj_j\}$ detected in the scene, compares its apparent size (bounding box area) to that of the current object $Obj_i$, and then compares them on a 7-point scale of size comparison phrases:
\textit{[much smaller/smaller/a bit smaller than, about the same size as, a bit bigger/bigger/much bigger than]}
The final template has the form \textit{``This is a/an $\{Obj_i\}$, defined as \{definition\}. This $\{Obj_i\}$ appears to be \{size comparison\} the \{$Obj_j$\}."}. The comparative scale text is chosen according to the bounding box area factor $f_A = \frac{A_i}{A_j}$ for the areas of objects $i$ and $j$. We assign $f_A$ to bins: two edge bins for $f_A \le e^{-3}$ and $f_A > e^3$, and 5 bins with centres defined at $e^k \forall k \in \{-2, -1, 0, 1, 2\}$. These 7 bins are each assigned a natural language phrase from the 7-point scale accordingly, to give the final phrase.
\subsection{ObjCAViT Module}
\label{sec:objcavit-module}
\begin{figure}
\centering
\includegraphics[width=\linewidth]{figures/ObjCAViT_Block_Detail.pdf}
\caption{\textbf{Our proposed ObjCAViT block}, which uses self-attention to allow the model to learn to relate image features to each other and to learn the relationships between detected objects in a scene. It then combines the two using a cross-attention mechanism that modifies the image features based on the learned relationships between the detected objects.
}
\label{fig:objcavit-detail}
\end{figure}
\begin{figure*}[!h]
\centering
\includegraphics[width=\textwidth]{figures/pred1_kitti.png}
\caption{Example inputs and outputs of our best model, demonstrated on the KITTI dataset. This model uses only synset definitions for the detected objects, and uses both object bounding box (or image patch) centre coordinates and dimensions as inputs to the positional encoders when performing self-attention. The object detections output by YOLOv7 are also shown in the right-hand column.}
\label{fig:pred1-kitti}
\end{figure*}
The \textbf{Object Cross-Attention Vision Transformer}, or \textbf{ObjCAViT}, is a principal contribution of our work, and its architecture can be seen in figure \ref{fig:objcavit-detail}. It is an extension of the Vision Transformer \cite{dosovitskiy_image_2021} and miniViT \cite{bhat_adabins_2020} of previous work, but with the key difference that it allows the model to learn three main cues: the relationships between objects, the relationships between patches of the input image, and how to link the two together. This mirrors the MDE cues known to be present in the biological domain (see section \ref{sec:background}).
First, the image and object features are fed through the common positional encoder, and the resultant positional embeddings are added to the image/object features. We tried different positional encoders: (1) a simple MLP with LeakyReLU activation that takes the $(x,y)$ coordinates and outputs a $128d$ positional embedding, (2) a similar model but with 4 inputs instead of 2 to allow embedding of bounding box/patch dimensions as well as positions.
The object features are self-attended to using a transformer encoder with 4 layers of 4 heads each, a feedforward dimension of 1024, and an embedding dimension of 128. The visual patch features are similarly self-attended. This yields a sequence of features representing the visual aspects of the image, and another set of features representing the semantics of the objects in the image and their relationships to one another. Lastly, a cross-attention mechanism is used, with the visual features acting as the query and value inputs, and the object features acting as the key input. This allows the network to attend to the image features based on the object features. The ObjCAViT module outputs a sequence of features.
\subsection{Output Stage}
\label{sec:output-stage}
The first feature in the ObjCAViT output sequence is processed by a simple MLP to obtain a vector of 256 depth bin widths, $b$, for that input image. The next 128 features in the sequence are dotted with the dense image features to give bin probabilities $P$ for each pixel of the dense image feature map. This output format, and the post-processing we use to convert it into depth maps, follow \cite{bhat_adabins_2020, li_binsformer_2022}.
To obtain the depth, the bin centres $c$ are computed from the bin widths $b$ and the maximum and minimum depth values $d_{max}$ and $d_{min}$ in use for the dataset:
\begin{equation}
c(b_i) = d_{min} + (d_{max} - d_{min})\biggl(\frac{b_i}{2} + \sum_{j=1}^{i-1}b_j\biggr)
\end{equation}
The final depth value $d$ for a pixel $n$ of the dense feature map $P$ is then obtained by summing the bin centres, weighted by the bin probabilities across the 256 bins:
\begin{equation}
d_{n} = \sum_{i=1}^{256}c(b_i)P_n
\end{equation}
Because $P$ is at $0.5 \times$ input resolution, the final output depth map is as well. We bilinearly upsample this output to match the input image resolution for loss computation.
\subsection{Loss Function}
\label{sec:loss-function}
The loss functions used are the scale-invariant log loss and the bin centre density loss of AdaBins \cite{bhat_adabins_2020}. The ground-truth and predicted depth values for pixel $n$ are given as $d^*_n$ and $d_n$ respectively. The depth loss we use is given by:
\begin{equation}
\label{eq:depth-loss}
\mathcal{L}_{SILog} = 10 \sqrt{\frac{1}{N}\displaystyle\sum_{i \in N} g_{n}^2 + \frac{0.15}{N^2}(\displaystyle\sum_{n \in N} g_{n})^2}
\end{equation}
where $g_{n} = log(d_{n}) - log(d^*_{n})$ and $N$ is the total number of pixels with valid depth values. The bin centre density loss encourages the network to predict bin centres that are similarly distributed to the ground-truth depth values. It is given by the Chamfer loss between the set of depth values in the ground truth $d$ and the bin centres $c(b)$, and vice versa:
\begin{equation}
\label{eq:bin-centre-loss}
\mathcal{L}_{bin} = \text{chamfer}(d,c(b)) + \text{chamfer}(c(b),d)
\end{equation}
\section{Background}
\label{sec:background}
\begin{figure*}[h]
\centering
\includegraphics[width=\textwidth]{figures/ObjCAViT.pdf}
\caption{\textbf{An overview of our architecture}, showing the input RGB image on the left and the predicted depth map on the right. The ObjCAViT block is shown in more detail in figure \ref{fig:objcavit-detail}. Orange blocks are learnable, red are pretrained and frozen, and grey are non-learned functions. Image and object features are coloured purple and blue respectively.}
\label{fig:main_arch}
\end{figure*}
\textbf{Monocular Depth Estimation} (MDE) methods generally treat the problem as a dense image to image mapping. They often consist of a convolutional encoder and decoder, and frequently make use of encoders that have been pretrained on ImageNet \cite{deng_imagenet:_2009} such as ResNet \cite{he_deep_2016}, VGG \cite{simonyan_very_2015}, or EfficientNet \cite{tan_efficientnet_2019}. Once dense features have been extracted from these encoders, they are then upsampled or decoded to provide an output depth map.
Previous SOTA methods have expanded on this basic template in different ways. \cite{eigen_depth_2014, eigen_predicting_2015, lee_big_2019} use a multi-scale prediction approach. \cite{lee_big_2019} make the assumption that the world is (locally) planar. Some \cite{ramamonjisoa_sharpnet:_2019, jiao_look_2018, bai_monocular_2019} co-predict depth with other tasks such as semantic segmentation or surface normals, sharing some weights between the different decoder heads or enforcing consistency between tasks in the loss function.
More recent methods have reframed the problem as classification, where the model must assign each pixel of the input image to a depth ``bin" instead of giving a scalar value. \cite{fu_deep_2018} directly assign each pixel to a bin, giving good performance but producing artifacts due to the discrete nature of the output. AdaBins \cite{bhat_adabins_2020} expanded on this work significantly: rather than using uniform bins, a transformer \cite{vaswani_attention_2017} model was used to adaptively change the distribution and width of the bins according to the input image, assigning final depth values by smoothly interpolating between bin centres using a pixel's bin probability vector. \cite{li_binsformer_2022} improve on adaptive binning by using intermediate features from the image encoder to assist in the binning process, and by adding an auxiliary scene classification task to encourage the model to learn global semantic information. \cite{li_depthformer_2022} use both a transformer and a traditional convolutional encoder to extract image features, before merging them and decoding to a depth map using a transformer decoder. Very recently, \cite{agarwal_attention_2022} have used an all-transformer architecture to extract image features and to perform adaptive binning based on these features. All of these recent methods, however, do not explicitly steer the model towards the learning of local scene or object \textit{semantics}.
\textbf{Cross attention} as a means of combining features from multiple sources is a technique that has produced positive results in a variety of problems, beginning with the original transformer paper \cite{vaswani_attention_2017}. \cite{li_selfdoc_2021} apply cross-attention to a joint visual and textual interpretation of a document. \cite{chen_crossvit_2021} use it for the combination of different scales of image patches in a vision-transformer-like model. In the problem of local feature matching, \cite{sarlin_superglue_2020} applied cross-attention to cause the model to learn the correspondences between pairs of features. While \cite{li_depthformer_2022} make use of deformable cross-attention, it is used to combine two different sets of image features together rather than to introduce non-image information.
\noindent\textbf{Language and depth.} Language and depth is a relatively new area of research. Intuitively, a language model exists to encode human language; if human language in turn encodes human ideas, then it would follow that language models encode human biases. \cite{henlein_what_2022} showed that BERT \cite{devlin_bert_2019} embeddings contain information about the likely distribution of objects across different rooms, the relationship between parts of objects and the objects they are likely part of, as well as the likely target objects for a given verb. \cite{auty_monocular_2022} make use of GloVe \cite{pennington_glove_2014} embeddings as a means of introducing knowledge about the world to the model to encourage it to use the familiar size biological depth cue. CLIP \cite{radford_learning_2021} is a transformer-based model that, given enough data, is able to correlate high-level visual concepts with language; this has been used for image generation from language \cite{ramesh_hierarchical_2022}, and has more recently been applied to zero-shot depth estimation \cite{zhang_can_2022} by correlating image features with the features of depth-related sentences. Despite the difficulty of training CLIP, pre-trained checkpoints for general purpose models are available online. For these reasons, coupled with CLIP's demonstrated high performance on tasks (notably image synthesis) that require a significant degree of world-knowledge, our method uses a frozen, pretrained CLIP model.
| {'timestamp': '2022-12-01T02:21:06', 'yymm': '2211', 'arxiv_id': '2211.17232', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17232'} | arxiv |
\section{Introduction}\label{sec:intro}\input{sections/01-intro}
\section{Background}\label{sec:related}\input{sections/02-related}
\section{Dataset: \textsc{Crepe}}\label{sec:data}\input{sections/03-data}
\section{Task Setup}\label{sec:task}\input{sections/04-task-setup}
\section{Experiments: Detection}\label{sec:exp-detection}\input{sections/05-exp-detection}
\section{Experiments: Writing}\label{sec:exp-writing}\input{sections/06-exp-writing}
\section{Discussion}\label{sec:discuss}\input{sections/07-discuss}
\section{Conclusion}\label{sec:concl}\input{sections/08-concl}
\section*{Acknowledgements}
We thank Daniel Fried and Julian Michael for their feedback on an early stage of the project. We thank Zeqiu Wu and H2Lab members for comments on the paper.
We thank Li Du for suggesting the name of the dataset.
\subsection{Question Answering}\label{subsec:background-qa}
There has been significant work on question answering, where the model receives a natural language, open-domain question and is required to return a short, concise answer~\citep{voorhees-tice-2000-trec,lee-etal-2019-latent}.
Most work focuses on questions that have a short text span as a correct answer. Other work studies unanswerable questions, but they study questions that are either intentionally written to be unanswerable~\citep{rajpurkar-etal-2018-know}, or where there is a lack of evidence to find the answer~\citep{choi2018quac,asai-choi-2021-challenges}.
More recently, \citet{kim-etal-2021-linguist} studies unverifiable presuppositions in questions under the given context, but using questions from \citet{kwiatkowski-etal-2019-natural} whose presuppositions are mostly not false based on {\em global} knowledge.\footnote{
Less than 5\% of questions from \citet{kwiatkowski-etal-2019-natural} contains false presupposition under our definition, likely because their questions are aggressively filtered.
}
In this work, we focus on open-domain questions with presuppositions that are false based on global knowledge. They are categorized to be unanswerable based on the taxonomy from previous work, but we argue they can be {\em answered} by providing false presuppositions and their corrections.
We show that false presuppositions in questions are \textbf{prevalent}. 25\% of questions contain false presuppositions in the domain of online forums (for which we collect annotations), research papers~\citep{dasigi-etal-2021-dataset}, scientific reviews~\citep{kang18naacl}, and social media~\citep{sap-etal-2020-social}.
\subsection{Presupposition}\label{subsec:background-presupposition}
Under a {\em pragmatic} point of view, a presupposition is a condition that a speaker would normally expect to hold in the common ground between discourse participants when that sentence is uttered~\citep{sep-presupposition,stalnaker1977pragmatic}.
Unlike semantic presuppositions~\citep{strawson1950referring}, pragmatic presuppositions cannot easily be traced to specific words or phrases, but rather depend on the context and the expectations of the discourse participants~\citep{potts2015presupposition}.
A key property of pragmatic presuppositions is that they are {\em backgrounded}---a pragmatic property of being a meaning that the speaker presumes to be mutual public knowledge.
Whether or not one is a presupposition is inherently debatable.
In this work, we carefully define a false presupposition in the question by leveraging the most voted comment in the web community, as we discuss further in Section~\ref{subsec:data-annotation}.
False presuppositions in {\em questions} have been discussed in the linguistic literature~\citep{kaplan-1978-indirect-responses, duvzi2015questions}. A key property of false presuppositions in the question is that they make a question infelicitous because there is no direct answer. \citet{kaplan-1978-indirect-responses} claims that an adequate and unambiguous answer to such a question is a negated presupposition, referred to as corrective indirect response. We follow them in providing the negated presupposition as the response to the question, and build the first benchmark based on questions written by information-seeking users.
\subsection{Data Source}\label{subsec:data-source}
Our highest priority is to study false presuppositions that {\em naturally} occur from information-seeking users. While it is significantly easier to manually write questions that would have false presuppositions,
we think these questions will significantly be different from naturally occurring questions.
Following \citet{fan-etal-2019-eli5}, we use questions posted on the ELI5 subreddit.\footnote{\href{https://www.reddit.com/r/explainlikeimfive}{\nolinkurl{www.reddit.com/r/explainlikeimfive}}}
We made a few modifications to the procedure that \citet{fan-etal-2019-eli5} took in order to improve the data quality.
We first filter questions and comments based on upvotes with a higher threshold. We then split the training, the development and the test data based on the time of the posting: questions on the training set are posted in 2011--2018, questions on the development set are posted in Jan--Jun of 2019, and questions on the test set are posted in Jul--Dec of 2019. We filter out the small subset of questions that include toxic language. Appendix~\ref{app:data-source-details} provides more details. %
\citet{krishna-etal-2021-hurdles} raised a concern that a significant amount of test are duplicates of those on the training set. We provide a detailed analysis in Appendix~\ref{app:data-source-details}. In summary, we think (1) the amount of duplicated (or paraphrased) questions is significantly less than their estimate, %
especially with respect to underlying presuppositions in the questions, and (2) even if there are paraphrased questions, data split based on the time frame is justified based on the real-world scenario.\footnote{We think having similar questions is an inherent property of questions on the web, and the model should be allowed to take whichever approach that is plausible, including the nearest neighbor approach~\citep{lewis-etal-2021-question}.}
\subsection{Data Annotation}\label{subsec:data-annotation}
Meeting the criteria \textbf{C2} and \textbf{C3} can be very difficult for the following reasons:\vspace{-.3em}
\begin{itemize}[leftmargin=1em]\itemsep -.1em
\item For \textbf{C2}: The validity of presupposition is inherently debatable and largely depends on the background of individuals (Section~\ref{subsec:background-presupposition}).\footnote{
This is also the case in previous work---for instance, the data annotated by experts in formal semantics and pragmatics can have low agreement~\citep{jeretic-etal-2020-natural}.
}
\item For \textbf{C3}: The open-domain nature of the task requires the search of world knowledge on the web, which is extremely expensive and may not be exhaustive enough despite the best efforts made by annotators, as discussed in \citet{kwiatkowski-etal-2019-natural,min-etal-2020-ambigqa}.
\end{itemize}
In this work, we make use of the \textbf{most upvoted comments} written by community users.
The comment, often written by domain experts, provides a response to the question in the ELI5 subreddit, and has been used as a credible source in prior work~\citep{fan-etal-2019-eli5}.
If the comment identifying a false presupposition has the most upvotes, it is likely that the presupposition is valid (made by a question writer) based on the background context shared by community users, thus satisfying \textbf{C2}. %
Moreover, the comment (1) is highly likely to contain information that is correct and adequate (satisfying \textbf{C3}), and (2) removes the need for exhaustively searching over the web (reducing the annotation cost).
\paragraph{Annotation task.} Annotators are given a pair of the question and the most voted comment, and perform the following steps.\vspace{-.35em}
\begin{enumerate}\itemsep -.15em
\item Filter out questions that are subjective, are uninformative, or rely too much on personal experience.
\item Judge whether there is a false presupposition in the question, %
identified by the comment.
\item If there is a false presupposition, write the presupposition and a correction as a concise, declarative sentence.
\end{enumerate}
\paragraph{Annotation pipeline.}
We maintain a pool of qualified annotators who passed our qualification task.
We assign two annotators per question, where each annotators independently annotate the question.
We filter out questions if either of the annotators mark them as such.
If the annotators agreed to on the label (whether or not there is a false presupposition), their label as well as their writings are taken as gold references.
When they disagreed, we assign a third annotators and take a majority vote over three workers.
We find that the disagreements %
are mainly due to inherent ambiguities of the task due to the different interpretation of the question or the comment, or difference in individual background knowledge. We discuss these cases in Section~\ref{subsec:data-analysis}.
\vspace{.1em}
More details in instructions and quality control are provided in Appendix~\ref{app:data-annotation-details}.
\begin{table*}[!t]
\centering \footnotesize
\setlength{\tabcolsep}{0.4em}
\begin{tabular}{p{0.46\textwidth}}
\toprule
\multicolumn{1}{c}{\textbf{False clauses (14\%)}} \vspace{.1em} \\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} If water has to be 100 to become steam, how come you don't get heavily burned in saunas?\\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} What we often call steam is just water vapor that has started to become visible due to different temperatures of the water vs air. It can exist at many temperatures. (...) \\
\textbf{\colorbox{purple!30}{{\textbf{\texttt{FP}}}}} Water has to be 100 degrees to be steam. \\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} Why is the air cold when you fan yourself on a very hot day? Doesn't motion generate heat? \\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} Moving air takes away heat faster from your skin. That's why it feels cool. (...) I assume you mean friction generates heat. But the air speed generated by a fan is way too slow to generate any friction heat. \\
\textbf{\colorbox{purple!30}{{\textbf{\texttt{FP}}}}} Motion of the fan generates heat. \\
\midrule
\multicolumn{1}{c}{\textbf{False properties (22\%)}} \vspace{.1em} \\
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ How do martial artists who karate chop or punch a cement block not break their hand? \\
\colorbox{pink!70}{\textbf{\texttt{C}}}\ It's a trick, the blocks are not very strong, and they are being punched or kicked in their weakest points. \\
\colorbox{purple!30}{{\textbf{\texttt{FP}}}}\ Chops or cement blocks are strong. \\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} How does your phone tell the difference between a step and random movement? \\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} You might be disappointed by this answer, but most of the time, you're not moving your phone so abruptly that the change in acceleration to it is anywhere near the shock that comes %
when you walk. \\
\textbf{\colorbox{purple!30}{{\textbf{\texttt{FP}}}}} A random movement is detectable by a phone. \\
\midrule
\multicolumn{1}{c}{\textbf{False existential presupposition (6\%)}} \vspace{.1em} \\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} What uses the space on a hard disk that we're unable to use? For example in a 1TB hard disk, we get about 930GB of usable memory, what happens to the other 70GB? \\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} There are %
TB (terabyte) and TiB (tebibyte). the "ra" ones are using multiplies of 1000. the "bi" ones are using multiplies of 1024. I will do some math for you: 1 TB=1000$^4$B = (...) = 0.93 TiB. There goes your 70 GiB.\\
\textbf{\colorbox{purple!30}{{\textbf{\texttt{FP}}}}} In a 1TB hard disk, 70GB is unusable. \\
\bottomrule
\end{tabular}\vspace{-.1em}
\begin{tabular}{p{0.47\textwidth}}
\toprule
\multicolumn{1}{c}{\textbf{False predicate (30\%)}} \vspace{.12em} \\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} How exactly is current stored in power plants?
\\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} It's not being stored at all. %
The power grid is a carefully balanced dance of supply and demand. (...) \\
\textbf{\colorbox{purple!30}{{\textbf{\texttt{FP}}}}} Current is stored in power plants. \\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} How can light bounce off objects but it has no mass. \\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} Light does not ``bounce''. A photon of light is absorbed by an atom, then (...) \\
\textbf{\colorbox{purple!30}{{\textbf{\texttt{FP}}}}} Light bounces off objects. \\
\midrule
\multicolumn{1}{c}{\textbf{False (causal) relationship between facts (22\%)}} \vspace{.1em}
\\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} If there's an equal and opposite reaction for everything, how does any action happen? Isn't it balanced out by the opposite reaction? \\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} I don't think you are fully comprehending what `equal' means in this situation. (...) These forces are acting on different bodies so they do not cancel each other out. (...) \\
\textbf{\colorbox{purple!30}{{\textbf{\texttt{FP}}}}} The equal and opposite reaction applies to the same object.\\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} In today’s high tech world, how come we are not able to reproduce ancient crafting methods like Roman Concrete, Damascus Steel, or Greek Fire? \\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} It's not that we can't reproduce them technologically, it's that the exact method or recipe was lost to history (...) \\
\textbf{\colorbox{purple!30}{{\textbf{\texttt{FP}}}}} Ancient crafting methods are not reproducible due to lack of technologies. \\
\midrule
\multicolumn{1}{c}{\textbf{Exceptions (4\%) }} \vspace{.1em} \\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} How do bugs and other insects survive winter when they have such a short lifespan? \\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} Depends on the insect, some don't have that short of a lifespan. But mostly (...) \\
\textbf{\colorbox{purple!30}{{\textbf{\texttt{FP}}}}} (All) insects have a short lifespan. \\
\midrule
\multicolumn{1}{c}{\textbf{No false presupposition / Annotation error (2\%)}} \vspace{.1em} \\
\textbf{\colorbox{blue!30}{\textbf{\texttt{Q}}}} Why can't we artificially make plastic decompose faster? \\
\textbf{\colorbox{pink!70}{\textbf{\texttt{C}}}} Decomposition happens when something eats the thing that is decomposing. (...) %
\\
\bottomrule
\end{tabular}\vspace{-.1em}
\caption{Breakdown of types of false presuppositions, based on 50 random samples on the development data. \colorbox{blue!30}{\textbf{\texttt{Q}}}, \colorbox{pink!70}{\textbf{\texttt{C}}}\ and \colorbox{purple!30}{{\textbf{\texttt{FP}}}}\ indicate the question, the comment, and the presupposition, respectively.
}\label{tab:data-analysis}
\end{table*}
\subsection{Data Analysis}\label{subsec:data-analysis}
The data statistics are provided in Table~\ref{tab:data-statistics}. We find that over 25\% of questions posted on Reddit includes false presuppositions.\footnote{
\citet{xu-etal-2022-answer}, who also used the ELI5 subreddit, identified 10\% of questions have false presuppositions (rejected presuppositions) and excluded them in their data.
The reason their estimate is significantly lower than ours is that they did not include partial rejection while we do.
}
\paragraph{Categorization of false presuppositions.}
We randomly sample 50 questions with false presuppositions and categorize them in Table~\ref{tab:data-analysis}. The five most frequent types of presuppositions include: %
\vspace{-.2em}
\begin{itemize}[leftmargin=1.3em]
\setlength\itemsep{-0.1em}
\item \textbf{False clauses} are those where \colorbox{purple!30}{{\textbf{\texttt{FP}}}}\ is made as a clause in \colorbox{blue!30}{\textbf{\texttt{Q}}}, e.g., ``the water has to be 100 to become steam'' or ``the motion of the fan generates heat'' in Table~\ref{tab:data-analysis}.
\item \textbf{False predicate} are those where the predicate in \colorbox{blue!30}{\textbf{\texttt{Q}}}\ is false, e.g., ``current is stored in power plants'' or ``light bounce off objects''. This is the most common type of false presuppositions on \textsc{Crepe}.
\item \textbf{False properties} are those where certain properties or attributes are presupposed in \colorbox{blue!30}{\textbf{\texttt{Q}}}, e.g., ``cement blocks are too strong so that people who punch them are likely to break their hand.''
They are often very implicit and may be deniable.
However, the question writer would not have asked the question otherwise, thus it is reasonable to assume that the \colorbox{purple!30}{{\textbf{\texttt{FP}}}}\ is actually made by the question writer.
\item \textbf{False (causal) relationship between facts} are those where \colorbox{blue!30}{\textbf{\texttt{Q}}}\ makes a (causal) relationship between facts that are false. This is another very implicit type of presuppositions, but again, the question writer would not have asked this question if they have not made such a presupposition. An interesting observation is that a large portion of such questions involve scientific phenomenon
on which the question writer has misunderstanding, e.g., in the example in Table~\ref{tab:data-analysis}, the question writer had a misconception about Newton's Third Law of Motion.
\item \textbf{False existential presupposition} indicates that \colorbox{blue!30}{\textbf{\texttt{Q}}}\ includes an existential presupposition, one type of semantic presuppositions, that is false. For instance, the example \colorbox{blue!30}{\textbf{\texttt{Q}}}\ in Table~\ref{tab:data-analysis} presupposes an unused space in a hard disk, and \colorbox{pink!70}{\textbf{\texttt{C}}}\ says there is no unused space.
\end{itemize}
\paragraph{Triggers in the comment.}
We analyze how comments point out the falsehood of the presupposition made in the question on the same set of 50 samples on the development data.
In 68\% of times, comments include specific lexical cues which we call {\em triggers}.
70\% of such triggers are negations. Other word-level triggers include ``actually'', ``just'', ``rare'', ``really'' and ``though''. Sentence-level triggers include ``You are mistaken'', ``You've got some major confusion here'', ``I don't think you are fully comprehending ...'' and ``It should be noted that...''. 80\% of triggers appear in the first sentence of the comment, and the rest of the sentences elaborate on how the presupposition is false or provide other relevant information that does not directly answer the question.
The rest 32\% do not include lexical triggers and requires more careful comprehension of the comment with respect to the question, e.g., the false existential example in Table~\ref{tab:data-analysis}.
\vspace{-.3em}
\paragraph{Analysis of ambiguous cases.}
Even with our best efforts, there are still inherent disagreement between annotators.
Some of them are due to inherent ambiguities in language, e.g., the first example in Table~\ref{tab:ambiguity-analysis} where `the state of the water' could either mean the molecule itself or the energy state of the molecule.
Others are due to disagreement on the validity of the presupposition, e.g., in the second example in Table~\ref{tab:ambiguity-analysis}, it is debatable whether or not the question writer presupposes that the Board deals with day to day at a company.
We revisit this issue in human performance estimation in Section~\ref{subsec:detection-subtask-results}.
\begin{table}[!t]
\centering \footnotesize
\begin{tabular}{p{0.46\textwidth}}
\toprule
\multicolumn{1}{c}{\textbf{Ambiguity in language}} \\
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ When water boils, its bubbles are round, but when it freezes, its crystals are 6-sided. Why isn’t frozen water round or boiling water hexagonally shaped? Aren’t H2O molecules the same in either state? \\
\colorbox{pink!70}{\textbf{\texttt{C}}}\ Bubbles are round because (...) Ice crystals are shaped in such a way because (...) The water molecules are much slower and aren't bouncing all over the place. Gaseous H2O is much higher energy and further apart so that the regular pattern of ice doesn't come into effect. \\
\midrule
\multicolumn{1}{c}{\textbf{Ambiguity in whether the presupposition is made}} \\
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ How do executives hold board of director positions at multiple fortune 500 companies? \\
\colorbox{pink!70}{\textbf{\texttt{C}}}\ The Board only meets occasionally to vote on more important matters. They don't really deal with day to day affairs like the CEO does. \\
\bottomrule
\end{tabular}\vspace{-.1em}
\caption{Two types of ambiguous cases. \colorbox{blue!30}{\textbf{\texttt{Q}}}\ and \colorbox{pink!70}{\textbf{\texttt{C}}}\ indicate the question and the comment, respectively.
}\label{tab:ambiguity-analysis}
\end{table}
\subsection{Baselines}\label{subsec:detection-subtask-baselines}
\subsubsection{Trivial baselines}\label{subsec:trivial-baselines}
\noindent
\textbf{Random} assigns \texttt{FP}\ or \texttt{N}\ randomly at uniform.
\textbf{\texttt{FP}\ only} always assigns \texttt{FP}.
\textbf{\texttt{N}\ only} always assigns \texttt{N}.
\textbf{Nearest Neighbor} retrieves one of questions from the training set that is closest to the test question, based on c-REALM~\citep{krishna-etal-2021-hurdles}, and returns its label as the prediction.
\subsubsection{\textsc{gold-comment} track\ baselines}\label{subsec:oracle-comment-baselines}
\textbf{Question only} trains a RoBERTa-based~\citep{liu2019roberta} classifier that takes the question as the only input and classifies the label. It is often called closed-book model~\citep{roberts-etal-2020-much}.
\textbf{Comment only} is a classifier based on RoBERTa-large that takes the comment as the only input and assigns the label; this baseline is provided as a reference.
\textbf{Question$\oplus$Comment} is a classifier based on RoBERTa-large that takes a concatenation of the question and the comment to the classifier, and assigns the label. %
We additionally experiment with the same model that is trained on either MNLI~\citep{N18-1101} or BoolQ~\citep{clark-etal-2019-boolq}, and tested on \textsc{Crepe}\ in a zero-shot fashion. This condition tests if training on similar, previously studied datasets helps.
\subsubsection{Main track baselines}\label{subsec:main-baselines}
We design a model called \textbf{c-REALM + MP (Multi-passage) classifier} that retrieves a set of paragraphs from Wikipedia and then assigns a label.
First, the model uses c-REALM~\citep{krishna-etal-2021-hurdles}, a state-of-the-art retrieval model on ELI5, to retrieve a set of $k$ passages from the English Wikipedia.
Next, the model uses the multi-passage classifier based on RoBERTa in order to assign a label. Given a question $q$ and a set of passages $p_1...p_k$, each $p_i$ ($1\leq i \leq k$) is concatenated with $q$ and is transformed into $\mathbf{h}_i \in \mathbb{R}^{h}$ through the Transformer model.
We then obtain logits via $\mathbf{p} = \mathrm{FFN}(\mathrm{MaxPool}(\mathbf{h}_1...\mathbf{h}_k)) \in \mathbb{R}^2$, where $\mathrm{FFN}$ is a feed-forward layer and $\mathrm{MaxPool}$ is an element-wise max operator.
Finally, we use $\mathrm{Softmax}(\mathbf{p})$ to compute the likelihood of $q$ having false presuppositions or not.
\vspace{-.3em}
\paragraph{Self-labeling}
Although our labeled data is small, there is large-scale unlabeled data (question and comment pairs) available.
We explore self-labeling to leverage this unlabeled data.
Specifically, we use the \textbf{Question$\oplus$Comment} to assign a silver label to the unlabeled training questions.
We then train the classifier on the union of this silver data as well as the gold labeled data.
\subsubsection{Human performance}
We estimate human performance to better understand the model performance. We recruit two human workers who perform the task for 186 questions for each track.
We estimate two types of human performance.
(1) \textbf{Human with the most voted comment}, where human workers assume the most voted comment as a ground truth in terms of factuality of the information and the validity of the presupposition. We think of it as an upperbound of model performance, since the comment is from multiple online users or domain experts.
(2) \textbf{Human w/o the most voted comment}, where human workers search over the web (except Quora and Reddit) to find information, and make the best judgment about the validity of the presupposition. We think it is likely to be worse than the upperbound of model performance, since only one worker, instead of multiple online users or domain experts, makes a decision.
\subsection{Results}\label{subsec:detection-subtask-results}
Results are reported in Table~\ref{tab:results-detection-task}.
\vspace{-.3em}
\paragraph{The \textsc{gold-comment} track.}
First, all trivial baselines achieve poor performance. In particular, poor performance of the nearest neighbor model indicates that there is no significant train-test overlap on \textsc{Crepe}.
The question only baseline and the comment only baseline are more competitive. This is likely due to bias in the question distribution (in case of the question only), and the comment usually includes information from the question (in case of the comment only).
Nonetheless, using both the question and the comment (Question$\oplus$Comment) achieves the best performance, outperforming the best trivial baseline by 22\% absolute.
Zero-shot models trained on MNLI and BoolQ achieve poor performance, being even worse than some of trivial baselines. This indicates our problem is significantly different from existing tasks like NLI or binary question answering.
The best model is 10\% below human performance, indicating room for improvement, even in the easier track.
\ignore{
\begin{table}[!t]
\centering \footnotesize
\begin{tabular}{lrr}
\toprule
Model & Dev & Test \\
\midrule
\multicolumn{3}{l}{\textbf{\em{Trivial baselines}}} \\
Random$^\otimes$ & 31.7 & 34.3 \\
Always predict \texttt{FP}$^\otimes$ & 42.8 & 40.0 \\
Always predict \texttt{N}$^\otimes$ & 0.0 & 0.0 \\
Nearest Neighbor$^\otimes$ & 35.2 & 32.4 \\
\midrule
\multicolumn{3}{l}{\textbf{\em{\textsc{gold-comment} track}}} \\
Question only & 56.8 & 54.6 \\
Comment only & 58.0 & 56.8 \\
Question$\oplus$Comment & \textbf{67.3} & \textbf{65.7} \\
Question$\oplus$Comment (MNLI)$^\otimes$ & 31.2 & 28.9 \\
Question$\oplus$Comment (BoolQ)$^\otimes$ & 37.1 & 31.6 \\
Human & 79.1 & 77.3 \\
\midrule
\multicolumn{3}{l}{\textbf{\em{Main track}}} \\
c-REALM + MP classifier & 57.7 & 54.1 \\
c-REALM + MP classifier (Self-labeling)$^\ddagger$ & \textbf{58.8} & \textbf{55.5} \\
Human & 57.1 & 59.7 \\
\bottomrule
\end{tabular}\vspace{-.1em}
\caption{Baseline results in the \textbf{detection subtask} on the development data and the test data, respectively. F1 scores reported.
By default, the models are trained on the labeled portion of \textsc{Crepe};
$^\otimes$ indicates the model is not trained on \textsc{Crepe}; $^\ddagger$ indicates the model is trained on both the labeled and unlabeled portions of \textsc{Crepe}.
}
\label{tab:results-detection-task}
\end{table}
}
\begin{table}[!t]
\centering \footnotesize
\begin{tabular}{lrr}
\toprule
Model & Dev & Test \\
\midrule
\multicolumn{3}{l}{\textbf{\em{Trivial baselines}}} \\
Random$^\otimes$ & 44.9 & 47.8 \\
Always predict \texttt{FP}$^\otimes$ & 21.4 & 20.0 \\
Always predict \texttt{N}$^\otimes$ & 42.1 & 42.9 \\
Nearest Neighbor$^\otimes$ & 56.2 & 54.1 \\
\midrule
\multicolumn{3}{l}{\textbf{\em{\textsc{gold-comment} track}}} \\
Question only & 67.7 & 66.9 \\
Comment only & 68.9 & 68.6 \\
Question$\oplus$Comment & \textbf{76.3} & \textbf{75.6} \\
Question$\oplus$Comment (MNLI)$^\otimes$ & 54.4 & 54.2 \\
Question$\oplus$Comment (BoolQ)$^\otimes$ & 60.4 & 58.2\\
\midrule
\multicolumn{3}{l}{\textbf{\em{Main track}}} \\
c-REALM + MP classifier & 68.3 & 66.3 \\
c-REALM + MP classifier (Self-labeling)$^\ddagger$ & \textbf{69.1} & \textbf{67.1} \\
\midrule
Human w/ most-voted comment & 86.4 & 85.1 \\
Human w/o most-voted comment & 70.9 & 70.9 \\
\bottomrule
\end{tabular}\vspace{-.1em}
\caption{Baseline results in the \textbf{detection subtask} on the development data and the test data, respectively. \textbf{Macro-F1} scores reported.
By default, the models are trained on the labeled portion of \textsc{Crepe};
$^\otimes$ indicates the model is not trained on \textsc{Crepe}; $^\ddagger$ indicates the model is trained on both the labeled and unlabeled portions of \textsc{Crepe}.
}
\label{tab:results-detection-task}
\end{table}
\vspace{-.3em}
\paragraph{The main track.}
Using retrieved passages from c-REALM and multi-passage classifier achieves 66.3\%
on the test set, which is significantly better than all trivial baselines.
The self-labeling technique leads to additional improvements, leading to an F1 of 67.1\%.
While these numbers are significantly better than trivial baselines, they are significantly worse than the model performance given the comment, and in fact, is very close to the performance of the question only baseline. This strongly suggests a retrieval bottleneck---getting passages that provide evidence as strong as human-written comments is difficult even with the state-of-the-art retrieval model.
To further support the bottleneck in retrieval, we conduct a detailed error analysis in Appendix~\ref{app:error-analysis}. For instance, 86\% of false negatives were due to retrieval misses, including failing to retrieve relevant topics (42\%), retrieving evidence on the relevant topics but not related to the false presuppositions (32\%), or retrieving evidence related to the presuppositions but is not direct enough (12\%).\footnote{This can be seen as a classification error---if the classification model can better capture implicit evidence, it could have made a correct prediction.}
\paragraph{Human performance.}
Humans given the most upvoted comment achieve performance that is significantly higher than all baseline numbers, indicating significant room for improvement.
Without the most upvoted comment, people achieve relatively poor performance
(70.9\%).
To better understand this, we analyze 44 error cases, and categorize them in Table \ref{tab:human-perf-detection-task}.
Nearly half of the errors are due to an inherent disagreement in labels, either due to (1) ambiguity, either in language or whether the presupposition was made, or (2) whether it is critical to correct false presuppositions (especially cases in the exception category in Table~\ref{tab:data-analysis}).
The most upvoted comment is an aggregation of many active users of the community, thus it is reasonable to consider the most upvoted comment as a ground truth, and human performance with the most upvoted comment as an upperbound performance of \textsc{Crepe}.
Future work may take other approaches, e.g., not treating it as a binary classification problem.
\begin{table}[!t]
\centering \footnotesize
\begin{tabular}{p{0.35\textwidth}r}
\toprule
Error Category &\% \\ \midrule
Failure in finding evidence & 11.4 \\
Mistakes in labeling & 11.4 \\
Wrong ground truth label & 11.4 \\
Inherent disagreement: ambiguity & 34.1 \\
Inherent disagreement: criticalness
& 9.1 \\
Information on the web being inconsistent & 22.7 \\
\bottomrule
\end{tabular}\vspace{-.1em}
\caption{Analysis of 44 errors made by human performers without the most upvoted comment.
}
\label{tab:human-perf-detection-task}
\end{table}
\ignore{
\begin{table*}[!t]
\centering \footnotesize
\begin{tabular}{lR{1cm}R{1cm}R{1cm}R{1cm}R{1cm}R{1cm}R{1cm}}
\toprule
\multirow{2}{*}{Model} &
\multicolumn{3}{c}{Development} & \multicolumn{4}{c}{Test} \\
\cmidrule(lr){2-4} \cmidrule(lr){5-8}
& uF1 & R-L & BLEU & uF1 & R-L & BLEU & Human (\%)
\\
\midrule
\multicolumn{8}{l}{\textbf{\em{\textsc{gold-comment} track}}: Copy Baseline} \vspace{.3em} \\
& 35.8 & \textbf{17.6} & 10.2 & 35.9 & \textbf{17.2} & 10.2 & -- \\
~~~~~~~~~~Presupposition & 45.0 & 17.0 & 14.8 & 44.7 & 16.5 & 14.6 & --\\
~~~~~~~~~~Correction & 26.5 & 18.1 & 5.5 & 27.0 & 17.8 & 5.7 & --\\
\midrule
\multicolumn{8}{l}{\textbf{\em{\textsc{gold-comment} track}}: Question$\oplus$Comment} \vspace{.3em} \\
~~Dedicated & \textbf{44.8} & 14.5 & \textbf{24.0} & \textbf{42.9} & 13.6 & \textbf{19.5} & 70.0 \\
~~~~~~~~~~Presupposition & 51.7 & 16.4 & 30.0 & 47.7 & 14.6 & 22.9 & --\\
~~~~~~~~~~Correction & 37.8 & 12.5 & 17.9 & 38.0 & 12.6 & 16.1 & -- \\
~~Unified & 43.3 & 14.7 & 21.5 & 40.3 & 13.6 & 18.2 & 70.0 \\
~~~~~~~~~~Presupposition & 53.4 & 17.2 & 30.9 & 49.2 & 15.7 & 25.9 & -- \\
~~~~~~~~~~Correction & 33.2 & 12.2 & 12.0 & 31.4 & 11.5 & 10.4 & -- \\
\midrule
\multicolumn{8}{l}{\textbf{\em{Main track}}: Question + c-REALM} \\
~~Dedicated & 37.9 & 12.8 & 18.5 & 35.4 & 11.7 & 14.9 & 56.7\\
~~~~~~~~~~Presupposition & 49.1 & 15.9 & 28.2 & 45.9 & 14.4 & 22.6 & -- \\
~~~~~~~~~~Correction & 26.6 & 9.6 & 8.7 & 24.9 & 8.9 & 7.1 & --\\
~~Unified & 40.1 & 13.8 & 19.5 & 37.4 & 12.8 & 16.0 & 66.7 \\
~~~~~~~~~~Presupposition & 49.4 & 16.2 & 28.8 & 46.3 & 14.9 & 23.6 & -- \\
~~~~~~~~~~Correction & 30.7 & 11.3 & 10.1 & 28.4 & 10.6 & 8.3 & -- \\
\bottomrule
\end{tabular}\vspace{-.1em}
\caption{Baseline results in the \textbf{writing subtask}, on the development data and the test data, respectively. We report three automatic metrics: unigram F1 (uF1), ROUGE-L (R-L) and BLEU.
We also report average performance for a system for presupposition and correction generation.
}\label{tab:results-writing-task}
\end{table*}
}
\newcommand{\result}[3]{#2 & #3 & #1}
\begin{table*}[!t]
\centering \footnotesize
\begin{tabular}{l
R{.7cm}R{.7cm}R{.7cm}R{.7cm}
R{.7cm}R{.7cm}R{.7cm}R{.7cm}
R{.7cm}R{.7cm}R{.7cm}R{.7cm}
}
\toprule
\multirow{3}{*}{Model} &
\multicolumn{6}{c}{Development} & \multicolumn{6}{c}{Test} \\
& \multicolumn{3}{c}{uF1} & \multicolumn{3}{c}{BLEU}
& \multicolumn{3}{c}{uF1} & \multicolumn{3}{c}{BLEU}
\\
\cmidrule(lr){2-4} \cmidrule(lr){5-7} \cmidrule(lr){8-10} \cmidrule(lr){11-13}
& P & C & A & P & C & A & P & C & A & P & C & A \\
\midrule
\multicolumn{5}{l}{\textbf{\em{\textsc{gold-comment} track}}: Copy Baseline} \vspace{.3em} \\
& \result{35.8}{45.0}{26.5}
& \result{10.2}{14.8}{5.5}
& \result{35.9}{44.7}{27.0}
& \result{10.2}{14.6}{5.7}
\\
\midrule
\multicolumn{5}{l}{\textbf{\em{\textsc{gold-comment} track}}: Question$\oplus$Comment} \\
~~Dedicated
& \result{\textbf{44.8}}{51.7}{\textbf{37.8}}
& \result{\textbf{24.0}}{30.0}{\textbf{17.9}}
& \result{\textbf{42.9}}{47.7}{\textbf{38.0}}
& \result{\textbf{19.5}}{22.9}{\textbf{16.1}}
\\
~~Unified
& \result{43.3}{\textbf{53.4}}{33.2}
& \result{21.5}{\textbf{30.9}}{12.0}
& \result{40.3}{\textbf{49.2}}{31.4}
& \result{18.2}{\textbf{25.9}}{10.4}
\\
\midrule
\multicolumn{5}{l}{\textbf{\em{Main track}}: Question + c-REALM} \\
~~Dedicated
& \result{37.9}{49.1}{26.6}
& \result{18.5}{28.2}{8.7}
& \result{35.4}{45.9}{24.9}
& \result{14.9}{22.6}{7.1}
\\
~~Unified
& \result{40.1}{49.4}{30.7}
& \result{19.5}{28.8}{10.1}
& \result{37.4}{46.3}{28.4}
& \result{16.0}{23.6}{8.3}
\\
\bottomrule
\end{tabular}\vspace{-.1em}
\caption{Baseline results in the \textbf{writing subtask}, on the development data and the test data, respectively. We report unigram F1 (uF1) and BLEU.
P, C and A indicate Presupposition, Correction, and Average between two.
}\label{tab:results-writing-task}
\end{table*}
\subsection{Baselines}\label{subsec:writing-subtask-baselines}
For the writing subtask, the system is given a question that is guaranteed to contain a false presupposition, and is required to generate the presupposition as well as the correction.
\subsubsection{\textsc{gold-comment} track\ baselines}\label{subsec:gold-comment-writing-baselines}
\paragraph{Copy baseline.} As a trivial baseline, we copy the given question as a presupposition and the given comment as a correction.
\vspace{-.3em}
\paragraph{Question$\oplus$Comment Dedicated.}
We train two generators separately to generate the presupposition and the correction, respectively, given a concatenation of the question and the comment.
Both models are based on the pretrained T5-base model ~\citep{2020t5}.
\vspace{-.3em}
\paragraph{Question$\oplus$Comment Unified.}
While having two dedicated models is a straight-forward way to produce two writings, we design a unified model that can be used for both the presupposition and the correction, motivated by the intuition that generation of each can benefit from each other.
We train one generator that is essentially to generate the correction. Specifically, the model is trained with a union of (1) annotated corrections, and (2) annotated presuppositions
prepended with ``It is not the case that'' so that they look like corrections.
At inference time, we use a standard, beam search decoding to generate the correction. To generate the presupposition, we first decode a sequence with a constraint~\citep{decao2020autoregressive} that it should start with ``It is not the case that'', and then take the sequence that comes next as a presupposition.
\subsubsection{Main track baselines}\label{subsec:main-writing-baselines}
We design \textbf{c-REALM + MP (Multi-Passage) Dedicated} and \textbf{c-REALM + MP (Multi-Passage) Unified}. They are similar to the dedicated and unidifed models in Section~\ref{subsec:gold-comment-writing-baselines}.
The only difference is that the model receives a question and a set of $k$ passages from c-REALM instead of a question-comment pair.
In order for the T5 model to read multiple passages,
we use the Fusion-in-Decoder architecture~\citep{izacard-grave-2021-leveraging}. We refer to Appendix~\ref{app:model-details} for more details.
\begin{table}[!t]
\centering \footnotesize
\begin{tabular}{lR{0.7cm}R{0.7cm}R{0.7cm}R{0.7cm}}
\toprule
Model & F & P & \textsc{Cr} & \textsc{Cs} \\
\midrule
\multicolumn{5}{l}{\textbf{\em{\textsc{gold-comment} track}}: Question + Comment} \\
~~Dedicated & 2.9 & 1.8 & 1.9 & 1.6 \\
~~Unified & 3.0 & 2.0 & 0.8 & 2.8 \\
\midrule
\multicolumn{5}{l}{\textbf{\em{Main Track}}: Question + c-REALM} \\
~~Dedicated & 2.8 & 1.8 & 0.6 & 1.6 \\
~~Unified & 3.0 & 1.8 & 0.6 & 2.8 \\
\midrule
\textbf{\em{Groundtruth}} & 2.9 & 2.8 & 2.7 & 2.9 \\
\midrule
\textbf{Agreement (\%)} & 96.3 & 65.4 & 63.0 & 74.8 \\
\bottomrule
\end{tabular}\vspace{-.1em}
\caption{Human evaluation results (scale: 0--3). F: Fluency, P: Presupposition, \textsc{Cr}: Correction, \textsc{Cs}: Consistency.
The last row reports the inter-annotator agreement rate.
}\label{tab:human-eval-results-writing-task}
\end{table}
\subsection{Results: Automatic Evaluation}\label{subsec:writing-subtask-results}
Table~\ref{tab:results-writing-task} reports the results. Examples of model outputs are provided in Appendix~\ref{app:writing-subtask-details}.
For \textsc{gold-comment} track, the dedicated model gives the best result across all metrics except unigram F1, outperforming the copy baseline and the unified model.
On the other hand, for the main track, the unified model outperforms the dedicated model.
We think this is because when the comment is given, finding the presupposition from the question and the correction from the comment in isolation is sufficient; however, in the main track where the comment is not given, the model benefits from multi-task learning.
For both tracks, models are better in writing presuppositions than writing corrections,
likely because the presupposition can often be extracted from the question alone, while the correction needs more comprehensive understanding of both the question and the comment, or an extra information from retrieval.
Although performance on presupposition identification is similar in the \textsc{gold-comment} track\ and in the main track, correction performance is significantly higher in the \textsc{gold-comment} track. We think it is because retrieving evidence passages that contain correction of the false presupposition is challenging, as discussed in Section~\ref{subsec:detection-subtask-results}.
\subsection{Results: Human Evaluation}\label{subsec:writing-subtask-human}
To augment the automatic metrics, we conduct human evaluation of model generations of 200 randomly sampled test instances from 4 aspects: fluency, presupposition, correction and consistency.
\vspace{-.8em}
\begin{itemize}[leftmargin=1.3em]
\setlength\itemsep{-0.1em}
\item \textbf{Fluency}: The generated text should be fluent (i.e., free of grammatical errors, spelling errors, and repetitions).
\item \textbf{Presupposition}: The generated presupposition should be the valid one in the question, and is factually false.
\item \textbf{Correction}: The correction should be made in the comment and provide reasonable amount of justification rather than being a simple negation of the presupposition.
\item \textbf{Consistency}: The presupposition and correction should be on the same topic and %
negate each other.
\end{itemize}
Each aspect is rated in the 0--3 scale.
We evaluate the output from all systems except the copying baseline, as well as the ground truth reference.
Each question is assigned two raters in order to reduce noise and report inter-rater agreement on pairwise comparison.
More details about the rating scheme are provided in Appendix~\ref{app:writing-subtask-details}.
Table~\ref{tab:human-eval-results-writing-task} reports the result of human evaluation.
All model can generate almost flawless fluent text, and generate presuppositions that are valid ones.
However, their outputs generated as false presuppositions are factually correct in half of the cases.
These observations are relatively consistent across different systems.
Notable differences between systems are found in correction and consistency. The dedicated model generates better correction, likely because it is given a comment. All other models struggle: in particular, the unified models tend to generate the correction that starts with ``It is not the case that'' even the model is not restricted to do so at inference time.
On the other hand, the unified model is better in consistency, likely because the dedicated model is more vulnerable in generating the presupposition and the correction in a totally different topic.
\section{Details in Data Source}\label{app:data-source-details}
\paragraph{Filtering Data Sources.}
When the question has several comments, we choose the comment with the highest upvotes.
To remove toxic language on the data, we follow the toxicity word list from \citet{cachola-etal-2018-expressively} to remove questions that contain any of the toxic words, except ``hell'' and ``damn'', as these two words are commonly used as interjections. %
\paragraph{Analysis in Train-Test Overlap.}
\citet{krishna-etal-2021-hurdles} reported that 81\% of the validation questions of the original ELI5 dataset are paraphrases of the question on the training set. We revisit this issue, and show with a careful assessment of underlying assumptions and a finer-grained definition of ``paraphrases'', the proportion of paraphrased questions is significantly smaller.
We assess 104 randomly sampled questions in the validation set with their closest 7 training questions retrieved using c-REALM, as \citet{krishna-etal-2021-hurdles} did, but with a different rating scale (1--4), following \citet{bhagat-hovy-2013-squibs}, \citet{ganitkevitch-etal-2013-ppdb}, and \citet{pavlick-etal-2015-ppdb}:
\vspace{-.2em}
\begin{itemize}[leftmargin=1.3em]
\setlength\itemsep{-0.1em}
\item \textbf{1: No Paraphrase; No similar intention}: Two questions do not share the meaning nor the intention.
\item \textbf{2: No Paraphrase; Similar intention}: Two questions are likely to have the same intention, but they are not paraphrases, because their literal meanings are different and/or their underlying assumptions are different.
\item \textbf{3: Non-trivial paraphrase:}
Most of the two questions' meanings are the same; however, they do not belong to any of lexical paraphrase (single word to single word), phrasal paraphrase (multiword to single/multiword), or syntactic paraphrase (paraphrase rules containing non-terminal symbols),\footnote{Definition derived from \citet{ganitkevitch-etal-2013-ppdb}.} and require non-trivial background knowledge to identify whether they have the same meaning.
\item \textbf{4: Paraphrases}: Two questions fall into either lexical paraphrase, phrasal paraphrase, syntactic paraphrase, structured paraphrase, or other trivial paraphrase.
\end{itemize}
Table~\ref{tab:paraphrase} presents the percentage and an example of each category. 76.9\% questions have a rating of 2 or less, indicating that for most validation question, there are either no similar intention question in the training set, or there are questions with similar intention but either their literal meanings are different or their underlying assumptions are different. In particular, the latter indicates that whether or not there is a false presupposition can be different, even though they may share similar intention.
Only 23.1\% questions have a rating of 3 and above, indicating that relatively few questions in the validation set have a non-trivial or trivial paraphrase in the training set.
We also explored automatically filtering paraphrased questions using BLEU or TF-IDF. However, we find it is non-trivial to find the right threshold, thus include all questions and leave filtering to future work.
\begin{table}[!t]
\centering \footnotesize
\begin{tabular}{lp{0.3\textwidth}}
\toprule
\textbf{1} (45.2\%) & \textbf{\em{Dev}}: Why are aluminium alloys difficult to weld? \\
&\textbf{\em{Train}}: Cold welding. Two pieces of metal touch in a vacuum, why do they stick together? How strong is this weld? \\
\midrule
\textbf{2} (31.7\%) & \textbf{\em{Dev}}: How is blood after a transfusion integrated into the body, especially when the transfused RBCs carry different DNA than the host RBCs? \\
&\textbf{\em{Train}}: How DNA from blood is changed when getting a blood transfusion\\
&\colorbox{pink!70}{\textbf{\texttt{comment}}}\ %
The dev question assumes that the transfused RBCs carry DNA, while the train question does not.
\\
\midrule
\textbf{3} (6.7\%) & \textbf{\em{Dev}}: How is information retained in solid-state memory devices after power is turned off?\\
&\textbf{\em{Train}}: How do electronics keep memory after you take all power sources away?\\
& \colorbox{pink!70}{\textbf{\texttt{comment}}}\ It is not trivial that ``information retained in solid-state memory devices'' is a paraphrase with ``electronics keep memory''. \\
\midrule
\textbf{4} (16.3\%) &\textbf{\em{Dev}}: What is the difference between centrifugal and centripetal force? \\
&\textbf{\em{Train}}: The difference between centrifugal force and centripetal force.\\
\bottomrule
\end{tabular}
\caption{The rating scale for paraphrase and examples for each category.
}\label{tab:paraphrase}
\end{table}
\section{Details in Data Annotation}\label{app:data-annotation-details}
The annotation instruction is in Figure \ref{fig:instruction}, and we show an example of the annotation interface in Figure \ref{fig:interface}.
\begin{figure*}[t]
\includegraphics[width=\textwidth, keepaspectratio]{figures/instruction.png}\vspace{-.1cm}
\caption{
The instruction we provided for our qualification task.
}\label{fig:instruction}
\end{figure*}
\begin{figure*}[t]
\includegraphics[width=\textwidth, keepaspectratio]{figures/screenshot.png}\vspace{-.1cm}
\caption{
An example of our designed annotation interface.
}\label{fig:interface}
\end{figure*}
\paragraph{Qualification Task.} The qualification task contains 20 pre-annotated questions by the authors, and we provide examples as well as their explanation to workers to demonstrate our task. Based on both whether the worker can correctly identify false presupposition and the writing quality, we selected 30 qualified workers.
\paragraph{Generation Task.} Qualified workers who passed the qualification task work on the main annotation task. Each question is assigned to two generators who independently annotate the label.
We monitor the agreement of workers and send the disagreed cases to further validate. We revoke qualification of generators whose more than 10\% of annotations marked to be invalid by the validators.
\paragraph{Validation Task.}
If two generators disagree on the label, their annotations are sent to two validators who judge their validity.
We select a smaller number of high qualified workers who have exceptional understanding of false presuppositions and are active users of Reddit.
We find that for a small number of highly ambiguous cases, two validators have disagreement. In this case, we send the question to a third validator and take the majority vote.
\vspace{.4em}
Generators and validators are paid with reasonable hourly wage (13 USD/hour and 18 USD/hour, respectively).
\section{Details in Experiments}\label{app:exp-details}
\subsection{Model details}\label{app:model-details}
\paragraph{Retrieval model.}
We use the English Wikipedia from 08/01/2019 provided by \citet{petroni-etal-2021-kilt}.
We obtain c-REALM embeddings of Wikipedia passages as well as the questions.
We use FAISS~\citep{johnson2019billion} to do approximate maximum inner product search to retrieve the top-5 passages for the query.
\paragraph{Classifier model.}
For all the models in the \textsc{gold-comment} track\ track, we use a per GPU batch size of 2, and for all the models in the main track, we use the top-5 passages as the context and a per GPU batch size of 8. We train all our model with learning rate $10^{-5}$, weight decay of 0, and maximum sequence length of 256. We train all our models for 5000 steps and a gradient accumulation step of 5.
All experiments were done with two Nvidia-RTX6000 GPUs (the detection subtask) or two Nvidia-A40 GPUs (the writing subtask).
We use half-precision training~\citep{micikevicius2018mixed} when training for our detection task and gradient checkpointing from fairscale~\citep{FairScale2021}, and choose the best checkpoint based on the performance on the validation set and report its test set performance. For the unified models for the writing subtask, we choose the best checkpoint that gives the best BLEU score for presupposition.
\subsection{Error analysis on the detection subtask}
\label{app:error-analysis}
\begin{table}[!t]
\centering \footnotesize
\begin{tabular}{p{1.5cm}p{2.8cm}|rr}
\toprule
\multicolumn{2}{c}{Error Type} & FP(\%) & FN(\%) \\\midrule
\textbf{Retrieval} & No related topic & 26 & 32\\
& Similar topic but not enough to make decision & 20 & 40\\
& Indirect evidence and require reasoning & -- & 12\\\midrule
\textbf{Classification} & Direct evidence & 34 & 10\\\midrule
\textbf{Labeling} & Ground truth label is wrong & 8 & 8 \\\midrule
\textbf{Inherent Disagreement} & Ambiguity & 4 & 2 \\
& Criticalness & 2 & 0\\\midrule
\textbf{Inconsistency} & Information on the web being inconsistent & 10 & 4 \\%Comment
\bottomrule
\end{tabular}
\caption{The breakdown analysis of false positive/false negative in the validation set for c-REALM + MP classifier model. FP: False positive. FN: False negative. \texttt{FP}~: False Presupposition. ``Indirect evidence and require reasoning'' can also belong to retrieval error. Information on the web being inconsistent: the comment contradicts with the retrieved passages. The categories are \textit{not} mutually exclusive.
}
\label{tab:detection-retrieval-error-analysis}
\end{table}
We conduct error analysis of predictions from c-REALM + MP classifier in the detection subtask.
The authors annotate 50 false positive instances and 50 false negative instances on the validation set, sampled uniformly at random, and categorize the cause of errors.
Results are reported in in Table \ref{tab:detection-retrieval-error-analysis}.
Overall, most errors are due to failure in retrieval---although the model often successfully retrieves passages that are on right topic, it fails to retrieve passages that contain enough information about whether the backgrounded presuppositions are true or false. This issue is more prominent in false negatives, likely because finding that the presupposition is true requires significantly more exhaustive search than noticing that the presupposition is false (since in most cases, whether the presupposition is correct is not explicitly mentioned).
Secondly, there are 8\% cases of labeling error in false positive cases. Note that for false positive cases, we did not distinguish between direct evidence and indirect evidence because there is no clear definition of ``evidence'' for non~\texttt{FP}~cases.
For false negative cases, if there is a retrieved passage that can directly \textit{answer} the question but the model fails in labeling, we consider this as a classification error rather than retrieving error, because the goal for retrieval is to retrieve passages that could give the answer to the question. The model also suffers more to classify given indirect evidence that requires reasoning, which matches our intuition.
Inherent disagreement and inconsistency issues contribute to the rest of the errors. We found that minor part (4\%, 2\% for false positive and false negative cases, respectively) of the error due to the inherent disagreements in labeling ambiguity. We also found that 2\% of the false positive errors are due to whether the \texttt{FP}~is critical to satisfy users information need based on the question. Furthermore, we also found that 14\% of the errors are due to the comment and the retrieved passages are not inconsistent, causing label mismatch, however, they are not a labeling error because our ground truth annotator is not presented with additional passages when annotating. Example of these inconsistencies can be found in Table \ref{tab:retrieval-inconsistencies-examples}.
\begin{table}[!t]
\centering \footnotesize
\begin{tabular}{p{0.47\textwidth}}
\toprule
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ Why aren’t helicopters used to rescue hikers and remove bodies from Mt. Everest?\\
\colorbox{pink!70}{\textbf{\texttt{C}}}\ The air in too thin and they can't fly that high up. They create lift by pushing air downwards. The higher up you go, the less air pressure you have, the less downward force a helicopter can make to fight gravity.\\
\textit{\textbf{Retrieved Passage}}: In 2016 the increased use of helicopters was noted for increased efficiency and for hauling material over the deadly Khumbu icefall. In particular it was noted that flights saved icefall porters 80 trips but still increased commercial activity at Everest...\\
\textit{\textbf{Original Label}}: No \texttt{FP}.\\
\textit{\textbf{Model Prediction}}: \texttt{FP}.\\
\colorbox{pink!70}{\textbf{\texttt{comment}}}\ Helicopter is used to rescue people from Mt. Everest according to the passages, but the comment does not point this \texttt{FP}~out.\\
\midrule
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ How does alcohol effect blood sugar in people with Diabetes?\\
\colorbox{pink!70}{\textbf{\texttt{C}}}\ ...\textbf{Short answer: straight alcohol doesn’t affect me at all (vodka, whiskey, etc).} I can drink without any noticeable effect on my blood sugar levels (and I have a continuous glucose monitor so I can literally see the effect or lack thereof)...\\
\textit{\textbf{Retrieved Passage}}:The intake of alcohol causes an initial surge in blood sugar, and later tends to cause levels to fall. Also, certain drugs can increase or decrease glucose levels...\\
\textit{\textbf{Original Label}}: \texttt{FP}.\\
\textit{\textbf{Model Prediction}}: no \texttt{FP}.\\
\colorbox{pink!70}{\textbf{\texttt{comment}}}\ The comment says that straight alcohol does not affect blood sugar change, but the retrieved passage says otherwise. \\
\bottomrule
\end{tabular}
\caption{Inconsistencies between comment and retrieved passages by c-REALM from Wikipedia.
}\label{tab:retrieval-inconsistencies-examples}
\end{table}
\subsection{Discussion on inherent ambiguity and inconsistency on the web}
\label{app:analysis-human-errors}
\begin{table*}[!t]
\centering \footnotesize
\begin{tabular}{p{0.45\textwidth}}
\toprule
\multicolumn{1}{c}{\textbf{Inherent disagreement: Ambiguity}}\\
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ How are paintings or museum art classified as masterpieces? Some look like paint scratches and yet they are classics. Why is that?\\
\colorbox{pink!70}{\textbf{\texttt{C}}}\ Great art isn’t just technical skill. Though a lot of those paintings that may look easy usually aren’t. But it’s also about having an original idea and expressing yourself in a way the world hasn’t seen before. (...)\\
\colorbox{pink!70}{\textbf{\texttt{comment}}}\ Whether the question made the implicit presupposition that a painting or an art is considered a masterpiece only depends on the technical skill exist in the question is debatable before looking at the comment. \\\\
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ Why is Hydrogen so common on Earth and Helium quite rare?\\
\colorbox{pink!70}{\textbf{\texttt{C}}}\ Hydrogen is highly reactive, it bonds to oxygen, forming water. Water is quite dense, even as a vapor, and is therefore quite durable in the atmosphere. Helium is a noble gas and nearly perfectly inert. Being unbound to any heavier elements, it quickly rises to the top of the atmosphere and is lost to space by various mechanisms. Hydrogen is lost over time, but only slowly.\\
\colorbox{pink!70}{\textbf{\texttt{comment}}}\ There is an \texttt{FP}~if the question is asking about hydrogen gas, as indicated by \href{https://www.nationalgrid.com/stories/energy-explained/what-is-hydrogen}{this webpage} that hydrogen gas is very rare on earth. However, if they are asking about hydrogen atom, then there is no \texttt{FP}.\\
\midrule
\multicolumn{1}{c}{\textbf{Inherent disagreement: Criticalness}}\\
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ Why do things look darker when wet?\\
\colorbox{pink!70}{\textbf{\texttt{C}}}\ You know how when you vacuum the floor it makes those different colored lines? If you look closely the darker colored parts of the carpet are laying down and the lighter colored parts are standing up. Many things that are dry have little hairs or rough surfaces that are basically standing up like little mirrors to reflect light. When these get knocked over or filled with water they can't reflect as well. A couple of damp riddles 1. What gets wetter as it dries 2. What gets darker as it dries Hint: An owlet and naipt\\
\bottomrule
\end{tabular}\vspace{-.1em}
\begin{tabular}{p{0.45\textwidth}}
\toprule
\multicolumn{1}{c}{\textbf{Information on the web being inconsistent}}\\
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ Why do 78\% of Americans live paycheque to paycheck?\\
\textit{\textbf{\href{https://www.cnbc.com/2022/06/27/more-than-half-of-americans-live-paycheck-to-paycheck-amid-inflation.html}{News on 06/07/2022}}}: 58\% Americans are living paycheck to paycheck.\\
\textit{\textbf{\href{https://www.forbes.com/sites/zackfriedman/2019/01/11/live-paycheck-to-paycheck-government-shutdown/?sh=e6204954f10b}{News on 01/11/2019}}}: 78\% Americans are living paycheck to paycheck.\\\\
\colorbox{blue!30}{\textbf{\texttt{Q}}}\ Why do pandas eat bamboo and when did they stop eating meat?\\
\colorbox{pink!70}{\textbf{\texttt{C}}}\ Everyone so far has gone with the "pandas are so dumb" response so let me give you a proper answer. For a start, evolution is not a intelligent or forward thinking process. Bamboo may be low in energy, but it is abundant, grows quickly and not many other animals eat it. So for any animal that can evolve to consume it, there's an open niche there to be taken. Now I'll admit pandas aren't the best creature at surviving, but they don't really need to be. They live in an environment with abundant food and no predators or competitors, so all they need to do is sit around eating bamboo, expend minimal energy and produce just enough babies to keep the species going. Now that might not seem very efficient from a human perspective, but actually it's a strategy that works surprisingly well, and pandas were doing absolutely fine until humans came along and started hunting them and destroying their habitat.\\
\textbf{\href{https://wwf.panda.org/discover/knowledge_hub/endangered_species/giant_panda/panda/what_do_pandas_they_eat/}{WWF:}} But they do branch out, with about 1\% of their diet comprising other plants and even meat. While they are almost entirely vegetarian, pandas will sometimes hunt for pikas and other small rodents.\\
\textbf{\href{https://www.science.org/content/article/how-pandas-survive-their-bamboo-only-diet}{Science:}} Pandas are one of the world's most fascinating vegetarians. Their digestive systems evolved to process meat, yet they eat nothing but bamboo—all day, every day. A new study reveals how these animals survive on a diet that should kill them.\\
\bottomrule
\end{tabular}\vspace{-.1em}
\caption{Inconsistencies and inherent ambiguity examples for human performance.
}\label{tab:inconsistencies-examples}
\end{table*}
Table \ref{tab:inconsistencies-examples} display examples for the category ``Inherent disagreement: ambiguity'', ``Inherent disagreement: criticalness'', and ``Information on the web being inconsistent'' from the human evaluation section of Section \ref{subsec:detection-subtask-results} and in Table \ref{tab:human-perf-detection-task}.
9.1\% of the errors is due to the inherent ambiguity of the criticalness of the \texttt{FP}, i.e., whether correcting the \texttt{FP}~is critical to satisfy users' information needed. For example, for the question ``Why do things look darker when wet?'' in Table \ref{tab:inconsistencies-examples}, although our human rater found \href{https://paintinggal.com/does-paint-dry-darker-or-lighter-what-you-need-to-know/}{evidence on the internet} that there exist things that look darker when dry, which would contradict the presupposition that (all) things look darker when wet, we believe that the question writer is mainly seeking an answer for the reason of the phenomenon that something looks darker when they are wet, and therefore, such \texttt{FP} is not critical to answer the users original question, and therefore the comment writer does not point it out.
Note that this is different than the ``exception'' examples mentioned in Table \ref{tab:data-analysis}, as the comment explicitly pointed out the falsehood of the presupposition, and therefore we consider the \texttt{FP}~as critical to answer the user's information seeking need.
Furthermore, 22.7\% of the errors in human performance is due to information on the web being inconsistent. For the question ``why do 78\% of Americans live paycheque to paycheck?'', \href{https://www.cnbc.com/2022/06/27/more-than-half-of-americans-live-paycheck-to-paycheck-amid-inflation.html}{News on 06/07/2022} points out that 58\% Americans lives paycheck to paycheck, while \href{https://www.forbes.com/sites/zackfriedman/2019/01/11/live-paycheck-to-paycheck-government-shutdown/?sh=e6204954f10b}{News on 01/11/2019} pointed out that 78\% of Americans live paycheck to paycheck. For the question ``why do pandas eat bamboo and when did they stop eating meat?'', creditable sources such as World Wide Fund(WWF) and Science says differently about whether panda eat meat or not.
34.1\% of the errors are due to ambiguity, as analyzed in Section~\ref{subsec:data-analysis}.
\begin{table*}[!t]
\centering \footnotesize
\begin{tabular}{p{0.99\textwidth}}
\toprule
\multicolumn{1}{c}{\colorbox{gray!30}{\textbf{\texttt{Inputs given to the human raters}}}
} \\
\textbf{\em{Question:}} Why do prosecuters/courts seek/sentence prison time greater than the expected lifespan of the offender (i.e. 150 years in prison)? Why not simply sentence those criminals to 'life' in prison instead?\\
\textbf{\em{Comment:}} Sentencing options are written into state laws. Life in prison is different in state laws than 150 years. Some of it comes into play with the "cruel and unusual punishment" clause in the Constitution too. Life in prison may not be ``cruel and unusual'' for a murder sentence, but it might be for, say, child sex trafficking. But if you trafficked 10 kids and the sentence is 15 years for each one, you get an effective life sentence that will also stand up, Constitutionally, against a ``cruel and unusual punishment'' defense.\\
\midrule
\multicolumn{1}{c}{\colorbox{gray!30}{\textbf{\texttt{Outputs human raters rate}}}
} \vspace{.3em} \\
\multicolumn{1}{c}{\textbf{Reference}} \\
\textbf{\em{Presupposition:}} It does not make sense to sentence a person to 150 years in prison if they can't live that long anyways, prosecutors should use the life in prison sentence instead.\\
\textbf{\em{Correction:}} The defendant can argue the life in prison sentence as cruel and unusual, so the actual year sentence is better to give than the alternative. \vspace{-.3em} \\
\multicolumn{1}{c}{\textbf{\textsc{gold-comment} track, Dedicated}} \\
\textbf{\em{Presupposition:}} Penalties should be able to be sentenced to life in prison.\\
\textbf{\em{Correction:}} Life in prison is different in state laws than 150 years in prison. \\
\multicolumn{1}{c}{\textbf{\textsc{gold-comment} track, Unified}} \\
\textbf{\em{Presupposition:}} If a criminal is sentenced to life in prison, they should be sentenced to life in prison.\\
\textbf{\em{Correction:}} It is not the case that if a criminal is sentenced to life in prison, they should be sentenced to life in prison. \\
\multicolumn{1}{c}{\textbf{Main, Dedicated}} \\
\textbf{\em{Presupposition:}} Penalties should be able to be imposed on criminals for life.\\
\textbf{\em{Correction:}} The longer the sentence, the more likely the prosecution will seek to sentence the offender to life in prison. \\
\multicolumn{1}{c}{\textbf{Main, Unified}} \\
\textbf{\em{Presupposition:}} Prosecutor's should seek prison time greater than the expected lifespan of the offender.\\
\textbf{\em{Correction:}} It is not the case that prosecutor's should seek prison time greater than the expected lifespan of the offender.\\
\bottomrule
\end{tabular}
\caption{An example of the input and the output human raters are given for the human evaluation of the writing subtask. Note that human raters are not given which output is a reference or from which system.
}\label{tab:writing-examples}
\end{table*}
\subsection{Details of the writing subtask}
\label{app:writing-subtask-details}
Example generations from each system are shown in
Table~\ref{tab:writing-examples}.
As we discuss in Section~\ref{subsec:writing-subtask-results}, the unified model strongly prefers to generate the correction with prefix ``It is not the case that'' even though we do not restrict it to do so at inference time.
\paragraph{Details in Human Evaluation.}
We conduct human evaluation for 200 questions on the test data.
We recruit two student evaluators, who independently evaluate the presupposition and the correction given a question and its comment.
They evaluated five outputs, including the reference in the data as well as generations from four systems in Section~\ref{subsec:writing-subtask-baselines}: the dedicated and the unified model from the \textsc{gold-comment} track\ and the main track, respectively.
We design detailed evaluation scheme, hold a 1 hour in-person tutorial session for human evaluators to be familiarized with the evaluation task. %
In particular, each output is rated based on four aspects as follows.
\vspace{.5em}
\textbf{Fluency} measures the fluency of the generated text, mainly whether it have repetitions, spelling errors or grammatical errors, or gibberish. %
\vspace{-.3em}
\begin{itemize}%
\setlength\itemsep{-0.1em}
\item[\textbf{0:}] Generated text have fluency errors.
\item[\textbf{3:}] Generated text is free of fluency errors.
\end{itemize}
\vspace{.1em}
\textbf{Presupposition} evaluates whether the generated presupposition is the valid one in the question and whether it is factually false according to the comment.
\vspace{-.3em}
\begin{itemize}%
\setlength\itemsep{-0.1em}
\item[\textbf{0:}] The presupposition is invalid, i.e., does not exist in the question.
\item[\textbf{1:}] The presupposition is valid, e.g., exists in the question, but it is not factually false.
\item[\textbf{3:}] The presupposition is valid and is factually false.
\end{itemize}
\vspace{.1em}
\textbf{Correction} evaluates whether the generated correction provides the valid correction to the presupposition based on the comment with no hallucinated information, and provide enough justification (rather than simply being a negated presupposition). The former considers correctness (precision of the information), while the latter considers adequacy (recall of the information)
\vspace{-.3em}
\begin{itemize}%
\setlength\itemsep{-0.1em}
\item[\textbf{0:}] The correction is wrong based on the comment, or the correction is hallucinated.
\item[\textbf{1:}] The correction is correct based on the comment, but no additional information is provided to justify, or is a simple negation of the presupposition.
\item[\textbf{2:}] The correction is correct based on the comment, but misses some details to fully justify the falsehood of presupposition.
\item[\textbf{3:}] The correction is correct and provide enough information to justify the falsehood of presupposition.
\end{itemize}
\vspace{.1em}
\textbf{Consistency} requires the generated assumption and correction should be on the same topic and negate each other. %
\vspace{-.3em}
\begin{itemize}%
\setlength\itemsep{-0.1em}
\item[\textbf{0:}] The presupposition and correction are not about the same topic.
\item[\textbf{1:}] The presupposition and correction are on the same topic, but they are not negating each other, or the negation is not explicit.
\item[\textbf{3:}] The presupposition and correction are consistent: are on the same topic and negate each other.
\end{itemize}
The evaluators are paid with 17 USD/hour.
See Section~\ref{subsec:writing-subtask-human} for the results and discussion.
| {'timestamp': '2022-12-01T02:21:39', 'yymm': '2211', 'arxiv_id': '2211.17257', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17257'} | arxiv |
\section{Introduction}
It is now well-known that neural network models can be vulnerable
to adversarial perturbations, which are small, often imperceptible
changes to the input that cause large, possibly targeted changes to
the output~\citep{Szegedy2014intriguing,biggio2013evasion}. To make
models robust to adversarial perturbation attacks, one popular strategy,
known as \emph{adversarial training}~\citep{kurakin2016adversarial,goodfellow2015explaining,madry2017towards,shafahi2019adversarial,wong2019fast},
is to attack a pre-trained model, and then to re-train the model with
the training set augmented or replaced by the attack. Despite its
simplicity, adversarial training works remarkably well in practice.
For example, the robust models trained by \citet{madry2017towards}
back in 2017 remain essentially unbroken in 2022, after more than
four years of white-box penetration testing by researchers world-wide.
Later researchers have extended the idea to train robust ImageNet
classifiers, that achieve a similar level of accuracy, and within
a comparable amount of training time, to nonrobust classifiers~\citep{shafahi2019adversarial,wong2019fast}.
Unfortunately, adversarial training is, in the end, an empirical strategy,
that does not rigorously promise a truly robust model. Its use leaves
open the possibility---however remote and unlikely---that a model
that was previously thought to be robust would later be defeated by
a more sophisticated attack, potentially after it has already been
deployed out in the field.
For applications where even a single failure is deemed unacceptable,
one often desires a formal mathematical proof or \emph{certification}
that an empirically robust model is truly robust against all future
attacks. Most certification methods are based on a classical technique
from optimization known as \emph{convex relaxation}. The idea is to
take the nonconvex set of viable attacks, and relax it into a larger,
convex set of attacks, some (or almost all) of which may not be physically
realizable. Irrespective of physical realizability, one can ``efficiently''
verify---i.e. in polynomial time---whether the model is truly robust
against the entire convex superset of attacks. If this is indeed the
case, then it immediately follows that the model is certifiably robust
against all viable attacks, since these constitute a subset of the
convex superset of attacks. However, if the model is not robust against
the convex superset, then we must decline to make a certification.
It may be the case that the model is not robust due to the existence
of a viable attack. Or, the model may in fact be robust, but there
exists a ficticious, non-physically-realizable attack within the convex
superset that prevents us from certifying this fact.
Most state-of-the-art certification techniques~\citep{tjeng2017evaluating,weng2018towards,weng2018evaluating,zhang2018crown}
are based on a triangle-shaped linear programming (LP) relaxation
of the ReLU activation introduced by \citet{wong2018provable}. While
the LP relaxation is \emph{exact} for a single ReLU activation (i.e.
it makes a certification if and only if there exists a viable attack),
it quickly becomes loose as more activations are added, and as the
attack budget is increased. Recent results by \citet{salman2019convex}
indicate the existence of ``convex relaxation barrier'' for the
LP relaxation. Every certification technique based on the LP relaxation
is inherently limited to being a factor of 1.5 to 2 times more conservative
for shallow model with 1-2 layers, and up to 10 times more conservative
for a deeper model with 9 layers.
One promising pathway for overcoming the convex relaxation barrier
faced by the LP relaxation is the semidefinite programming (SDP) relaxation
of \citet{NIPS2018_8285}. Empirically, the SDP relaxation appears
to be much \emph{tighter} than the LP relaxation, in that it is able
exclude far more ficticious attacks that cannot be physically realized.
However, the cost of solving the SDP relaxation---while technically
still polynomial time---is so large as to be completely inaccessible,
even for tiny models with just a few hundred activations. At its core,
the SDP relaxation requires us to optimize over the $\frac{1}{2}n(n+1)$
elements of an $n\times n$ symmetric matrix, where $n$ is equal
to the total number of ReLU activations, plus the dimension of the
input layer. Even a single-layer model with 200 ReLU activations for
the MNIST dataset would require us to optimize over the $4.84\times10^{5}$
elements of a $984\times984$ symmetric matrix, which is already nearing
the limit of state-of-the-art solvers like MOSEK~\citep{mosek2019mosek}.
\paragraph{Contributions}
This paper proposes a certification technique based on a \emph{nonconvex}
relaxation for the ReLU activation. We argue that the set of viable
attacks is naturally nonconvex, and as such a nonconvex relaxation
should better exclude ficticious attacks when compared to a convex
relaxation of a similar dimension or complexity. We base our nonconvex
relaxation on a \emph{low-rank restriction} of the usual convex SDP
relaxation of the ReLU activation. Rigorously, we show that the nonconvex
relaxation is always at least as tight as the SDP relaxation, but
that it optimizes over the $nr$ elements of an $n\times r$ rectangular
matrix, where $n$ is the same as before in the SDP relaxation, and
$r$ is a relaxation rank parameter. If a small value of $r$ can
be used (in practice, our experiments suggest a value of $r\le10$),
then the nonconvex relaxation enjoys the same tightness and effectiveness
of the SDP relaxation, while optimizing over a dramatically smaller
number of variables that is comparable to the LP relaxation.
The nonconvexity of the relaxation poses a potential issue. Here,
we adopt an approach known as the Riemannian staircase~\citep{boumal2016non,boumal2020deterministic},
which allows nonconvex low-rank SDPs that satisfy a condition known
as linear independence constraint qualification (LICQ) to be solved
to near-global optimality in polynomial time. Unfortunately, LICQ
is highly restrictive and also difficult to verify in practice. It
is often taken as a strong assumption in the existing literature~\citep{rosen2014rise,carlone2015lagrangian,rosen2019se},
but this reduces the Riemannian staircase from a provable algorithm
to an empirical heuristic. In this paper, we rigorously show that the verification problem generically satisfies LICQ. It immediately follows
that our nonconvex relaxation can generically be solved to near-global
optimality in polynomial time.
Our experiments provide empirical confirmation of our theoretical
claims. We re-examine the models originally used by \citet{salman2019convex}
to demonstrate the existence of a ``convex relaxation barrier''
for the LP relaxation. Using a relaxation rank $r$ of no more than
10, we re-certify these models using our nonconvex relaxation, in
time comparable to that of the best-possible LP relaxation. Our results
find that even a basic nonconvex relaxation offers a significant reduction
in conservatism, from factors of 2 to 10 down to a factor of around
1.1. Augmenting the nonconvex relaxation by bound propagation (as
is commonly done for the LP relaxation) allows us to almost fully
close the gap towards exact certification.
\section{Background and related work}
Consider the task of classifying a data point $\hat{x}\in\R^{p}$
as belonging to the $\hat{c}$-th of $q$ classes. The standard approach
is to train a classifier model $f_{\theta}:\R^{p}\to\R^{q}$ with
parameters $\theta$ so that the prediction vector $f_{\theta}(\hat{x})$
takes on its maximum value at the $\hat{c}$-th element, as in $f_{\theta}(\hat{x})[\hat{c}]>f_{\theta}(\hat{x})[c]$
for all incorrect labels $c\ne\hat{c}$. In this paper, we focus our
attention on $\ell$-layer feedforward ReLU-based neural network models,
defined recursively
\begin{equation}
x_{1}\equiv x,\quad f_{\theta}(x)\equiv W_{\ell}x_{\ell}+b_{\ell},\quad x_{k+1}=\max\{0,W_{k}x_{k}+b_{k}\}\quad\text{ for }k\in\{1,2,\dots,\ell\}\label{eq:model}
\end{equation}
with respect to the parameters $\theta=\{W_{k},b_{k}\}_{k=1}^{\ell}$,
which consist of the weights $W_{1},\dots,W_{\ell}$ and the biases
$b_{1},\dots,b_{\ell}$. Throughout the paper, we will use $n_{k}$
to denote the number of neurons at the $k$-th layer, and $n=\sum_{k=1}^{\ell}n_{k}$
to denote the total number of neurons summed over the entire neural
network. Note that our convention includes the neurons at the input
layer, i.e. those taking on values in $x_{1}\equiv x$, but excludes
those at the output layer, i.e. those taking of values of $f_{\theta}(x)\equiv W_{\ell}x_{\ell}+b_{\ell}$.
To compute an adversarial example $x\approx\hat{x}$, the standard
approach (and usually, the most effective approach) is to apply projected
gradient descent (PGD) to the following \emph{semi-targeted attack}
problem, which was first introduced by \citet{carlini2017towards}:
\begin{equation}
\phi[c]=\min_{x\in\R^{p}}\quad f_{\theta}(x)[\hat{c}]-f_{\theta}(x)[c]\quad\text{ s.t. }\quad\|x-\hat{x}\|_{p}\le\rho.\label{eq:attack2}
\end{equation}
Here, the attack budget is controlled by the parameter $\rho$, which
specifies the maximum radius of the adversarial perturbation as measured
in the $\ell_{p}$ norm. The attack is said to be semi-targeted because
it seeks to rank the target class $c$ above the true class $\hat{c}$,
without necessarily requiring the target class $c$ to be the top-ranked class. Nevertheless,
applying PGD to (\ref{eq:attack2}) frequently results in misclassification
to the target class $c$. In fact, for a non-robust model, only a
single PCG iteration is usually enough for targeted misclassification
to occur; the resulting one-iteration attack is called the fast gradient
sign method (FGSM) attack, due to \citet{goodfellow2015explaining}.
Empirically robust models can be obtained by adversarially training
a model against either the FGSM attack (as in \citet{goodfellow2015explaining}
and later \citet{wong2019fast}) or the PGD attack (as in \citet{madry2017towards}
and \citep{shafahi2019adversarial}).
In turn, robustness to adversarial perturbations can be certified
by verifying that (\ref{eq:attack2}) achieves a positive global minimum
$\phi[c]>0$ for every incorrect class $c\ne\hat{c}$. To explain,
recall that $\phi[c]$ denotes the maximum margin by which an attack
can cause the model $f_{\theta}$ to rank the incorrect label $c\ne\hat{c}$
above the true label $\hat{c}$. Clearly, if there exists no attack
capable of ranking any incorrect label $c\ne\hat{c}$ above the true
label $\hat{c}$, then the model is robust. In turn, the numerical
value of the minimum global minimum, written
\begin{equation}
\phi^{\star}=\min_{c\ne\hat{c}}\quad\phi[c]>0,\label{eq:attack1}
\end{equation}
is a \emph{robustness margin} that measures how robust the model is
to adversarial perturbations. The more positive is the robustness
margin $\phi^{\star}$, the more the model is able to resist misclassification.
Unfortunately, it is NP-hard in general to compute the global minimum
$\phi[c]$, and therefore also the robustness margin $\phi^{\star}$~\citep{weng2018towards}.
While stratgies like mixed-integer linear programming (MILP)~\citep{tjeng2017evaluating}
and Satisfiability Modulo Theories (SMT)~\citep{katz2017reluplex}
exist to compute these values exactly, their worst-case run time must
scale exponentially with the number of activations, unless P=NP. Instead,
most certification method rely on solving (\ref{eq:attack2}) subject
to a relaxation of the ReLU activation function in (\ref{eq:model}).
In particular, \citet{wong2018provable} suggested the following triangle-shaped
LP relaxation for a single ReLU activation:
\[
\begin{array}{c}
\beta=\max\{0,\alpha\},\\
\underline{\alpha}\le\alpha\le\overline{\alpha}
\end{array}\quad\implies\quad\begin{array}{c}
\beta\ge0,\qquad\beta\ge\alpha,\\
{\displaystyle \beta\le\frac{\max\{0,\overline{\alpha}\}-\max\{0,\underline{\alpha}\}}{\overline{\alpha}-\underline{\alpha}}}(\alpha-\underline{\alpha})+\max\{0,\underline{\alpha}\}
\end{array}
\]
Extending this relaxation to all ReLU activations across all layers
of a model requires upper- and lower-bounds $\underline{\alpha},\overline{\alpha}$
on each pre-activation variable $\alpha$; recursive bound propagation
procedures have been proposed to compute these efficiently~\citep{weng2018evaluating,weng2018towards,zhang2018crown,salman2019convex}.
Substituting into the semi-targeted attack problem (\ref{eq:attack2})
results in a lower-bound $\phi_{\lb}[c]\le\phi[c]$ for the incorrect
class $c\ne\hat{c}$. In turn, taking the minimum lower-bound $\phi_{\lb}^{\star}=\min_{c\ne\hat{c}}\phi_{\lb}[c]$
among all incorrect classes results a lower-bound $\phi_{\lb}^{\star}\le\phi^{\star}$
on the robustness margin. If $\phi_{\lb}^{\star}>0$, then the model
is robust, and its robustness margin is at least $\phi_{\lb}^{\star}$.
The LP relaxation described above is easily verified to be tight for
a single activation, meaning that it provides a lower-bound $\phi_{\lb}[c]=\phi[c]$
that holds with equality. However, for many single activations, the
relaxation is usually loose, meaning that the lower-bound $\phi_{\lb}[c]<\phi[c]$
is strict. Indeed, \citet{salman2019convex} pointed out that the
lower-bound is loose by a sizable margin, and that this gap cannot
be improved. They refer to the inherent looseness of the LP relaxation
as the ``convex relaxation barrier''.
One promising direction that can potentially overcome the ``convex
relaxation barrier'' is the SDP relaxation of \citet{NIPS2018_8285}.
The relaxation is based the insight that the ReLU activation equation
can be equivalently imposed as two linear inequalities and a single
quadratic equality
\[
\beta=\max\{0,\alpha\}\quad\iff\quad\beta\ge0,\quad\beta\ge\alpha,\quad\beta(\beta-\alpha)=0.
\]
Following a standard approach of \citet{Shor19871}, it follows that
the ReLU activation equation over a single layer can be written as
the following linear inequalities
\begin{gather}
x_{2}=\max\{0,W_{1}x_{1}+b_{1}\}\quad\iff\quad\begin{array}{c}
x_{0}=1,\quad x_{2}\ge0,\quad x_{2}\ge W_{1}x_{1}+b_{1},\\
\diag(X_{22})=\diag(W_{1}X_{12}+b_{1}x_{2}^{T}),
\end{array}\label{eq:onelayer}
\end{gather}
imposed over the following rank-1 matrix variable
\[
X=\left[\begin{array}{c|cc}
x_{0} & x_{1}^{T} & x_{2}^{T}\\
\hline x_{1} & X_{11} & X_{12}\\
x_{2} & X_{12}^{T} & X_{22}
\end{array}\right]\succeq0,\qquad\rank(X)=1.
\]
The nonconvexity of the ReLU activation is entirely captured within
the constraint $\rank(X)=1$. Relaxing this constraint results a convex
relaxation, commonly known simply as ``the'' SDP relaxation.
In their original experiments, \citet{NIPS2018_8285} found that the
simple SDP relaxation described became loose once it is applied to
deeper models containing many layers. This empirical observation was
later rigorously justified by the geometric analysis of \citet{zhang2020tightness}.
Instead, \citet{NIPS2018_8285} proposed a bound propagation procedure---directly
analogous to the LP relaxation---that allows the SDP relaxation to
be tightened for deeper networks.
\section{Rank-constrained SDP relaxation and its dual}
Our goal in this paper is to develop better lower-bounds on the following
instance of (\ref{eq:attack2}):
\begin{alignat}{2}
\phi[c]=\min_{x=(x_{1},\dots,x_{\ell})\in\R^{n}}\quad & w_{\ell}^{T}x_{\ell}+w_{0}\equiv[(\e_{c}-\e_{\hat{c}})^{T}W_{\ell}]x_{\ell}+[(\e_{c}-\e_{\hat{c}})^{T}b_{\ell}] & \tag{A}\label{eq:attack}\\
\text{s.t. }\quad & x_{k+1}=\max\{0,W_{k}x_{k}+b_{k}\}\qquad\text{for }k\in\{1,\dots,\ell-1\}\nonumber \\
& \|x_{1}-\hat{x}\|\le\rho.\nonumber
\end{alignat}
Here, we recall that to lower-bound the robustness margin $\phi_{\lb}^{\star}\le\phi^{\star}$,
it suffices to lower-bound the semi-targeted problem $\phi_{\lb}[c]\le\phi[c]$
for every incorrect class $c\ne\hat{c}$, and then take the minimum
$\phi_{\lb}^{\star}=\min_{c\ne\hat{c}}\phi_{\lb}[c]$ among all incorrect
classes.
Following existing work on the SDP relaxation, we begin by substituting
the rank-1 SDP reformulation of the ReLU activation in (\ref{eq:onelayer})
to the semi-targeted attack problem (\ref{eq:attack}). But instead
of deleting the rank-$1$ constraint altogether, we propose to slightly
relax it to a rank-$r$ constraint, where $r\ge1$ is a \emph{relaxation
rank} parameter, to result in a family of \emph{nonconvex} relaxations
\begin{alignat}{2}
\phi_{r}[c]=\min_{X\in\S^{n+1}}\quad & w_{\ell}^{T}x_{\ell}+w_{0}x_{0} & \tag{SDP-\ensuremath{r}}\label{eq:sdp}\\
\text{s.t. }\quad & \tr(X_{1})-2x_{1}^{T}\hat{x}_{1}+x_{0}\|\hat{x}_{1}\|^{2}\le x_{0}\rho^{2},\qquad x_{0}=1 & \qquad(y_{0},z_{0})\nonumber \\
& x_{k+1}\ge0,\qquad x_{k+1}\ge W_{k}x_{k}+b_{k}x_{0}, & \qquad(y_{k,1},y_{k,2})\nonumber \\
& \diag(X_{k+1}-W_{k}X_{k,(k+1)}-b_{k}x_{k+1}^{T})=0, & (z_{k})\nonumber \\
& \qquad\text{for all }k\in\{1,2,\dots,\ell-1\}\nonumber
\end{alignat}
whose optimization variable $X$ is an $(n+1)\times(n+1)$ rank-constrained
positive semidefinite matrix with bounded trace
\[
X=\left[\begin{array}{c|ccc}
x_{0} & x_{1}^{T} & \cdots & x_{\ell}^{T}\\
\hline x_{1} & X_{1,1} & \cdots & X_{1,\ell}\\
\vdots & \vdots & \ddots & \vdots\\
x_{\ell} & X_{1,\ell}^{T} & \cdots & X_{\ell,\ell}
\end{array}\right]\succeq0,\quad\rank(X)\le r,\quad\tr(X)\le R^{2},
\]
and we will assume throughout the paper that the trace bound $R$
has been chosen large enough so that $\tr(X^{\star})<R^{2}$ holds
at optimality with a \emph{strict inequality}. It follows from (\ref{eq:onelayer})
that $r=1$ instance of (\ref{eq:sdp}) coincides with (\ref{eq:attack})
exactly. Due to our use of a rank upper-bound, every subsequent instance
then provides a lower-bound on its previous relaxation:
\[
\phi[c]=\phi_{1}[c]\ge\phi_{2}[c]\ge\cdots\ge\phi_{n+1}[c].
\]
Finally, setting $r=n+1$ has the same effect as deleting the rank
constraint, because every $(n+1)\times(n+1)$ matrix can have rank
at most $n+1$. Therefore, the $r=n+1$ instance coincides with the
convex semidefinite relaxation as originally proposed by \citep{raghunathan2018certified}.
For relaxation ranks of $r<n+1$, the corresponding nonconvex instances
of (\ref{eq:sdp}) are NP-hard in general to solve to global optimality.
Even if we are provided with a globally optimal solution $X^{\star}$,
there is generally no way to (rigorously) tell that $X^{\star}$ is
indeed globally optimal. Instead, the most we can say is that $X^{\star}$
provides an upper-bound $w_{\ell}^{T}x_{\ell}^{\star}+w_{0}\ge\phi_{r}[c]$
on the optimal value of (\ref{eq:sdp}), which is itself intended
to be a lower-bound $\phi_{r}[c]\le\phi[c]$ on our original problem
of interest (\ref{eq:attack}). Of course, one cannot draw a definitive
conclusion in either direction from an upper-bound on a lower-bound.
Instead, we seek to construct a lower-bound on the optimal value $\phi_{r}[c]$
of the relaxation (\ref{eq:sdp}), which would in turn lower-bound
the optimal value $\phi[c]$ of the original problem (\ref{eq:attack}).
Our motivating insight is that all instances of (\ref{eq:sdp}), including
those nonconvex instances for $r<n+1$, have the \emph{same} convex
Lagrangian dual. Define dual variables $y=(y_{0},\{y_{k,1},y_{k,2}\}_{k=1}^{\ell})$
and $z=(y_{0},\{z_{k}\}_{k=1}^{\ell})$ to correspond to the linear
constraints in (\ref{eq:sdp}) as shown in parentheses. Then, the
dual problem is written:
\begin{equation}
\max_{\begin{subarray}{c}
y\ge0,z,\\
\mu\le0
\end{subarray}}\quad z_{0}+R^{2}\mu\text{ s.t. }S(y,z)\equiv\frac{1}{2}\left[\begin{array}{c|cccc}
s_{0} & s_{1}^{T} & s_{2}^{T} & \cdots & s_{\ell}^{T}\\
\hline s_{1} & S_{1,1} & S_{1,2}\\
s_{2} & S_{1,2}^{T} & S_{2,2} & \ddots\\
\vdots & & \ddots & \ddots & S_{(\ell-1),\ell}\\
s_{\ell} & & & S_{(\ell-1),\ell}^{T} & S_{\ell,\ell}
\end{array}\right]\succeq\mu I,\tag{SDD}\label{eq:sdd}
\end{equation}
in which the components of the slack matrix are written
\begin{gather*}
s_{0}=2\left[w_{0}+y_{0}(\|\hat{x}\|^{2}-\rho^{2})+\sum_{k=1}^{\ell-1}b_{k}^{T}y_{k,2}-z_{0}\right],\\
s_{1}=W_{1}^{T}y_{1,2}-2\hat{x}y_{0},\quad s_{\ell}=w_{\ell}-\left[Z_{(\ell-1)}b_{(\ell-1)}+y_{(\ell-1),1}+y_{(\ell-1),2}\right],\\
s_{k+1}=W_{k+1}^{T}y_{(k+1),2}-\left(Z_{k}b_{k}+y_{k,1}+y_{k,2}\right)\quad\text{for }k\in\{1,\dots,\ell-2\},\\
S_{1,1}=2y_{0}I,\;S_{k,(k+1)}=-W_{k}^{T}Z_{k},\;S_{(k+1),(k+1)}=2Z_{k}\quad\text{for }k\in\{1,\dots,\ell-1\},
\end{gather*}
where $Z_{k}=\diag(z_{k})$ for all $k$. We therefore obtain the
following lower-bound on semi-targeted attack problem in (\ref{eq:attack}),
which is valid for \emph{any} choice of multipliers $y\ge0$ and $z$.
\begin{prop}[Dual lower-bound]
\label{prop:dual}Let $X^{\star}$ denote the global solution of
(\ref{eq:sdp}) with rank $r\ge1$. Then, any dual multipliers $y=(y_{0},\{y_{k,1},y_{k,2}\}_{k=1}^{\ell-1})$
and $z=(z_{0},\{z_{k}\}_{k=1}^{\ell-1})$ that satisfy $y\ge0$ provide
the following lower-bound
\[
\phi[c]\ge\phi_{r}[c]\ge z_{0}+R^{2}\cdot\min\{0,\lambda_{\min}[S(y,z)]\}.
\]
\end{prop}
Let $X^{\star}$ denote the globally optimal solution for the convex
instance of (\ref{eq:sdp}) with $r=n+1$. It turns out that \emph{strong
duality} is satisfied in the convex case, meaning that there exists
optimal multipliers $y^{\star},z^{\star}$ that exactly satisfy $\phi_{n+1}[c]=z_{0}^{\star}+R^{2}\cdot\min\{0,\lambda_{\min}[S(y^{\star},z^{\star})]\}$
and therefore \emph{certify} the global optimality $X^{\star}$ via
\propref{dual}. In fact, SDP solvers are guaranteed to compute
a primal feasible $X$ and dual multipliers $y,z$ that certify $X$
to be $\epsilon$ near-globally optimal in at most $O(\sqrt{n}\log(1/\epsilon))$
iterations. However, each iteration requires costs up to $O(n^{6})$
time and $O(n^{4})$ memory, and this limits the maximum number of
neurons $n$ that can be considered in practice to no more than a
few hundred to a thousand.
Now, suppose that the convex solution $X^{\star}$ is in fact low-rank,
as in $r^{\star}=\rank(X^{\star})\ll n$. The statement below says
that the \emph{nonconvex} instance of (\ref{eq:sdp}) with $r=r^{\star}$
also admits optimal multipliers $y^{\star},z^{\star}$ that certify
global optimality.
\begin{thm}[Existence of global optimality certificate]
\label{thm:rstar}Let $r^{\star}=\rank(X^{\star})$, where $X^{\star}$
denotes the maximum-rank solution to the convex instance of (\ref{eq:sdp})
with $r=n+1$. Then, there exists optimal multipliers $y^{\star}=(y_{0}^{\star},\{y_{k,1}^{\star},y_{k,2}^{\star}\}_{k=1}^{\ell-1})$
and $z^{\star}=(z_{0}^{\star},\{z_{k}^{\star}\}_{k=1}^{\ell-1})$
that satisfy $y^{\star}\ge0$ and the following
\[
\phi_{r^{\star}}[c]=z_{0}^{\star}+R^{2}\cdot\min\{0,\lambda_{\min}[S(y^{\star},z^{\star})]\}.
\]
\end{thm}
\begin{proof}
The convex instance of (\ref{eq:sdp}) satisfies the dual Slater's
condition: the primal is feasible with $x_{0}=1,$ $x_{1}=\hat{x},$
$x_{k+1}=\max\{0,W_{k}x_{k}+b_{k}\},$ and $X_{i,j}=x_{i}x_{j}^{T},$
and the dual is strictly feasible with $y=\one$ and $z=0$ and $\mu\to-\infty$.
Therefore, strong duality holds, and there exists $y^{\star},z^{\star}$
that satisfy $y^{\star}\ge0$ and $\phi_{n+1}[c]=z_{0}^{\star}+R^{2}\cdot\min\{0,\lambda_{\min}[S(y^{\star},z^{\star})]\}$.
Now, we observe that $X^{\star}$ is also feasible for the nonconvex
instance of (\ref{eq:sdp}) with $r=\rank(X^{\star})$. This proves
that $\phi_{r^{\star}}[c]\le\phi_{n+1}[c]$, and therefore $\phi_{r^{\star}}[c]=\phi_{n+1}[c]$
because of every larger $r_{+}=r+1$ gives a relaxation of the previous
value of $r$.
\end{proof}
Therefore, a simple idea is to directly solve the nonconvex instance
of (\ref{eq:sdp}) with $r=r^{\star}\ll n$. In the following section,
we use an approach of \citet{burer2003nonlinear} to directly optimize
over the $O(nr)=O(n)$ underlying degrees of freedom contained within
a rank-$r$ matrix $X$. This approach also produces dual multipliers
$y,z$ that certify the \emph{local optimality} of the computed $X$.
Our main result is that, if $X$ is indeed globally optimal, then
the dual multipliers $y,z$ that certify the local optimality of $X$
must also certify its global optimality via \propref{dual}.
\section{Solution via Nonlinear Programming}
In order to expose the underlying degrees of freedom in the rank-$r$
matrix $X$, we reformulate problem (\ref{eq:sdp}) into a low-rank
factorization form first proposed by \citet{burer2003nonlinear}:
\begin{alignat}{2}
\phi_{r}[c]=\min_{u_{0},u,V}\quad & u_{0}\cdot(w_{\ell}^{T}u_{\ell}) & \tag{BM-\ensuremath{r}}\label{eq:bm}\\
\text{s.t. }\quad & \|u_{1}-u_{0}\hat{x}\|^{2}+\|V_{1}\|^{2}\le u_{0}^{2}\rho^{2},\quad u_{0}^{2}=1 & \qquad(y_{0},z_{0})\nonumber \\
& u_{0}\cdot u_{k+1}\ge0,\qquad u_{0}\cdot(u_{k+1}-W_{k}u_{k}-b_{k}u_{0})\ge0, & (y_{k,1},y_{k,2})\nonumber \\
& \diag\left[(u_{k+1}-W_{k}u_{k}-b_{k}u_{0})u_{k+1}^{T}+(V_{k+1}-W_{k}V_{k})V_{k+1}^{T}\right]=0, & (z_{k})\nonumber \\
& 1+\sum_{k=1}^{\ell-1}(\|u_{k}\|^{2}+\|V_{k}\|^{2})\le R^{2}, & (\mu)\nonumber
\end{alignat}
for all $k\in\{1,\dots,\ell-1\}$, and over optimization variables
are $u_{0}\in\R$ and $u=(u_{1},\dots,u_{\ell})\in\R^{n}$ and $V=(V_{1},\dots,V_{\ell})\in\R^{n\times(r-1)}$.
Problem (\ref{eq:bm}) is obtained by substituting the following into
(\ref{eq:sdp})
\begin{equation}
X=\left[\begin{array}{c|ccc}
x_{0} & x_{1}^{T} & \cdots & x_{\ell}^{T}\\
\hline x_{1} & X_{11} & \cdots & X_{1,\ell}\\
\vdots & \vdots & \ddots & \vdots\\
x_{\ell} & X_{1,\ell}^{T} & \cdots & X_{\ell,\ell}
\end{array}\right]=\left[\begin{array}{c|c}
u_{0} & 0\\
\hline u_{1} & V_{1}\\
\vdots & \vdots\\
u_{\ell} & V_{\ell}
\end{array}\right]\left[\begin{array}{c|c}
u_{0} & 0\\
\hline u_{1} & V_{1}\\
\vdots & \vdots\\
u_{\ell} & V_{\ell}
\end{array}\right]^{T}=UU^{T}.\label{eq:bmpart}
\end{equation}
The equivalence between these two problems follows because every $(n+1)\times(n+1)$
matrix $X$ of rank $r$ can be factored as $X=LL^{T}$ into a low-rank
Cholesky factor $L$ that is both lower-triangular and of dimensions
$(n+1)\times r$.
The advantage of the formulation (\ref{eq:bm}) is that it reduces
the number of explicit variables from the $\frac{1}{2}n(n+1)\approx\frac{1}{2}n^{2}$
in the original matrix $X$ to $nr+1\approx nr$ in the factor matrix
$U$, while also allowing the positive semidefinite constraint $X\succeq0$
to be enforced for free. For moderate values of $r\ll n$, the resulting
instance of (\ref{eq:bm}) contains just $O(n)$ variables and constraints.
We propose solving (\ref{eq:bm}) as an instance of the standard-form
nonlinear program,
\begin{equation}
\min_{\|x\|\le R}\quad f(x)\quad\text{ s.t. }\quad g(x)\le0,\quad h(x)=0,\tag{NLP}\label{eq:nlp}
\end{equation}
using a high-performance general-purpose solver like \texttt{fmincon}
or \texttt{knitro}. These are primal-dual solvers, and are designed
to output a primal point $x=(u_{0},u,\vec(V))$ that is \emph{first-order
optimal}, and dual multipliers $y=(y_{0},\{y_{k,1},y_{k,2}\}_{k=1}^{\ell})$
and $z=(z_{0},\{z_{k}\}_{k=1}^{\ell})$ that \emph{certify} the first-order
optimality of $x$. Below, the notion of first-order optimality is
taken from \citet[Theorem 12.3]{nocedal2006numerical}, and the notion
of certifiability follows from the proof of \citep[Theorem 12.1]{nocedal2006numerical}.
\begin{defn}
The point $x$ is said to be \emph{first-order optimal} if it satisfies
the constraints $g(x)\le0$ and $h(x)=0$, and there exists no escape
path $x(t)$ that begins at $x(0)=x$ and makes a first-order improvement
to the objective while satisfying all constraints, as in
\begin{equation}
f(x(t))\le f(x)-\delta t,\quad g(x(t))\le0,\quad h(x(t))=0,\qquad\forall t\in[0,\epsilon)\label{eq:escape1}
\end{equation}
for sufficiently small but nonzero $\delta>0$ and $\epsilon>0$.
\end{defn}
\begin{defn}
The point $x$ is said to be \emph{certifiably first-order optimal}
if it satisfies the constraints $g(x)\le0$ and $h(x)=0$, and there
exist dual multipliers $y$ and $z$ that satisfy the Karush--Kuhn--Tucker
(KKT) equations:
\begin{equation}
\nabla f(x)+\nabla g(x)y+\nabla h(x)z=0,\quad y\odot g(x)=0,\quad y\ge0.\label{eq:kkt}
\end{equation}
The dual multipliers $y$ and $z$ are said to \emph{certify} $x$
as being first-order optimal.
\end{defn}
Our main idea is to simply take the dual multipliers $y,z$ computed
by the nonlinear programming solver, round them $y\gets\max\{0,y\}$
as necessary to ensure that $y\ge0$, and then to plug them back into
\propref{dual}. Unfortunately, it also possible for a primal point
$x$ to be first-order optimal without being certifiably so, i.e.
they may not exist dual multipliers $y,z$ to certify the first-order
optimality of $x$. As a simple example, consider $f(x)=x,$ $g(x)=x^{2},$
and $h(x)=0$. The global minimum $x=0$ is obviously first-order
optimal, but it is impossible to find a multiplier $y\ge0$ that satisfies
$\nabla f(x)+y\nabla g(x)=1+2xy=0$ at this point $x=0$. In this
case, a nonlinear programming solver may fail to produce a set of
dual multipliers $y,z$ altogether.
Instead, we give a mild constraint qualification that guarantees the
existence of dual multipliers $y,z$ specifically for problem (\ref{eq:bm}).
Concretely, we prove that if all of the ReLU activation functions
are differentiable at the point $x$, then the linear independence
constraint qualification (LICQ) is satisfied, so the nonconvex relaxation
(\ref{eq:bm}) is also smooth at $x$.
\begin{lem}[Nonzero preactivation]
\label{lem:npcq}Let $x=(u_{0},u_{1},\dots,u_{\ell},\vec(V_{1}),\dots,\vec(V_{\ell}))$
satisfy:
\begin{equation}
\e_{i}^{T}(W_{k}u_{k}+b_{k}u_{0})\ne0,\quad\e_{i}^{T}W_{k}V_{k}\ne0\quad\text{for all }k\in\{1,\dots,\ell-1\},\quad i\in\{1,\dots,n_{k}\}.\tag{NPCQ}\label{eq:npcq}
\end{equation}
Then, $x$ is first-order optimal if and only if there exist dual
multipliers $y$ and $z$ to certify $x$ as being first-order optimal.
Moreover, the choice of dual multipliers $y,z$ is unique.
\end{lem}
It then follows from the uniqueness of the dual multipliers that,
if $x$ is indeed globally optimal, then the dual multipliers $y,z$
that certify the local optimality of $X$ must also certify its global
optimality via \propref{dual}.
\begin{thm}[Zero duality gap]
\label{thm:zerodual}Let $r\ge r^{\star}$ where $r^{\star}$ is
defined in \thmref{rstar}. If $x$ is globally optimal and satisfies
(\ref{eq:npcq}), then the dual multipliers $y$ and $z$ that certify
$x$ to be first-order optimal must also certify $x$ to be globally
optimal, as in
\[
\phi_{r}[c]=u_{0}\cdot(w_{\ell}^{T}u_{\ell})=z_{0}+R^{2}\cdot\max\{0,\lambda_{\min}[S(y,z)]\}.
\]
\end{thm}
Therefore, if a first-order optimal point $x$ satisfies nonzero preactivation
but yields a large duality gap, then either $r$ is too small, or
$x$ is not globally optimal (it is either a suboptimal local minimum
or a saddle-point). In either case, we suggest lifting to a higher
relaxation rank $r_{+}=r+1$. With this higher relaxation rank $r_{+}$,
any first-order optimal point $x$ from before---including the true
global minimum of the rank-$r$ problem if $r<r^{\star}$---is guaranteed
to become a saddle point. The statement below gives a direction to
escape the saddle-point and make a decrement.
\begin{thm}[Escape lifted saddle point]
\label{thm:escape}Let $x=(u_{0},\{u_{k},V_{k}\}_{k=1}^{\ell})$
be certifiably first-order optimal for (\ref{eq:bm}) with dual multipliers
$(y,z)$. If $x$ satisfies (\ref{eq:npcq}) and $\|x\|<R$ and $\gamma=-\lambda_{\min}[S(y,z)]>0$,
then the eigenvector $\xi=(\xi_{0},\xi_{1},\xi_{2},\dots,\xi_{\ell})$
that satisfies $\xi^{T}S(y,z)\xi=-\gamma\|\xi\|^{2}$ implicitly defines
an escape path $x_{+}(t)=(u_{0},\{u_{k,+}(t),V_{k,+}(t)\}_{k=1}^{\ell})$
with
\[
u_{k,+}(t)=u_{k}+O(t^{2}),\qquad V_{k,+}(t)=[V_{k},0]+t\cdot[0,u_{k}\xi_{0}/u_{0}+\xi_{k}]+O(t^{2})
\]
that makes a second-order improvement to the objective while satisfying
all constraints, as in
\[
f(x_{+}(t))=f(x)-t^{2}\gamma,\quad g(x_{+}(t))\le0,\quad h(x_{+}(t))=0\text{ for all }t\in[0,\epsilon)
\]
for sufficiently small but nonzero $\epsilon>0$.
\end{thm}
To escape the lifted saddle-point in practice, it suffices to move
along the \emph{straight} path $\tilde{x}_{+}(t)=(u_{0},\{\tilde{u}_{k,+}(t),\tilde{V}_{k,+}(t)\}_{k=1}^{\ell})$
\[
\tilde{u}_{k,+}(t)=u_{k},\qquad\tilde{V}_{k,+}(t)=[V_{k},0]+t\cdot[0,u_{k}\xi_{0}/u_{0}+\xi_{k}],
\]
then solve for feasibility $g(x)\le0$ and $h(x)=0$. Concretely,
after computing a first-order optimal $x$, we increment the relaxation
rank $r_{+}=r+1$, and initialize the nonlinear programming solver
using the lifted point $\tilde{x}_{+}(\epsilon)$ as the initial primal
point, and the old multipliers $y,z$ as the initial dual multipliers.
If this arrives at the global optimum, then the corresponding $y,z$
must certify $x$ as being so. Otherwise, we repeat the rank lifting
procedure.
Progressively lifting the relaxation rank $r$, in our experience
it takes no more than $r\le10$ to reduce the duality gap to values
of $10^{-8}$. To rigorously guarantee a zero duality gap, however,
can require a relaxation rank on the order of $r=O(\sqrt{n})$~\citep{boumal2020deterministic},
irrespective of the value of $r^{\star}$. Indeed, counterexamples
with $\epsilon_{\feas}>0$ exist for relaxation ranks $r$ that are
even slightly smaller than this threshold~\citep{waldspurger2020rank,zhang2022improved}.
As a purely theoretical result, the ability to achieve a zero duality
gap implies that the nonconvex relaxation (with $r\ge r^{\star}$)
can be solved in polynomial time (and is therefore not NP-hard). Of
course, setting $r=O(\sqrt{n})$ would also force us to optimize over
$O(n^{3/2})$ variables, thereby offsetting much of our computational
advantage against the usual convex SDP relaxation in practice.
\algref{staircase} summarizes our proposed approach in pseudocode
form, and introduces a number of small practical refinements. The
algorithm is, at its core, a special instance of the Riemannian staircase~\citep{boumal2016non,boumal2020deterministic},
and as such bears similarities to related work in \citep{rosen2014rise,carlone2015lagrangian,cohen2019certified,rosen2019se}.
However, our specialization to the verification setting enjoys much
stronger guarantees, summarized in \thmref{zerodual} and \thmref{escape},
because we are able to formally establish constraint qualification
in \lemref{npcq}. In contrast, prior work often take LICQ as a strong
assumption, but this reduces the Riemannian staircase from a rigorous
algorithm to an empirical heuristic.
\begin{algorithm}
\caption{\label{alg:staircase}Summary of proposed algorithm}
\textbf{Input:} Initial relaxation rank $r\ge2$. Weights $W_{1},\dots,W_{\ell}$
and biases $b_{1},\dots,b_{\ell}$ for the neural network. Original
input $\hat{x}$, true label $\hat{c}$, target label $c$, and perturbation
size $\rho$. Variable radius bound $R$.
\textbf{Output:} Lower-bound $\phi_{\lb}[c]\le\phi[c]$ on the optimal
value of the semi-targeted attack problem (\ref{eq:attack}).
\textbf{Algorithm:}
\begin{enumerate}
\item (Solve rank-$r$ relaxation) Use a nonlinear programming solver to
solve the following
\begin{alignat*}{2}
\min_{\|x\|\le R}\quad f(x) & \equiv(\e_{c}-\e_{\hat{c}})^{T}(W_{\ell}u_{\ell}u_{0}+b_{\ell})\\
\text{s.t.}\quad g_{0}(x) & \equiv\|u_{1}-u_{0}\hat{x}\|^{2}+\|V_{1}\|^{2}-\rho^{2} & \le0 & \quad(y_{0})\\
h_{0}(x) & \equiv1-u_{0}^{2} & =0 & \quad(z_{0})\\
g_{k}(x) & \equiv\begin{bmatrix}-u_{0}u_{k+1}\\
u_{0}(W_{k}u_{k}+b_{k}u_{0}-u_{k+1})
\end{bmatrix} & \le0 & \quad(y_{k,1},y_{k,2})\\
h_{k}(x) & \equiv\diag[(u_{k+1}-W_{k}u_{k}-b_{k}u_{0})u_{k+1}^{T}+(V_{k+1}-W_{k}V_{k})V_{k+1}^{T}] & =0 & \quad(z_{k})
\end{alignat*}
for all $k\in\{1,2,\dots,\ell-1\}$ and over $x=(u_{0},u_{1},\dots,u_{\ell},\vec(V_{1}),\dots,\vec(V_{\ell}))$.
Retrieve the corresponding dual multipliers $y=(y_{0},\{y_{k,1},y_{k,2}\}_{k=1}^{\ell})$
and $z=(z_{0},\{z_{k}\}_{k=1}^{\ell})$.
\item (Check certifiable first-order optimality) If $\|\nabla f(x)+\nabla g(x)y+\nabla h(x)z\|$
is sufficiently small, and if $g(x)\le0$ and $h(x)=0$ and $\|x\|<R$
hold to sufficient tolerance, then continue. Otherwise, return error due to solver's inability to achieve certifiable first-order optimality.
\item (Check dual feasibility) If $\epsilon_{\feas}=-\lambda_{\min}[S(y,z)]$
is sufficiently small, where the slack matrix $S(y,z)$ is defined
in (\ref{eq:sdd}), then return $\phi_{\lb}[c]=z_{0}-\epsilon_{\feas}\cdot R.$
Otherwise, continue.
\item (Escape lifted saddle point) Compute the eigenvector $\xi=(\xi_{0},\xi_{1},\dots,\xi_{\ell})$
satisfying $\|\xi\|=1$ and $\xi^{T}S(y,z)\xi=-\epsilon_{\feas}$.
Set up new primal initial point $x_{+}=(u_{0},u_{1},\dots,u_{\ell},\vec(V_{+,1}),\dots,\vec(V_{+,\ell})$
where
\[
V_{+,k}=[V,0]+\epsilon\cdot[0,u_{k}\xi_{0}/u_{0}+\xi_{k}].
\]
Increment $r\gets r+1$ and repeat Step 1 with $(x_{+},y,z)$ as the
initial point.
\end{enumerate}
\end{algorithm}
\section{Experiments}
In this section, we compare the practical performance of our proposed
verifier \texttt{BM} to LP-based verifiers for certifying both $\ell_2$ and $\ell_\infty$ adversaries. In addition, we also perform simulation on \texttt{BM-Full}, which is an extension of \texttt{BM} with the addition of pre-activation bounds on each hidden neuron. The detail formulation for \texttt{BM-Full} can be found in the Appendix.
\paragraph{Methods}
\texttt{BM} denotes the proposed method in the main paper. \texttt{BM-Full} denotes the proposed method with preactivation bounds. \texttt{PGD} denotes the projected gradient descent algorithm for finding the upper bound of (\ref{eq:attack}). We compare \texttt{BM} and \texttt{BM-Full} to three LP-based verifiers: \texttt{LP-Full}, \texttt{CROWN-Ada} and \texttt{Fast-Lip}. \texttt{LP-Full} \cite{salman2019convex} is the optimal LP-relaxed verifier that uses the tightest possible pre-activation bounds by solving LP problems for each hidden neuron. \texttt{CROWN-Ada} \cite{zhang2018efficient} is a fast LP-relaxed verifier that uses the adaptive linear bounds on activations. \texttt{Fast-Lip} \cite{weng2018towards} is a fast robustness verifier based on propagating Lipschitz constant. Throughout out this experimental section, we set the preactivation bounds in \texttt{BM-Full} to be the same as those used in \texttt{LP-Full}.
\paragraph{Simulation environment.}
All simulations in this section are conducted on a computer with Apple silicon M1 pro chip with 10-core CPU, 16-core GPU, and 32GB of RAM. We implement \texttt{BM} and \texttt{BM-Full} in MATLAB, the non-convex relaxation problem (\ref{eq:bm}) is solved via trust-region interior-point solver KNITRO \cite{byrd2006k} with warm-start strategy. Due to the space constraints, we defer the detailed implementation for \texttt{BM} and \texttt{BM-Full} to the Appendix.
\paragraph{Model architectures}
We perform extensive simulation using three types of feed forward ReLU networks trained on MNIST dataset \cite{deng2012mnist}: NOR-MNIST, ADV-MNIST and LPD-MNIST. All three models are fully connected neural networks that have 2 hidden layers with 100 neurons each. NOR-MNIST is normally trained using cross-entropy loss. ADV-MNIST is adversarially trained to against PGD attack using the method of \cite{madry2017towards}, with $\ell_\infty$ radius equals to 0.1. LPD-MNIST is robustly trained via adversarial polytope perturbation by \cite{wong2018provable}, with the size of the adversarial polytope being 0.1. All three models are adopted from \cite{salman2019convex}. Additionally, we use MLP-$m\!\times\!n$ to denote a fully connected neural network of $m$ hidden layers of $n$ neurons each. All MLP-$m\!\times\!n$ are adversarially trained using \cite{madry2017towards} with $\ell_\infty$ radius equals to 0.1.
\subsection{Robustness verification on neural network inputs.}
One important aspect of robust verification in image classification is to verify whether a correctly classified image is indeed robust at a radius $\rho$. Intuitively, most correct images of a robustly trained model should also be robust. To demonstrate the efficacy of our proposed method, in this experiment, we apply \texttt{BM} and \texttt{BM-Full} to verify robustness of correctly classified images for a robustly trained model.
In robust verification, we mark an image $\hat x$ as \emph{certified robust} within a norm ball of radius $\rho$ if the lower bound on (\ref{eq:attack}) is positive with respect to all 9 incorrect classes of $\hat x$, and mark an image $\hat x$ as \emph{not robust} if an attack is found by \texttt{PGD}; for \texttt{BM} and \texttt{BM-Full} the lower bound on (\ref{eq:attack}) is given by Proposition~\ref{prop:dual}. Additionally, for images that can neither be attacked by \texttt{PGD} nor certified by a verifier, we mark them as \emph{status unknown}.
\paragraph{Results and discussions.}
Figure~\ref{fig:barchart-l2} shows the bar chart of the number of images that are \emph{certified robust}, \emph{status unknown} and \emph{not robust} within the first 1000 images for ADV-MNIST. We compare the results form our BM-based verifier to LP-based verifiers, \texttt{LP-Full}, \texttt{CROWN-Ada} and \texttt{Fast-Lip}, with respect to three different perturbation radius.
In Figure~\ref{fig:barchart-l2}, we show that our verifiers are able to consistently outperform all LP-based verifiers under different perturbation radii. Notably, for small perturbation, our verifiers can nearly certify all images that cannot be attacked by \texttt{PGD}, leaving a very small portion of images that are \emph{status unknown}. This confirms the robust training method from \cite{madry2017towards} is indeed effective.
\begin{figure}[h!]
\centering
\begin{subfigure}{0.5\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/bar1-1.png}
\end{subfigure}%
\begin{subfigure}{0.5\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/bar1-2.png}
\end{subfigure}%
\caption{\textbf{Robustness verification for ADV-MNIST with $\ell_2$ norm.} We compare the number of images verified within the first 1000 images for three different $\ell_2$ perturbation radius, 1.0, 1.3 and 1.5. Each image has three possible status. (1) \textbf{Not robust (colored red)}: an attack has been found by \texttt{PGD}. (2) \textbf{Status unknown (colored gray)}: \texttt{PGD} cannot find an attack, but the verifier fail to certify robustness. (3) \textbf{Certified robust (colored blue)}: the verifier successfully certify robustness. We compare the verification results from our verifiers to those from others. \textbf{(Left.)} Our verifiers based on BM: \texttt{BM-Full} and \texttt{BM}. \textbf{(Right.)} Other verifiers based on LP: \texttt{LP-Full}, \texttt{CROWN-Ada} and \texttt{Fast-Lip}.}
\label{fig:barchart-l2}
\end{figure}
\subsection{Tightness of our lower bound.}
Since robust verification is an NP-hard problem, all relaxation methods must become loose for sufficiently large radius. Fortunately, robust verification is only need when the \texttt{PGD} upper bound of (\ref{eq:attack}) is positive; therefore, we only need the relaxation to be tight when the \texttt{PGD} upper bound is still positive. In this experiment, we analyze the gap between our lower bound in Proposition~\ref{prop:dual} and the \texttt{PGD} upper bound over a wide range of perturbation radius.
To accurately measure the gap between our lower bound and the \texttt{PGD} upper bound, we average each bound over all 9 incorrect classes of the first 10 correctly classified images in the test set, in total 90 samples are considered.
\paragraph{Results and discussions.}
Figures~\ref{fig:tightness} shows the average \texttt{PGD} upper bound, and the average lower bound on (\ref{eq:attack}) computed from \texttt{BM}, \texttt{BM-Full}, \texttt{LP-Full}, \texttt{CROWN-Ada} and \texttt{Fast-Lip} for ADV-MNIST.
As illustrated in Figure~\ref{fig:tightness}, our lower bounds are significantly tighter than all the other verifiers across a wide range of $\ell_2$ and $\ell_\infty$ perturbation radius. Most importantly, our lower bounds are able to remain tightness in regions where the \texttt{PGD} upper bound is still positive.
The huge gap between LP-based verifiers and the \texttt{PGD} upper bound has been pointed out by \cite{salman2019convex}, where he discover that even the optimal LP-relaxed verifier, the \texttt{LP-Full} in our experiment, is still subject to a theoretical limit: the convex relaxation barrier. Specifically, there exists an inherent tradeoff between tightness and tractability, while LP-based verifiers are highly tractable, there is a fundamental limit on the level of tightness that the underlying relaxation problem could achieve. The results in Figure~\ref{fig:tightness} show that our proposed method \texttt{BM} and \texttt{BM-Full}, which is based on solving nonconvex SDP relaxation via rank-$r$ Burer-Monteiro, is able to overcome convex relaxation barrier and at the same time maintain computational tractable.
\begin{figure}[h!]
\centering
\begin{subfigure}{0.5\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/tightness1-1.png}
\end{subfigure}%
\begin{subfigure}{0.5\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/tightness1-2.png}
\end{subfigure}
\begin{subfigure}{0.5\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/tightness2-1.png}
\end{subfigure}%
\begin{subfigure}{0.5\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/tightness2-2.png}
\end{subfigure}
\caption{\textbf{Tightness of our lower bound on (\ref{eq:attack}) for ADV-MNIST}. We compute the average lower bound on (\ref{eq:attack}) using each verifier and compare it to the average \texttt{PGD} upper bound over a wide range of perturbation radius. The averages are taken over the first 10 images. \textbf{(Top row.)} $\ell_2$ perturbation. \textbf{(Bottom row.)} $\ell_\infty$ perturbation. \textbf{(Left column.)} Our verifiers based on BM: \texttt{BM-Full} and \texttt{BM}. \textbf{(Right column.)} Other verifiers based on LP: \texttt{LP-Full}, \texttt{CROWN-Ada} and \texttt{Fast-Lip}.}
\label{fig:tightness}
\end{figure}
\subsection{Visualizing adversarial attacks and robustness verification}
To illustrated why robustness verification is important in image classification, in this experiment, we perform a case study based on an image in the test set using the model ADV-MNIST. In particular, we focus on showing how would the $\ell_2$ adversaries look like in practice for four perturbation radius $\rho\in\{0.5, 1.0, 1.7,2.0\}$, as well as their corresponding lower bound on (\ref{eq:attack}) computed from BM-based and LP-based verifiers. We choose $\ell_2$ norm over $\ell_\infty$ norm for this experiment because $\ell_2$ norm allows perturbations to be concentrated on a small group of pixels, which produces adversaries that are more perceptually consistent to the original dataset when the perturbation radius is large.
\begin{figure}[h]
\centering
\includegraphics[width=\linewidth]{figures_arxiv/casestudy.png}
\caption{\textbf{Visualizing $\ell_2$ adversarial examples for ADV-MNIST.} We take an image in the test set to compare the capability of different verifiers for certifying robustness within four different $\ell_2$ radius $\rho\in\{0.5, 1.0, 1.7,2.0\}$. Each column in the figure shows (left to right): \textbf{(Column 1.)} The image is robust for $\rho=0.5$, and it can be certified by all verifiers. \textbf{(Column 2.)} The image is robust for $\rho=1.0$, but it can be only be certified by our verifiers, \texttt{BM-Full} and \texttt{BM}. \textbf{(Column 3.)} The image is closed to become not robust for $\rho=1.7$, but it can still be certified by our verifiers. \textbf{(Column 4.)} The image is not robust for $\rho=2.0$.}
\label{fig:case_study}
\end{figure}
\paragraph{Results and discussions.}
Figure~\ref{fig:case_study} shows: the adversarial attacks targeting the second most probable class of a MNIST image of class "1"; the probability of the top-2 classes for the attacked image (calculated using the softmax function); the \texttt{PGD} upper bound; and the lower bounds from different verifiers. For the MNIST image shown in the figure, the second most probable class is "7", and its adversarial attacks are computed via \texttt{PGD}.
The first and second column of Figure~\ref{fig:case_study} correspond to attacks within two small $\ell_2$ perturbation radius $\rho\in\{0.5, 1.0\}$. We see that every verifiers is able to verify robustness for $\rho=0.5$, however, only \texttt{BM-Full} and \texttt{BM} are able to verify robustness for $\rho=1.0$, all the other verifiers fail because their corresponding lower bounds become loose. In both cases, the adversaries look really similar to the original image.
The third and fourth column of Figure~\ref{fig:case_study} correspond to attack within two large $\ell_2$ perturbation radius $\rho\in\{1.7, 2.0\}$. Notice that \texttt{BM-Full} and \texttt{BM} can still verify robustness for $\rho=1.7$ even though the image is at the boundary of becoming not robust. In addition, the image is not robust for $\rho=2.0$ as the \texttt{PGD} upper bound is negative. Notably, both images start gaining features of the digit "7".
\subsection{Tightness plots for deeper neural networks}
It is known that the relaxation gap generally increases along with the number of layers in the neural network. To demonstrate the performance of our proposed methods in deeper networks, in this experiment, we measure the gap of \texttt{BM-Full} and \texttt{BM} with respect to models of three different depths.
\begin{figure}[h]
\centering
\begin{subfigure}{0.33\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/depth1-1.png}
\end{subfigure}%
\begin{subfigure}{0.33\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/depth1-2.png}
\end{subfigure}%
\begin{subfigure}{0.33\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/depth1-3.png}
\end{subfigure}
\begin{subfigure}{0.33\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/depth2-1.png}
\end{subfigure}%
\begin{subfigure}{0.33\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/depth2-2.png}
\end{subfigure}%
\begin{subfigure}{0.33\textwidth}
\centering
\includegraphics[width=\linewidth]{figures_arxiv/depth2-3.png}
\end{subfigure}
\caption{\textbf{Lower bound on (\ref{eq:attack}) with different model depth ($\ell_2$ norm).} We compute the average lower bound on (\ref{eq:attack}) for three models with 4, 6, 9 hidden layers of 100 neuron each, respectively. The upper bound on robustness margin is estimated via \texttt{PGD}. Observe that the gap between the \texttt{PGD} upper bound and lower bound from \texttt{BM-Full} are significantly smaller than that from \texttt{LP-Full}. We note that without bound propagations, \texttt{BM} does get loose when the number of hidden layer is more than 6. \textbf{(Top row.)} Our verifiers, \texttt{BM-Full} and \texttt{BM}. \textbf{(Bottom row.)} Other verifiers: \texttt{LP-Full}, \texttt{CROWN-Ada} and \texttt{Fast-Lip}.}
\label{fig:depth}
\end{figure}
\paragraph{Results and discussions.}
Figure~\ref{fig:depth} plots the average bounds against $\ell_2$ perturbation radius for three MLP networks with 4, 6, 9 hidden layers of 100 neurons each. Notably, \texttt{BM} become loose for MLP-$6\!\times\!100$ and become looser than \texttt{LP-Full} for MLP-$9\!\times\!100$. This result is expected and is consistent with \cite{zhang2020tightness}; in particular, the SDP relaxation for ReLU gate, without any bound constrains on preactivations, does become loose for multiple layers. On the other hand, \texttt{BM-Full} remain significantly tighter than \texttt{LP-Full} for all cases. Furthermore, since the preactivation bounds used in \texttt{BM-Full} and \texttt{LP-Full} are the same in this experiment, Figure~\ref{fig:tightness} and Figure~\ref{fig:depth} suggest that with the same quality of preactivation bounds, \texttt{BM-Full} would yield a tighter relaxation than \texttt{LP-Full}. Based on this finding, we note that the preactivation bounds for \texttt{BM-Full} can also be computed via BM-based methods, which should yield a tighter bound on the preactivations and hence further reduces the relaxation gap for \texttt{BM-Full}; one example would be recursively apply \texttt{BM-Full} to compute the upper and lower bound on each neuron, however, such method can be extremely computational expensive for small to medium size networks. We leave \texttt{BM-Full} with better preactivation bounds to our future work.
\section*{Acknowledgments}
The authors thank Zico Kolter for insightful discussions and pointers
to the literature. Financial support for this work was provided by
the NSF CAREER Award ECCS-2047462 and C3.ai Inc. and the Microsoft
Corporation via the C3.ai Digital Transformation Institute.
\bibliographystyle{plainnat}
| {'timestamp': '2022-12-01T02:21:23', 'yymm': '2211', 'arxiv_id': '2211.17244', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17244'} | arxiv |
\section{Introduction}
Over recent years, deep learning methods have been increasingly used for Computer Vision tasks, including Object Detection.
While the most of the architectures are optimised on well known benchmarks like COCO \cite{coco} \cite{yolov4} \cite{dino}, further remarkable results have been obtained using CNNs for domain-specific tasks, such as medical \cite{medical_OD}, traffic \cite{traffic}, environmental \cite{fire} etc. Such domain specific solutions, however, are usually heavily optimized for a specific target dataset, starting from carefully tailored architecture to choice of training tricks. This not only makes them time-consuming and computationally heavy to obtain but also is the reason why they \textbf{lack good domain generalization}. Training models in such a way suffers from the caveat of overly adjusting the techniques to a specific dataset. That leads to, on one hand, great predictions for a given dataset, on the other, showing poor transferability to a different one. Meaning, such a model is unlikely to train well on a new, previously unseen dataset, without additional time-consuming and computationally expensive experiments to find the optimal tweaks of the model architecture and training pipeline. Hence, such an approach, even though used in the past with great successes, is \textbf{not flexible enough} for the rapidly evolving needs across a wide variety of computer vision use cases with a focus on time to value.
In this paper we propose an alternative approach aimed at those situations, addressing the needs of fast-paced industry and real-world applications. We provide a \textbf{dataset-agnostic template for object detection that is ready to be used straight away} and guarantees a strong baseline on a wide variety of datasets, without needing additional time-consuming and computationally demanding experiments. The template also provides the flexibility for further fine-tuning, however, it is not required. This methodology includes a carefully chosen and pre-trained model, together with a robust and efficient training pipeline for further training.
To achieve this, we base this study on a carefully chosen corpus of 11 datasets that cover a wide range of domains and sizes. They differ in both number of images as well as their complexity, including the number of classes, object sizes, distinguishability from the background, and resolution.
The training procedure involves parallel experiments on all the datasets from the corpus, optimizing the model with respect to average metrics over all corpora.
To summarize, we introduce:
\begin{itemize}
\item a training paradigm together with a choice of a corpus of datasets,
\item a universal, dataset-agnostic model template for object detection training,
\item additional patience parameters for ReduceOnPlateau and Early Stopping, to correct for the different sizes of datasets and avoid over/under-fitting,
\item choice of data-agnostic augmentations and specific tricks for each of our 3 models that work on a wide range of datasets
\end{itemize}
This methodology in the Intel{\textregistered} Geti{\texttrademark} computer vision platform enables platform users to accelerate their object detection training workloads for their real-world use cases across a variety of industries.
\section{Related Work}
\subsection{Architectures}
In this section, we will briefly describe the architectures we explore in our experiments.
\textbf{SSD}
Since its introduction, SSD \cite{SSD} has been a go-to model in the industry, thanks to its high computational efficiency. As an anchor-based detector, it predicts detections on the predefined anchors. All generated predictions are classified as positive or negative, and then an extra offset regression on the positives is done for the final refinement of the bounding box location. However, anchor-based models present a serious disadvantage, they need manual tuning of the number of anchors, their ratio, and scale. This fact negatively affects their ability to generalize to different datasets.
\textbf{FCOS} Anchor-free detectors address these concerns. Instead of anchor boxes, they use single points for detection, determining the center of the object. FCOS \cite{FCOS} approaches object detection in a per-pixel way, making use of the multi-level predictions thanks to FPN. For each layer of the feature pyramid, each point on the feature map can generate a prediction, that is later classified as positive or negative, and further regression is done to determine the bounding box around the initial point. Since the predictions are made on points, a new way to define positives and negatives is introduced to replace the traditional IoU-based strategy. This brings further improvements. Additionally, to suppress the low-quality detections during NMS, \textit{centerness}, evaluating localization estimation, is used in combination with classification score as a new ranking measure.
\textbf{YOLOX} YOLOX \cite{YOLOX} is a new anchor-free member of another classic family of models. As a basis it takes YOLOv3 \cite{YOLOv3}, still widely used in the industry, then boosting it for modern times with the newest tricks, including decoupled head, to deal with classification VS regression conflict, and advanced label assigning strategy, SimOTA.
\textbf{ATSS} ATSS \cite{ATSS} improves performance of detection, due to introduction of \textit{Adaptive Training Sample Selection}. It is a method that allows for an automatic selection of positive and negative samples based on the statistical characteristics of objects.
\textbf{VFNet}
VFNet \cite{VFNet} builds on FCOS and ATSS advances, topping it up with a new ranking measure for the NMS stage, to suppress low-quality detections even more efficiently. The proposed metric, \textit{the IoU-aware classification score}, combines together information on the classification score and localization estimation in a more natural way and in only one variable. This not only gives better results in terms of the quality of detections but also avoids the overhead of the additional branch for localization score regression.
\textbf{Faster R-CNN and Cascade R-CNN}
All the models considered so far were one-stage detectors.
Faster R-CNN \cite{faster} is a two-stage detector, where in the first stage the model coarse scans the whole image to generate region proposals, on which it concentrates in more detail in the second stage. A Region Proposal Network is introduced for the effective generation of region proposals. It is an anchor-based detector with a definition of positive and negative samples through IoU threshold. This generates issues with the quality of detections, low threshold produces noisy detections, increased threshold causes vanishing positive samples and effectively overfitting. Cascade R-CNN \cite{cascade} is a multi-stage detector addressing this issue. It consists of a sequence of detectors trained with increasing IoU thresholds.
\subsection{Towards More Universal Models}
Recently a lot of work has been done in the area of moving towards more flexible, generalizable models in computer vision.
This ranges from multi-task training \cite{multi_task}, where a model is simultaneously trained to perform different tasks, to domain generalization \cite{dom_gen}, where the goal is to build models that can predict well on datasets out-of-distribution from those seen during training. Another interesting direction is a few-shot dataset generalisation \cite{few_shot_gen}.
In this approach parallel training on diverse datasets is used to build a universal template that can adapt to unseen data using only a few examples.
Similar work to ours has been done in the classification domain \cite{custom_class}, where adaptive training strategies are proposed and proved to be working by training lightweight models on a number of diverse image classification datasets.
\section{Method}
This section describes in detail our approach to train dataset-agnostic models from the architecture to the training tricks.
\subsection{Architecture}
To create a scope of the models that are applicable for the various object detection datasets regardless of difficulty and object size, we experimented with architectures in three categories: the light-weighted (about 10 GFLOPs), highly accurate, and medium ones. A detailed comparison of the different architectures used can be found in Table~\ref{tab:avg_metrics}.
For the fast and medium models we took light and accurate enough MobileNetV2 backbone \cite{mobilenetv2}, which is commonly used in the application field.
For the accurate model we used ResNet50 \cite{resnet} as a backbone.
For the light model we used really fast SSD with 2 heads, which can be even more optimized for CPU using OpenVINO{\texttrademark} toolkit; for medium - ATSS head; and for accurate - VFNet with modified deformable convolutions (DCNv2 \cite{modifiedDCN}).
In our experiments, as described later, we were not limited with these architectures to achieve specific goals of performance and accuracy. For example, we also tried lighted ATSS as a candidate for the fast model, and SSD with more heads as a candidate for the medium model.
But the final setup with 3 different architectures worked best.
\subsection{Training Pipeline}
\label{training_pipeline_section}
\paragraph{Pretraining weights}
To achieve fast model convergence and to get high accuracy right from the start, we used pretrained weights.
Firstly, we trained MobileNetV2 classification model with ImageNet21k\cite{imagenet21k}, so a model could learn to differentiate trivial features and patterns.
Afterward, we only took the trained MobileNetV2 backbone weight, cutting off the fully connected classifier head.
Then, we used this pretrained backbone for our object detection model and trained ATSS-MobileNetV2 and SSD-MobileNetV2 on the COCO object detection dataset \cite{coco} with 80 annotated classes.
For VFNet we used pretrained COCO weights from OpenMMlab MMDetection \cite{openmmlab}.
\paragraph{Augmentation}
For augmentation, we used some classic tricks that have gained the trust of researchers. We augmented images with a random crop, horizontal flip, and brightness and color distortions.
The multiscale training was used for medium and accurate models to make them more robust.
Also, after a series of experiments we carefully and empirically chose certain resolutions for each model in order to meet the trade-off between accuracy and complexity. For example, SSD performed best on the square 864x864 resolution, ATSS on the rectangle (992x736), and for VFNet we used the default high resolution without any tuning (1344x800).
During resizing we did not keep the initial aspect ratio for 3 reasons:
\begin{enumerate}
\item to add extra regularization;
\item to avoid blank spaces after padding;
\item to avoid spending too much time on model resizing if the image aspect ratio differs a lot from the default.
\end{enumerate}
The impact of these tricks on accuracy and training time can be found in the Ablation study (section~\ref{ablation_section}).
\paragraph{Anchor clustering for SSD}
Despite the wide application of the SSD model, especially in production, its high inference speed, and good enough results, its dependence on careful anchor box tuning is a huge drawback.
It relies on the dataset and object size characteristics.
So, it becomes a challenge to build dataset-agnostic training using SSD model.
For that reason, we followed the logic in \cite{lighweight_model} and used information from the training dataset to modify the anchor boxes before training started.
We collect object size statistics and cluster them using KMeans algorithm \cite{kmeans} to find the optimal anchor boxes with the highest overlap among the objects. These modified anchor boxes are then passed for training.
This procedure is used for each dataset and helps to make the light model more adaptive, improving the result without additional model complexity overhead.
\paragraph{Early Stopping and ReduceOnPlateau}
The complexity and size of the input dataset can vary drastically, making it hard to predict the number of epochs, needed to get a satisfying result and could often lead to large training times or even overfitting.
To prevent it, we used Early Stopping \cite{early_stop} to stop training after a few epochs if those did not improve the result further. Further, we used average precision (AP@[0.5,0.95]) on the validation subset as a target metric.
This problem with the unfixed number of epochs also creates uncertainty in determining learning rate schedule for the given scenario.
We utilized the adaptive ReduceOnPlateau \cite{reduceonplateau} scheduler in tandem with Early Stopping, as commonly employed, to circumvent this problem.
This scheduler reduces the learning rate automatically if the consecutive epochs do not lead to improvement in the target metric - average precision for the validation dataset in our case.
We implemented both of these algorithms for the MMDetection \cite{mmdetection} framework that forms the backbone of our codebase. It also powers the Intel Geti computer vision platform.
It is an OpenVINO{\texttrademark} toolkit fork of the OpenMMLab repository.
\paragraph{Iteration patience}
Another challenge is that the number of iterations in the epoch differs drastically from dataset to dataset depending on its length. This creates a problem to choose an appropriate "patience" parameter for Early Stopping and ReduceOnPlateau in case of the dataset-agnostic training.
For example, if we use the same patience for large datasets and small ones, the training with a small amount of data will stop too early and will suffer from undertraining.
A possible solution here would be to copy the training dataset several times for every training epoch, increasing the number of iterations in the epoch.
However, this will also lead to large datasets suffering from overfitting and long training times.
To overcome this, we adapted the classic approaches of ReduceOnPlateau and Early Stopping by adding \textbf{iteration patience} parameter.
It works similarly to the epoch patience parameter but also ensures that a specific number of iterations were run during training on those epochs.
This approach increased the accuracy on the small datasets however it has some drawbacks as well.
The iteration patience could vary from architecture to architecture and must be chosen manually, which causes adding an extra hyperparameter.
It leads to a less universal training pipeline and careful hyperparameter selection is required in case of trying new architectures, which could be time-consuming.
Another caveat is that on small datasets a large part of the training cycle is still spent on the validation and checkpoint creation because of the short epochs.
It leads to the fact that up to 50\% of the training is spent on not-so-useful checkpoints which are clearly undertrained and not really informative.
Therefore, ideally, you should maximize the time spent on training compared to the time spent on validation and checkpoint creation.
\section{Experiments}
\subsection{Datasets}
For training purposes, we used 11 public datasets varying in terms of the domains, number of images, classes, object sizes, overall difficulty, and horizontal/vertical alignment.
BCCD\cite{bccd}, Pothole\cite{pothole}, WGISD1\cite{wgisd}, WGISD5\cite{wgisd} and Wildfire\cite{wildfire} datasets represent the category with the small number of train images.
Here WGISD1 and WGISD5 share the same images, but WGISD1 annotates all objects as 1 class (grape), while WGISD5 classifies each grape variety.
Aerial\cite{aerial}, Dice\cite{dice}, MinneApple\cite{minneapple} and PCB\cite{pcb} represent datasets with small objects that average size is less than 5\% of the image.
The PKLOT\cite{pklot} and UNO\cite{uno} are large datasets with more than 4000 images.
The samples of the images can be found in Figure~\ref{fig:data_sample}. For illustration purposes, images were cropped to the square format.
The detailed statistics with splitting into sections can be found in Table~\ref{tab:data}.
\begin{figure*}[t]
\centering
\includegraphics[width=18cm]{pictures_5_2}
\caption{Samples of the Training Datasets.}
\label{fig:data_sample}
\end{figure*}
\begin{table}[h!]
\caption{Object Detection Training Datasets.}
\label{tab:data}
\centering
\begin{tabular}{l|c|c|c|c|c}
Dataset & Number of & Average object & \multicolumn{2}{c}{Number of Images} \\
& classes & size, \% of image & Train & Validation \\ \hline
BCCD & 3 & 17x21 & 255 & 73 \\
Pothole & 1 & 23x14 & 465 & 133 \\
WGISD1 & 1 & 7x16 & 110 & 27 \\
WGISD5 & 5 & 7x16 & 110 & 27 \\
Wildfire & 1 & 18x15 & 516 & 147 \\ \hline
Aerial & 5 & 4x6 & 52 & 15 \\
Dice & 6 & 5x3 & 251 & 71 \\
MinneApple & 1 & 4x2 & 469 & 134 \\
PCB & 6 & 3x3 & 333 & 222 \\ \hline
PKLOT & 2 & 5x8 & 8691 & 2483 \\
UNO & 14 & 7x7 & 6295 & 1798 \\
\hline
\hline
\end{tabular}
\end{table}
\subsection{Evaluation Protocol}
For validation, we used a COCO Average Precision with IoU threshold from 0.5 to 0.95 (AP@[0.5,0.95]) as the common metric for the object detection task.
\begin{displaymath}
\text{AP} = \sum_n (R_n - R_{n-1}) P_n
\end{displaymath}
where $P_n$ and $R_n$ are the precision and recall at the $n$-th threshold. AP averages 10 values because IoU thresholds belong to
[0.5,0.95] with an interval 0.05.
We collected train, val, and test AP for each dataset, evaluating the final weights on the train, validation, and test subset respectively.
The val AP acted as the main metric for comparison.
To rank the different training strategies and architectures, the train, val, and test AP scores for each dataset were averaged across the data corpus.
Each of these AP scores contributes equally to the final metric without any weighting strategy.
As an auxiliary metric we used the same average AP scores but on different subsets:
\begin{itemize}
\item on datasets with small objects where average object size is less than 5\% of the image - to monitor how the network handles a hard task of the small object detection
\item on large datasets that contain more than 4000 images - to monitor how the network uses the potential of the large dataset and how its size impacts the training time.
\end{itemize}
\subsection{Results}
After more than 300 training rounds, we have chosen the 3 best architectures in terms of accuracy-performance trade-off: the lightweight and fast, the medium, and the heavy but highly accurate.
These are SSD on the MobileNetV2, ATSS on the MobileNetV2, VFNet on the ResNet50 respectively.
To increase the overall accuracy and keep training time within acceptable ranges we applied some common and architecture-aware practices, which are listed below and described in detail in Training pipeline section ~\ref{training_pipeline_section}.
The contribution of each of these techniques in both improving the accuracy and reducing the training time could be found in the Ablation study (section ~\ref{ablation_section}).
To choose the best models, we also experimented with well-known architectures in the scope of the lightweight, medium, and heavy models, such as YOLOX, FCOS, Faster R-CNN, and Cascade R-CNN.
We have tuned parameters, resolution, training strategy, and augmentation individually to achieve the best accuracy with comparable complexity.
The accuracy values of these architecture experiments could be found in Table~\ref{tab:avg_metrics}.
\begin{table*}[h!]
\caption{Architecture Comparison.}
\label{tab:avg_metrics}
\centering
\begin{tabular}{c|c|c|c|c|c}
& & & \multicolumn{3}{c}{AVG AP on the} \\
\cline{4-6}
Model & AVG AP$^*$, \% & GFLOPs & small & small object & large \\
& & & datasets,\% & datasets, \% & datasets,\% \\
\hline\hline
\textit{Fast models} \\
YOLOX & 49.6 & 6.45 & \textbf{48.8} & 35.1 & 80.7 \\
\textbf{SSD} & \textbf{52.0} & 9.36 & 46.9 & \textbf{38.7} & \textbf{91.2} \\
\hline\hline
\textit{Medium models} \\
FCOS & 56.7 & 20.86 & 52.2 & 43.8 & 93.8 \\
\textbf{ATSS} & \textbf{60.3} & 20.86 & \textbf{55.2} & \textbf{49.7} & \textbf{94.1} \\
\hline\hline
\textit{Accurate models} \\
Faster R-CNN & 61.8 & 433.40 & 55.4& 53.7 & 94.0 \\
Cascade R-CNN & 62.5 & 488.54 & 56.2& 55.0 & 93.6 \\
\textbf{VFNet} & \textbf{64.7} & 347.78 & \textbf{59.5} & \textbf{56.1} & \textbf{95.2} \\
\hline \hline
\multicolumn{5}{l}{\footnotesize{$^*$The average AP on the validation subsets was reported her}} \\
\end{tabular}
\end{table*}
For all of the models we used the following training setup:
\begin{itemize}
\item start from the weights pretrained on the COCO;
\item augment images with a crop, flip, and photo distortions;
\item use ReduceOnPlateau learning rate scheduler with iteration patience;
\item use the Early Stopping to prevent overfitting on the large datasets and iteration patience to prevent underfitting on the small ones.
\end{itemize}
Additional special techniques included:
\begin{itemize}
\item for SSD: anchor box reclustering and pretraining COCO weights on ImageNet-21k\cite{imagenet21k}
\item for ATSS: multiscale training and using ImageNet-21k weights
\item VFNet - multiscale training
\end{itemize}
Detailed results are in Table~\ref{tab:detailed_metrics} below.
\begin{table*}[h!]
\caption{Detailed Results of the Chosen Models on All Datasets.}
\label{tab:detailed_metrics}
\centering
\begin{tabular}{c|c|c|c|c|c|c|c|c|c|c|c} Model & \multicolumn{5}{c|}{Small datasets} & \multicolumn{4}{c|}{Datasets with small objects} & \multicolumn{2}{c}{Large datasets} \\ \cline{2-12}
&
\rotatebox[origin=c]{90}{BCCD} & \rotatebox[origin=c]{90}{Pothole} & \rotatebox[origin=c]{90}{WGISD1} &
\rotatebox[origin=c]{90}{WGISD5} & \rotatebox[origin=c]{90}{Wildfire} &
\rotatebox[origin=c]{90}{Aerial} & \rotatebox[origin=c]{90}{Dice} & \rotatebox[origin=c]{90}{MinneApple} & \rotatebox[origin=c]{90}{PCB} &
\rotatebox[origin=c]{90}{PKLOT} & \rotatebox[origin=c]{90}{UNO} \\
\hline
\hline\hline
\textit{Fast models} \\
YOLOX & 63.5 & 44.7 & 44.1 & 47.7 & 47.7 & 24.2 & 58.2 & 23.0 & 34.9 & 80.9 & 80.5 \\
\textbf{SSD} & 60.0 & 37.5 & 45.9 & 40.2 & 51.0 & 22.7 & 61.3 & 31.1 & 39.8 & 94.7 & 87.7 \\
\hline\hline
\textit{Medium models} \\
FCOS & 63.5 & 42.4 & 55.2 & 55.0 & 44.7 & 29.3 & 59.8 & 39.5 & 46.7 & 97.3 & 90.2 \\
\textbf{ATSS} & 63.5 & 47.9 & 57.5 & 55.4 & 51.5 & 36.8 & 73.8 & 41.0 & 47.3 & 97.7 & 90.5 \\
\hline\hline
\textit{Accurate models} \\
Faster R-CNN & 64.2 & 0.502 & 59.4 & 52.3 & 51.1 & 45.3 & 77.8 & 40.9 & 50.8 & 97.3 & 90.7 \\
Cascade R-CNN & 65.5 & 51.2 & 60.5 & 53.2 & 50.4 & 45.9 & 79.5 & 42.7 & 51.7 & 95.9 & 91.3\\
\textbf{VFNet} & 65.2 & 55.1 & 63.8 & 59.5 & 53.9 & 46.3 & 81.2 & 44.4 & 52.4 & 98.6 & 91.8 \\
\hline \hline
\multicolumn{12}{l}{\footnotesize{The average AP on the validation subsets was reported here}} \\
\end{tabular}
\end{table*}
\subsection{Ablation Study}
\label{ablation_section}
To estimate the impact of each training trick on the final accuracy, we conducted ablation experiments, by removing each of them from the training pipeline.
Based on our experiments, each of these tricks improved the accuracy of the target metric approximately by 1 AP
See results in Table~\ref{tab:ablation_accuracy}.
The iteration patience parameter showed great improvement (7.4 AP) for the fast SSD model, which stopped too early without the new parameter.
The best trick for medium ATSS is using COCO weights, which improved accuracy by 3.5 AP.
For the VFNet the most productive trick was to use COCO weights which increased the accuracy by 17 AP as well.
\begin{table*}[h!]
\caption{Impact of Each Training Trick on the Accuracy of the Candidate Models.}
\label{tab:ablation_accuracy}
\centering
\begin{tabular}{l|c|c|c|c}
Configuration & SSD & ATSS & VFNet \\
& AVG AP$^*$,\% & AVG AP,\% & AVG AP,\% \\
\hline
Final solution & \textbf{52.0} & \textbf{60.3} & \textbf{64.7} \\
w/o pretraining on the COCO & 51.2 & 56.8 & 47.7 \\
w/o Iteration patience & 44.6 & 58.6 & 64.3\\
w/o ReduceOnPlateau LR scheduler & 50.9 & 58.9 &63.7 \\
w/o Multicsale training & - & 59.2 & 64.0 \\
\hline
\textit{Architecture aware features} & & & \\
w/o Anchor reclustering & 48.2 & - & - \\
w/o modified DCN & - & - & 64.1 \\
\hline
\multicolumn{4}{l}{\footnotesize{$^*$The average AP on the validation subsets was reported here}} \\
\end{tabular}
\end{table*}
Since we focused not only on the overall accuracy but also on getting results within an acceptable time range and fast inference of the trained model, we also used some tricks to reduce the training time and complexity of the model, while preserving the accuracy of predictions.
We measured time spent on training in a single GPU setup, using GeForce 3090.
See Table~\ref{tab:ablation_training_time} for certain numbers.
The first thing it is seen here, which is counter-intuitive, is that the small SSD model averagely requires more epochs and more time to fulfill its potential and train enough than the medium ATSS model.
Talking about training time tricks, the most powerful was to use Early Stopping, which reduced the training time by 4.2-8.6 times.
Also, using the standard high resolution (1344x800) of the input images increased the training time for SSD and ATSS architectures by 25-40\%. However, for SSD architecture, the accuracy decreased by 0.9 AP due to the image resolution being too high for such a small model.
And, for ATSS, the accuracy increased by 1.7 AP, mostly due to datasets with small objects. But it slowed inference time by 1.5 times, rendering it too slow for our criteria for a medium model.
\begin{table*}[h!]
\caption{Impact of Each Training Trick to the Training Time$^*$ of the Candidate Models.}
\label{tab:ablation_training_time}
\centering
\begin{tabular}{l|c|c|c|c|c|c|c|c}
& \multicolumn{2}{|c|}{SSD} & \multicolumn{2}{|c|}{ATSS} & \multicolumn{2}{|c|}{VFNet} \\
Configuration & AVG training & AVG & AVG training & AVG & AVG training & AVG \\
& time, min & epochs & time, min & epochs & time, min & epochs \\
\hline
Final solution & 45.18 & 145 & 36.27 & 92 & 230.91 & 71 \\
w/o Early Stopping & 245.20 &300& 306.25 &300& 986.96&300 \\
w/o Tuning resolution & 56.64 & 136 & 50.64 & 111 & - & - \\
\hline
\multicolumn{4}{l}{\footnotesize{$^*$GeForce RTX 3090 was used to benchmark training time.}}
\end{tabular}
\end{table*}
\section{Conclusions}
In this research, we have outlined an alternative approach to training deep neural network models for fast-paced real-world use cases, across a variety of industries. This novel approach addresses the need for achieving high accuracy without performing time-consuming and computationally expensive training or fine-tuning for individual use cases. This methodology forms the backbone of the Intel Geti computer vision platform that enables rapidly building computer vision models for real world use cases.
As a first step, we have proposed a corpus of publicly available 11 datasets, spanning across various domains and dataset sizes.
Subsequently, we have performed more than 300 experiments, each consisting of parallel trainings -- one per each dataset in the selected corpus. We have selected average AP results over all datasets in the corpus as a target metric to optimize our final models.
Using this methodology, we have analyzed a number of architectures, concretely, SSD and YOLOX as fast model architectures for inference, ATSS and FCOS as medium model architectures, and VFNet, Cascade-RCNN, and Faster-RCNN as accurate models.
In the process, we have identified tricks and partial optimization that helped us optimize the average AP scores across the dataset corpus.
We encountered a significant challenge adjusting the optimal training time while building a universal template for a wide range of possible real-world use cases. This also affected the learning rate scheduler.
To solve this we introduced an additional iteration patience parameters for early stopping and ReduceOnPlateau along with the epoch patience parameter. This enabled us to balance the requirements for small and large datasets while maintaining optimal training times irrespective of the dataset sizes.
Our efforts result in 3 (one per 3 different performance-accuracy regimes) dataset-agnostic templates for object detection training, that provide a strong baseline on a wide variety of datasets and can be deployed on CPU using the OpenVINO{\texttrademark} toolkit.
\bibliographystyle{IEEEtran}
| {'timestamp': '2022-12-01T02:19:35', 'yymm': '2211', 'arxiv_id': '2211.17170', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17170'} | arxiv |
\section{Introduction}
For most if not all cancer types, omics profiling studies have been extensively conducted. The early studies are usually focused on a single cancer type/subtype. More recently, as represented by the NCI pan-cancer study, more and more studies have conducted the joint analysis of data on multiple cancer types \cite{weinstein2013cancer,tamborero2013comprehensive}. Such studies can be more challenging and more informative than those on a single cancer type \cite{Guerra2009, Ma2011, Huang2016}. On one hand, with the well-known heterogeneity, differences across cancer types are expected. On the other hand, many studies have suggested the shared omics basis of multiple cancers \cite{Rhodes2004}. As such, a certain level of commonality is also expected. {\it It is important to acknowledge and accommodate both difference and commonality in analysis.}
\begin{figure}
\center
\includegraphics[width=6in]{plot/gene3.pdf}
\caption{Analysis of TCGA melanoma data: Breslow thickness against the expressions of three genes. Three colors correspond to three cancer stages.}\label{fig:gene}
\end{figure}
In the literature, the heterogeneity (difference) across different types of cancers has been sufficiently acknowledged. In contrast, the difference among subjects with the same type of cancer has been noted to a less extent\cite{habermann2007stage, cheng2015stage, palaniappan2016computational}. To fix idea, consider the TCGA melanoma data analyzed in study (for more details, refer to Section \ref{sec:mel}). In Figure \ref{fig:gene}, we show the plots of Breslow thickness (response variable) against the expressions of three genes. The three colors correspond to the three different cancer stages, and the lines are generated using lowess smoothing. It is easy to see that, for different stages of the same cancer, the effects of genes on the response variable are significantly different. It is noted that data on the three stages have been included in one single dataset, and this particular data \cite{akbani2015genomic} as well as those alike \cite{krauthammer2012exome} have usually been analyzed as a whole, with insufficient attention to heterogeneity/difference. In short, accommodating omics difference associated with a third variable (stage in this particular example) is much needed but insufficiently studied \cite{cheng2015stage}.
Many analytic approaches have been developed for analyzing a single cancer omics dataset\cite{chadeau2013, Ang2016}.
Such methods can be used to analyze, for example, the TCGA melanoma dataset as a whole, which stresses commonality but cannot accommodate difference. They can also be applied to one part of data (which may correspond to one stage, subtype, etc.) at a time, and then results are compared across different data parts to draw conclusions on commonality and difference \cite{palaniappan2016computational}. One major problem is that, since each data part often has a small sample size, results from single-part analysis and hence the final results can be unsatisfactory. Related discussions have been extensively provided in recent integrative analysis studies \cite{Ma2011, Huang2016, Huang2017}. In the literature, the work that is the most relevant to this study is perhaps the contrasted penalization \cite{Shi2014}, which encourages similarity in analysis results (especially regression coefficients) across datasets. Contrasted penalization and some other approaches can be limited by identifying similarity but not commonality, in the sense that parts of the analysis results (from multiple datasets) may be similar but not identical (and thus are not commonly shared). In addition, they may not sufficiently accommodate the coordination among omics variables.
\begin{figure}
\center
\includegraphics[width=8 cm]{plot/scheme.pdf}
\caption{Scheme of analysis. Left: true model structure; Middle: analysis by an alternative; Right: CoFu analysis.}\label{graph}
\end{figure}
The analysis scheme of this study is described in Figure \ref{graph}. The left panel describes the true model structure. Here, the three columns correspond to three datasets (with each dataset corresponding to one cancer subtype, stage, etc.), and the rows correspond to genes (or other omics units). The genes form three communities with sizes nine, seven, and six, which are generated from network analysis and describe the coordinated nature of genes. The genes that are associated with the responses are colored. For this schematic example, the orange community behaves the same for the three datasets (commonality), while the yellow and green communities behave differently (difference). {\it Our goal is to conduct community-based analysis (so as to sufficiently accommodate gene coordination) and identify commonality as well as difference in genes' associations with responses}. For such a purpose, a Community Fusion (CoFu) approach is developed. In the middle and right panels of Figure \ref{graph}, the analysis results using an alternative and CoFu are provided, where CoFu has a more accurate identification (more definitive results are provided below in simulation).
For the analysis of cancer omics data, this study has a unique focus on identifying both commonality and difference, and complements the existing studies. A novel CoFu approach is developed. Advancing from methods that pool all datasets together, it can flexibly allow difference across datasets. By jointly analyzing multiple datasets (and hence conducting integrative analysis), it can be more effective than analyzing multiple datasets individually and then pooling results. Advancing from contrasted penalization and other related approaches, it conducts community-based analysis and can identify commonality as opposed to similarity. Overall, this study can deliver a practically useful new venue for analyzing cancer omics data and may lead to important new findings.
\section{Methods}
Consider the analysis of $K$ independent datasets. Each dataset can be on a different type of cancer or a different stage of the same cancer (or be stratified in another meaningful way). In dataset $k(=1, \ldots, K)$, there are $n_k$ i.i.d. observations. Here homogeneity is assumed within but not across datasets. Denote $\bm{y}^{k}=(y_1^k,\ldots,y_{n_k}^k)^\top$ as the response vector and $\bm{X}^k \in \mathbb{R}^{n_k\times p}$ as the design matrix for genes (or other omics units). To simplify notation, it is assumed that the same set of genes is measured in all $K$ datasets. In addition, assume that data processing, for example normalization, has been properly conducted.
For the $k$th dataset, consider the linear regression (LR) model
\begin{equation*}
\label{eq:linear}
\bm{y}^{k}= \bm{X}^{k}\bm{\beta}^{k}+\bm{\epsilon}^k,\ \ k=1,2,\ldots, K,
\end{equation*}
where $\bm{\beta}^k=(\beta_1^k,\ldots,\beta_p^k)^\top$ is the length-$p$ vector of regression coefficients, and $\bm{\epsilon}^k$ is the vector of random errors. Here we first consider linear regression, which is the most popular and matches data analyzed in this article. The proposed method is applicable to other models, for example, the GLM model. More details are provided in Appendix \ref{sec:logit}.
For analyzing cancer omics data, network-based analysis, which takes a system perspective and accommodates the interconnections among genes, has been shown to be more informative than individual-gene-based analysis. In our analysis, we accommodate the network community structure, with the understanding that genes in the same community tend to behave in a coordinated manner, while those in different communities tend to behave differently. In recent literature, there have been extensive studies on network and community construction \cite{zhang2017network}. Here we adopt existing construction and assume that the community structure is available prior to analysis. Assume that the $p$ genes belong to $L$ non-overlapping communities, with $p_{(l)}$ genes in community $l$. Denote $\bm{\beta}_{(l)}^k$ as the coefficient vector for community $l$ in dataset $k$.
We propose the CoFu estimate:
\begin{eqnarray}
\label{eq:cri}
&&\{\hat{\bm\beta}^k: k=1,\ldots, K\}=argmin \left\{ \sum_{k=1}^K\frac{1}{2n_k}\parallel \bm{y}^k-\bm{X}^k\bm{\beta}^k\parallel_2^2+
\lambda_1\sum_{k=1}^K\parallel\bm{\beta}^k\parallel_1
\right. \nonumber \\
&& ~~~~~~~~~~~~~~~~~~~~~~~~~~~\left.
+\lambda_2\sum_{k=1}^{K-1}\sum_{l=1}^L\parallel \bm{\beta}^k_{(l)}-\bm{\beta}^{k+1}_{(l)}\parallel_2 \right\},
\end{eqnarray}
where $\lambda_1, \lambda_2>0$ are data-dependent tuning parameters. The nonzero components of $\hat{\bm\beta}^k$ correspond to genes that are associated with the response in dataset $k$. If $\hat{\bm{\beta}}^{k_1}_{(l)}=\hat{\bm{\beta}}^{k_2}_{(l)}$, then genes in community $l$ behave the same in datasets $k_1$ and $k_2$. That is, they represent the commonality shared by the two datasets. Otherwise, they represent the difference. As such, the proposed analysis can simultaneously identify both commonality and difference.
\noindent\underline{Rationale}
In (\ref{eq:cri}), with $K$ independent datasets, the lack-of-fit measure is the sum of $K$ individual ones. Normalization by sample size is taken to avoid domination by larger datasets. The first penalty is Lasso, which has been adopted in a large number of studies. It accommodates the high data dimensionality and conducts regularized estimation and selection of relevant genes. When desirable, it can be replaced by other, more complicated penalties. For example, when it is desirable to accommodate network adjacency (between any two nodes), then Laplacian-type penalties can be further added.
The main advancement is the second penalty, which conducts community-level analysis and has a fusion form. Tailored to data analyzed in Section \ref{sec:realdata}, the penalty has been designed for datasets with a natural order. For example, dataset $k$ may correspond to cancer stage $k$. For two adjacent datasets, the fusion penalty encourages equal regression coefficients, that is, commonality. However, it is flexible and does not reinforce commonality. Different from the ``standard'' fusion penalties, it is imposed on the regression coefficients of different datasets. Different from the contrasted penalties, it conducts community-based analysis: a whole community will be concluded as behaving the same (or differently) in multiple datasets. The results so generated can be more interpretable than those individual-gene-based. In addition, with a nonzero probability, the proposed penalty may generate $\hat{\bm{\beta}}^{k_1}_{(l)}=\hat{\bm{\beta}}^{k_2}_{(l)}$, differing from the contrasted penalization \cite{Shi2014} which generates similar but not identical estimates. For scenarios where a natural order of data does not exist, the second penalty can be revised as $ \lambda_2\sum_{k,j=1,\ldots, K}\sum_{l=1}^L\parallel \bm{\beta}^k_{(l)}-\bm{\beta}^{j}_{(l)}\parallel_2$. Loosely speaking, the newly proposed penalty has a group Lasso form (on the differences of coefficient vectors). It can be potentially replaced by other group penalties (as well as other techniques that can conduct group selection).
\subsection{Computation}
To tackle the non-separability of the penalty, we introduce a new set of parameters: $\bm{\eta}^k=\bm{\beta}^k-\bm{\beta}^{k+1}$. In addition, we also define a set of parameters $\bm{\delta}^k=\bm{\beta}^k$ to separate the $L_1$ norm operation and the sum of squares operation defined on $\bm{\beta}^k$. Then, the minimization in (\ref{eq:cri}) is equivalent to the following constrained optimization problem
\begin{eqnarray*}
\label{eq:optimization}
\min f(\bm{\beta},\bm{\eta},\bm{\delta}) \equiv \sum_{k=1}^K\frac{1}{2n_k}\parallel \bm{y}^k-\bm{X}^k\bm{\beta}^k \parallel_2^2+\lambda_1\sum_{k=1}^K\parallel\bm{\delta}^k
\parallel_1+\lambda_2\sum_{k=1}^{K-1}\sum_{l=1}^L\parallel \bm{\eta}_{(l)}^k \parallel_2,
\end{eqnarray*}
subject to
\[\bm{\beta}^k-\bm{\beta}^{k+1}-\bm{\eta}^k=0, \ \ k=1,2,\ldots, K-1, \]
and
\[\bm{\beta}^k=\bm{\delta}^k, \ \ k=1,2, \ldots, K.\]
Here $\bm{\beta}=((\bm{\beta}^1)^\top, \ldots,(\bm{\beta}^K)^\top)^\top$, $\bm{\eta}=((\bm{\eta}^1)^\top,\ldots,(\bm{\eta}^{K-1})^\top)^\top$, and $\bm\delta=((\bm\delta^1)^\top,\ldots,(\bm\delta^K)^\top)^\top$.
By the augmented Lagrangian method\cite{Hestenes1969}, the estimates can be obtained by minimizing
\begin{eqnarray*}
\label{Lagrange}
\mathcal{L}(\bm{\beta},\bm{\eta},\bm{\delta}, \bm{u},\bm{v}) &= & f(\bm{\beta},\bm{\eta},\bm{\delta}) +\sum_{k=1}^{K-1} (\bm{u}^k)^\top(\bm{\beta}^k-\bm{\beta}^{k+1}-\bm{\eta}^k)+
\sum_{k=1}^K(\bm{v}^k)^\top (\bm{\beta}^k-\bm{\delta}^k)\nonumber \\
&& +\frac{\sigma}{2}\Big(\sum_{k=1}^{K-1}\parallel \bm{\beta}^k-\bm{\beta}^{k+1}-\bm{\eta}^k \parallel_2^2+\sum_{k=1}^K\parallel \bm{\beta}^k-\bm{\delta}^k \parallel_2^2\Big),
\end{eqnarray*}
where the dual variables $\bm{u}=((\bm{u}^1)^\top,\ldots,(\bm{u}^{K-1})^\top)^\top$ and $\bm{v}=((\bm{v}^1)^\top,\ldots,(\bm{v}^K)^\top)^\top$ are Lagrange multipliers, and $\sigma>0$ is the penalty parameter. Throughout this article, we set $\sigma=2$, which leads to satisfactory numerical results.
We compute the estimate of $(\bm\beta,\bm{\eta},\bm{\delta}, \bm{u},\bm{v})$, denoted as $(\hat{\bm\beta},\hat{\bm\eta},\hat{\bm\delta},\hat{\bm u},\hat{\bm v})$, iteratively by using the ADMM method. For a given $(\bm{\eta},\bm{\delta}, \bm{u},\bm{v})$, to obtain the update of $\bm{\beta}$, we set
$\partial L/\partial \bm\beta$ to be zero, where
\begin{eqnarray*}
L&=&\sum_{k=1}^K\frac{1}{2n_k}\parallel\bm{X}^k \bm{\beta}^k-\bm{y}^k \parallel_2^2\nonumber \\
& & +\frac{\sigma}{2}\Big(\sum_{k=1}^{K-1}\parallel \bm\beta^k-\bm\beta^{k+1}-\bm\eta^k+\bm u^k/\sigma\parallel_2^2+\sum_{k=1}^K\parallel \bm\beta^k-\bm\delta^k +\bm v^k/\sigma\parallel_2^2\Big)\nonumber\\
&=& \frac{1}{2}\parallel\bm{X} \beta-\mathbf{y} \parallel_2^2+\frac{\sigma}{2}\Big(\parallel \bm{A}\bm\beta-\bm\eta+\bm u/\sigma\parallel_2^2+\parallel\bm\beta-\bm\delta+\bm v/\sigma\parallel_2^2\Big).
\end{eqnarray*}
$\bm{X}={\rm{diag}}(\bm{X}^1/\sqrt{n_1},\dots,\bm{X}^k/\sqrt{n_k})$, $\bm{y}=((\bm{y}^1/\sqrt{n_1})^\top,\ldots,
(\bm{y}^K/\sqrt{n_k})^\top)^\top$. $e_j$ is the length-$K$ column vector, with the $j$th element equal to 1 and the rest equal to 0. $\Delta=\{e_j-e_{j+1}, j=1,\ldots,K-1\}^\top$. $\bm{A}=\Delta \otimes \bm{I}_p$, where $\bm{I}_p$ denotes the $p\times p$ identity matrix, and $\otimes$ denotes the Kronecker product.
Thus, for a given $(\bm\eta(t),\bm \delta(t), \bm u(t),\bm v(t))$ at the $t$th iteration,
\begin{eqnarray}
\label{up:beta}
\bm\beta(t+1) = [\bm X^\top \bm X+\sigma(\bm{A}^\top \bm A+\bm I_{pK})]^{-1}
\times \{\bm X^\top \bm y+\sigma[\bm A^\top(\bm\eta(t)-\bm u(t)/\sigma)+\bm \delta(t)-\bm v(t)/\sigma]\},
\end{eqnarray}
where $\bm{I}_{pK}$ denotes the $pK\times pK$ identity matrix.
The component of the Lagrange function $\mathcal{L}(\bm{\beta},\bm{\eta},\bm{\delta}, \bm{u},\bm{v})$ that depends on $\bm\delta$ is
\begin{equation*}
\lambda_1 \parallel \bm\delta \parallel_1+\frac{\sigma}{2}\parallel \bm\beta-\bm\delta+\bm v/\sigma \parallel_2^2.
\end{equation*}
Hence, the closed-form solution for $\bm\delta$ is
\begin{equation*}
\hat{\bm\delta}=\mathrm{ST}_{\lambda_1/\sigma}(\bm\beta+\bm v/\sigma),
\end{equation*}
where $\mathrm{ST}_{\lambda}(x)=\mathrm{sign}(x)(|x|-\lambda)_+$ is the soft thresholding function, and $(x)_+=x$ if $x>0$, and $(x)_+=0$ otherwise. Then, the update of $\bm \delta$ at the $(t+1)$th iteration is
\begin{equation}
\label{up:delta}
\bm\delta(t+1)=\mathrm{ST}_{\lambda_1/\sigma}[\bm\beta(t+1)+\bm v(t)/\sigma].
\end{equation}
For $\bm\eta^k$, the relevant component in $\mathcal{L}(\bm{\beta},\bm{\eta},\bm{\delta},\bm{u},\bm{v})$ is
\begin{equation}
\label{eq:eta}
\lambda_2\parallel \bm\eta^k_{(l)}\parallel_2+\frac{\sigma}{2} \parallel \bm\beta^{k}_{(l)}- \bm\beta^{k+1}_{(l)}-\bm\eta^k_{(l)}+\bm u^{k}_{(l)}/\sigma\parallel_2^2.
\end{equation}
The minimizer of (\ref{eq:eta}) is
\begin{equation*}
\hat{\bm\eta}^k_{(l)}=\Big( 1-\frac{\lambda_2}{\sigma\parallel \bm\beta^k_{(l)}-\bm\beta^{k+1}_{(l)}+\bm u^k_{(l)}/\sigma\parallel_2} \Big)_{+} (\bm\beta^k_{(l)}-\bm\beta^{k+1}_{(l)}+\bm u^k_{(l)}/\sigma), \ k=1,2,\ldots, K-1.
\end{equation*}
We can thus obtain the update of $\bm \eta^k_{(l)}$ at the $(t+1)$th iteration as
\begin{eqnarray}
\label{up:eta}
\bm \eta^k_{(l)}(t+1) = \Big( 1-\frac{\lambda_2}{\sigma\parallel \bm\beta^k_{(l)}(t+1)-\bm\beta^{k+1}_{(l)}(t+1)+\bm u^k_{(l)}(t)/\sigma\parallel_2} \Big)_{+}
\times [\bm \beta^k_{(l)}(t+1)-\bm \beta^{k+1}_{(l)}(t+1)+\bm u^{k}_{(l)}(t)/\sigma].
\end{eqnarray}
Finally, the estimates of $\bm u$, $\bm v$ are updated as
\begin{eqnarray}
&& \bm u(t+1) = \bm u(t)+\sigma[\bm A \bm \beta(t+1)-\bm \eta(t+1)],\label{up:u}\\
&&\bm v(t+1) = \bm v(t)+\sigma[\bm \beta(t+1)-\bm \delta(t+1)].\label{up:v}
\end{eqnarray}
\noindent\underline{Overall algorithm}
The overall algorithm proceeds as follows:
\noindent Step 1: Initialize $\bm \beta(0)$. Let $\bm \delta(0)=\bm \beta(0)$, $\bm \eta(0)=\bm A\bm \beta(0)$, $\bm u(0)=0$, and $\bm v(0)=0$. In our numerical study, we use the Lasso estimate (without fusion) as the initial value.
\noindent Step 2: At the $(t+1)$th iteration, compute $\bm \beta(t+1), \bm \delta(t+1), \bm \eta(t+1), \bm u(t+1)$ and $\bm v(t+1) $ according to Eqs. (\ref{up:beta}), (\ref{up:delta}), (\ref{up:eta}), (\ref{up:u}), and (\ref{up:v}), respectively.
\noindent Step 3: Repeat Step 2 until convergence. Specifically, convergence is concluded if all of the primal residuals and dual residuals are small enough, that is,
\begin{equation*}
\max\{\parallel \bm{A}\bm{\beta(t+1)}-\bm{\eta(t+1)} \parallel_2 , \parallel \bm{\beta(t+1)}-\bm{\delta(t+1)} \parallel_2,\parallel \bm{\delta(t+1)}-\bm{\delta(t)} \parallel_2, \parallel \bm{\eta(t+1)}-\bm{\eta(t)} \parallel_2\}<\epsilon.
\end{equation*}
In numerical study, $\epsilon$ is set to be $10^{-3}$.
\noindent\underline{Tuning parameter selection}
The proposed approach involves two tuning parameters: $\lambda_1$ and $\lambda_2$. In numerical study, they are selected using V-fold cross validation (CV). In this article, $V=5$. More specifically, each dataset is partitioned randomly into 5 non-overlapping subsets with equal sizes. We apply a two-dimensional grid search for $\lambda_1$ and $\lambda_2$ with $\lambda_2\in(0.001,0.01,0.1,1)$. Let $\lambda_1^{\text{max}}$ be the minimal $\lambda$ such that all regression coefficients shrink to 0, i.e., $\lambda_1^{\max}=\max_{k} \parallel \frac{\bm{(X^k)}^\top\bm{y}^k}{n^k} \parallel_{\infty}$. We choose $\lambda_1^{\min}$ to be some small fraction (default value is 0.01 in our implementation) of $\lambda_1^{\max}$ and log-linearly interpolate between $\lambda_1^{\min}$ and $\lambda_1^{\max}$. For the CoFu method, the CV is computationally affordable. For example, the 5-fold CV for a simulated dataset takes less than 15 minutes on a desktop PC.
\section{Simulation}
\label{sec:sim}
In simulation, we set $K=3$, $n_k=200$, and $p=1,000$. Genes form $L=50$ non-overlapping communities, with community sizes ranging from $\frac{3p}{4L}$ to $\frac{5p}{4L}$. As in the literature \cite{Huang2017}, we simulate omics measurements from multivariate normal distributions, which may mimic gene expression data (as analyzed below). The normal distributions have marginal means 0, marginal variances 1, and correlation matrix $\Sigma$. The following correlation structures are considered: (a) structured correlation. Omics measurements within the same communities are more strongly correlated than those in different communities. More details are provided below; (b) unstructured correlation. The correlation coefficient between measurements $i$ and $j$ is randomly sampled from the uniform distribution $\mathcal{U}[0.2,1]$; and (c) no correlation. That is, all omics measurements are independent. This may serve as a test of sensitivity and examine performance of the proposed approach when there is a lack of well defined network structure.
Roughly speaking, the structured correlation matrix corresponds to the scenario where two genes within the same community are strongly correlated while two genes within different communities are weakly correlated. Since in reality it is possible that not all genes within the same community are correlated, we generate the structured correlation matrix via network-based analysis, which is considerably more complicated than in the literature and consists of the following steps: (a) generate an unweighted network with a community structure\footnote{Most networks of interest display community structures, that is, their nodes are organized into groups, called communities. The density of edges within a community is comparatively higher than that between communities.}, (b) add a weight to each edge, which quantifies the connection between two nodes (omics measurements), and (c) generate the correlation matrix $\Sigma$. More specifically, we adopt the degree-correlated stochastic block model (DC-SBM) \cite{Karrer2011} to generate an unweighted network with a community structure. To mimic networks in reality, we generate a degree sequence of nodes following the power-law distribution with exponent $\gamma$. For each pair of nodes $i$ and $j$, an undirected edge is placed with probability
\begin{equation}
\label{pij_unnorm}
p_{ij}=\frac{<d>p}{Z}d_i d_j q_{m_im_j},
\end{equation}
where $Z=\sum_{i,j}d_i d_j q_{m_im_j}$ is the normalization constant, $d_i$ is the degree of node $i$, $<d>$ is the average degree of nodes, and $m_i$ represents the community that node $i$ belongs to. $q_{m_im_j}$ represents the connection probability between communities $m_i$ and $m_j$. If $m_1=m_2$, $q_{m_1m_2}$ is sampled from an uniform distribution $\mathcal{U}[0.3,0.5]$, otherwise $q_{m_1m_2}=0.02$. In all simulations, we set $\gamma=2.5$ and $<d>=10$.
Next, we add a weight to each edge. Specifically, for edges between nodes in the same community and edges between nodes in different communities, weights are sampled independently from uniform distributions $\mathcal{U}[0.5, 1]$ and $\mathcal{U}[0.2, 0.5]$, respectively. Denote the adjacency matrix of the weighted network as $\Sigma_0$, with all diagonal elements equal to 1. Note that $\Sigma_0$ is not necessarily positive definite. To guarantee positive definiteness, we set $\Sigma=\Sigma_0-(\lambda_{\min}-\frac{1}{p})\bm{I}_{p}$, where $\lambda_{\min}$ is the smallest eigenvalue of $\Sigma_0$, and $\bm{I}_p$ is the $p\times p$ identity matrix. For a more intuitive presentation, we plot one simulated structured correlation matrix in Figure \ref{fig:sigma} (Appendix \ref{sec:table}) with $p=200$, $L=10$, and other parameters as described above. As shown in the figure, only genes that are connected by an edge are correlated. The correlation between two connected genes within the same community is strong, whereas that between two connected genes from different communities is weak.
Each dataset has $r$ important omics measurements with $r=100$ and 150, which are distributed uniformly across communities. All communities are divided randomly into three categories: (a) all-overlapping, where the three datasets have the same sparsity structure and also the same regression coefficients; (b) half-overlapping, where datasets 1 and 2 share half of the important effects, for which the regression coefficients are identical. The same is true for datasets 2 and 3. Half of the important effects in datasets 2 and 3 are dataset-specific; and (c) non-overlapping, where there is no important effect shared by any two datasets. Denote $\rho_a$, $\rho_h$, $\rho_n$ ($\rho_a+\rho_h+\rho_n=1$) as the proportions of all-, half-, and non-overlapping communities, respectively. For the important effects, their regression coefficients are (a) all set to be 0.5; (b) sampled from the uniform distribution $\mathcal{U}[0.2,1]$; and (c) sampled from different distributions. Specifically, the nonzero regression coefficients in dataset 2 are from $\mathcal{U}[0.4,0.7]$, those specific to dataset 1 are from $\mathcal{U}[0.1,0.3]$, and those specific to dataset 3 are from $\mathcal{U}[0.8,1]$. The random errors are simulated independently from $N(0,1)$. The response variables are computed from the linear models.
\begin{table}[htbp]
\centering
\caption{
Simulation under the LR model: mean(sd) of AUC for effect identification. All nonzero coefficients are equal to 0.5.}
\begin{tabular}{lcccccc}
\toprule
& & $r=100$ & & & $r=150$\\
\cmidrule(r){2-4} \cmidrule(l){5-7
& structured &unstructured & independence &structured &unstructured & independence \\
\midrule
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.1,0,0.9)$} \\
P.Lasso & 0.619(0.014)&0.593(0.015)&0.62(0.013)&0.578(0.017)&0.574(0.013)&0.579(0.018)\\
S.Lasso & 0.77(0.009)&0.833(0.01)&0.761(0.012)&0.695(0.015)&0.777(0.01)&0.685(0.012)\\
CoFu &0.771(0.01)&0.813(0.012)&0.753(0.012)&0.694(0.012)&0.762(0.012)&0.676(0.013)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.1,0.9,0)$} \\
P.Lasso &0.732(0.015)&0.743(0.02)&0.725(0.015)&0.621(0.02)&0.703(0.012)&0.646(0.021)\\
S.Lasso &0.781(0.013)&0.85(0.012)&0.782(0.012)&0.689(0.013)&0.787(0.007)&0.687(0.013)\\
CoFu &0.827(0.013)&0.891(0.008)&0.814(0.009)&0.73(0.012)&0.8(0.012)&0.716(0.015)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.2,0.6,0.2)$} \\
P.Lasso & 0.752(0.017) &0.719(0.023) &0.744(0.017) &0.689(0.018) &0.666(0.014) &0.68(0.016)\\
S.Lasso & 0.772(0.011) & 0.847(0.011) & 0.76(0.011) & 0.699(0.012) &0.786(0.008) &0.689(0.01)\\
CoFu &0.838(0.012) &0.878(0.007) &0.826(0.01) & 0.762(0.008) &0.803(0.01) &0.753(0.011)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.4,0.1,0.5)$} \\
P.Lasso & 0.746(0.012) &0.741(0.012) &0.739(0.012) &0.698(0.013) &0.684(0.01) &0.69(0.014)\\
S.Lasso & 0.775(0.007) & 0.831(0.013) & 0.752(0.013) &0.691(0.016) &0.775(0.008) &0.681(0.017)\\
CoFu &0.823(0.009) &0.865(0.011) &0.817(0.008) &0.756(0.017) &0.795(0.011) &0.746(0.016)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.5,0.5,0)$} \\
P.Lasso & 0.885(0.013) &0.866(0.007) &0.885(0.01) &0.82(0.019) &0.799(0.017) &0.812(0.017)\\
S.Lasso & 0.776(0.011) &0.834(0.009)& 0.764(0.015) & 0.692(0.015) &0.781(0.009) &0.69(0.009)\\
CoFu &0.894(0.011) &0.893(0.005) &0.891(0.011) &0.817(0.009) &0.839(0.011)&0.816(0.01) \\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.6,0.2,0.2)$} \\
P.Lasso & 0.878(0.011) & 0.847(0.013) &0.873(0.009) & 0.831(0.022) &0.779(0.016) &0.809(0.024) \\
S.Lasso &0.762(0.012) &0.831(0.011) &0.76(0.013) & 0.692(0.016) & 0.777(0.009) & 0.684(0.018) \\
CoFu &0.887(0.011) &0.888(0.009) &0.881(0.008) &0.822(0.017) &0.829(0.011) &0.827(0.019)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.9,0,0.1)$} \\
P.Lasso &0.89(0.014)&0.925(0.02)&0.872(0.015)&0.832(0.017)&0.884(0.012)&0.828(0.02)\\
S.Lasso &0.768(0.009)&0.845(0.012)&0.774(0.012)&0.691(0.013)&0.785(0.008)&0.685(0.015)\\
CoFu &0.876(0.013)&0.899(0.008)&0.859(0.01)&0.805(0.012)&0.864(0.012)&0.798(0.014)\\
\bottomrule
\end{tabular}
\label{tab:var1}
\end{table}
\begin{table}[htbp
\centering
\caption{
Simulation under the LR model: mean(sd) of AUC for community differentiation. All nonzero coefficients are equal to 0.5.
}
\begin{tabular}{lcccccc}
\toprule
& & $r=100$ & & & $r=150$\\
\cmidrule(r){2-4} \cmidrule(l){5-7
& structured &unstructured & independence &structured &unstructured & independence \\
\midrule
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.1,0,0.9)$} \\
S.Lasso &0.578(0.035)&0.54(0.097)&0.571(0.066)&0.565(0.078)&0.515(0.105)&0.537(0.068)\\
CoFu &0.739(0.033)&0.762(0.038)&0.724(0.042)&0.711(0.042)&0.74(0.042)&0.679(0.039)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.1,0.9,0)$} \\
S.Lasso &0.543(0.057)&0.54(0.092)&0.53(0.066)&0.496(0.088)&0.468(0.105)&0.484(0.071)\\
CoFu &0.712(0.038)&0.762(0.036)&0.724(0.043)&0.692(0.042)&0.691(0.062)&0.656(0.052)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.2,0.6,0.2)$} \\
S.Lasso & 0.573(0.082) & 0.54(0.105) & 0.549(0.074) & 0.517(0.066) &0.52(0.119) &0.509(0.081)\\
CoFu &0.744(0.032) &0.721(0.05) &0.704(0.048) & 0.679(0.049) &0.71(0.053) &0.679(0.042)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.4,0.1,0.5)$} \\
S.Lasso & 0.565(0.043) & 0.541(0.091) & 0.557(0.061) &0.538(0.063) &0.531(0.1) &0.552(0.06)\\
CoFu &0.749(0.031) &0.746(0.032) &0.752(0.038) &0.724(0.049) &0.737(0.066) &0.73(0.057)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.5,0.5,0)$} \\
S.Lasso & 0.533(0.048) & 0.49(0.103) & 0.552(0.062) & 0.476(0.099) &0.492(0.124) &0.513(0.084)\\
CoFu &0.777(0.043) &0.771(0.029) &0.779(0.046) &0.728(0.038) &0.724(0.036)&0.729(0.03) \\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.6,0.2,0.2)$} \\
S.Lasso & 0.515(0.036) & 0.5(0.096) & 0.53(0.043) &0.438(0.093) &0.477(0.1) &0.486(0.087)\\
CoFu &0.755(0.053) &0.755(0.041) &0.779(0.04) &0.685(0.051) &0.721(0.046) &0.694(0.033)\\
\multicolumn{3}{l}{$(\rho_a,\rho_h,\rho_n)=(0.9,0,0.1)$} \\
S.Lasso &0.518(0.066)&0.498(0.098)&0.54(0.07)&0.466(0.078)&0.441(0.098)&0.45(0.076)\\
CoFu &0.965(0.042)&0.965(0.048)&0.975(0.042)&0.947(0.045)&0.907(0.048)&0.961(0.048)\\
\bottomrule
\end{tabular}
\label{tab:group1}
\end{table}
We compare CoFu with
two closely related alternatives: (a) P.Lasso, which pools all datasets together and applies Lasso. This approach emphasizes commonality but cannot detect difference across datasets; and (b) S.Lasso, which applies Lasso to each dataset separately, and then the results are combined and compared. This is virtually a meta-analysis strategy, allows difference, but cannot encourage commonality.
For CoFu and the alternatives, we are mainly interested in two identification accuracy. The first, as in many other studies, is the identification of nonzero effects. The second, which is unique to this study, is the identification of communities that behave the same/differently in different datasets. More precisely, for a given community, if the $L_2$ norm of the difference between the regression coefficient vectors of two adjacent datasets is less than 0.01, we conclude commonality; otherwise, difference is concluded. The identified commonality/difference is compared against the true. For the proposed as well as alternatives, tuning parameter values affect identification performance. To get a more comprehensive view and minimize the (possibly different) impact of tuning on different methods, we follow the literature, consider a sequence of tunings, and evaluate using the ROC (receiver operating characteristic) approach, under which the AUC is the measure of identification accuracy (more details in Appendix \ref{sec:AUC}). Considering that in practice a definitive set of results may be desirable, we also evaluate identification results using true/false positive rates with tunings selected using 5-fold CV. In addition, we evaluate estimation and prediction performance. Specifically, estimation is quantified by using ERMSE (estimation RMSE), which is defined as $\sqrt{\sum_k \parallel \bm{\beta}^k-\hat{\bm{\beta}}^k\parallel^2_2}$, and prediction is quantified by using PRMSE (prediction RMSE), which is defined as $\sqrt{\sum_k \parallel \bm{y}^k-\bm{X}^k\hat{\bm{\beta}}^k\parallel^2_2}$.
We simulate 100 replicates for each setting. For the settings with all nonzero coefficients equal to 0.5, we show the identification of nonzero effects in Table \ref{tab:var1} and differentiation of communities with commonality/difference in Table \ref{tab:group1}, where the AUC summaries are presented. Results for the other settings are shown in Appendix \ref{sec:table}. The proposed CoFu is observed to have favorable performance in identifying nonzero effects. Consider for example Table \ref{tab:var1}. With $r=100$, $(\rho_a,\rho_h,\rho_n)=(0.4,0.1,0.5)$, and the structured correlation, the mean AUCs are 0.746 (P.Lasso), 0.775 (S.Lasso), and 0.823 (CoFu), respectively. Performance of S.Lasso is not strongly affected by the overlapping across datasets, as it analyzes each dataset separately. In general, S.Lasso has good performance, however, is inferior to CoFu under most settings. P.Lasso has superior performance when the sets of important effects in the three datasets almost entirely overlap, for example, when $(\rho_a,\rho_h,\rho_n)=(0.9,0,0.1)$. However, as expected, its performance deteriorates significantly when there are large differences across datasets. It is noted that CoFu still has competitive performance even under the worst case scenario, thus providing a ``safe'' choice in practice. Similar observations are also made under the other settings as presented in Appendix \ref{sec:table}. In the differentiation of community commonality/difference, note that as P.Lasso is not capable of identifying differences across datasets, its results are not presented. Simulation shows that CoFu significantly outperforms S.Lasso. For example in Table \ref{tab:group1} with $r=100$ and $(\rho_a,\rho_h,\rho_n)=(0.1,0,0.9)$, CoFu has AUCs 0.739 (structured), 0.762 (unstructured), and 0.724 (independence), respectively, while S.Lasso has AUCs below 0.6. For the settings presented in Appendix \ref{sec:table}, the observed patterns are similar. The results with tunings selected using CV are presented in Table \ref{tab:CV1}-\ref{tab:CV3} (Appendix \ref{sec:table}). The CoFu method is observed to have superior performance in terms of identification, estimation, and prediction.
Simulation is also conducted under the Logit model, a representative of generalized linear models. Details of the estimation procedure are presented in Appendix \ref{sec:logit}. In simulation, covariates are generated in the same way as described above. The response values are generated from the Logit model and Bernoulli distribution. The identification results measured by AUCs are presented in Table \ref{tab:log1}-\ref{tab:log2} (Appendix \ref{sec:table}). The CoFu method is observed to have similar superior identification performance as under the LR model. It is noted that the improvement over the alternatives may not be as large as under the LR model. To this end, we conduct a nonparametric test on the paired AUC values and find that the improvement is statistically significant for all scenarios. For example, for $r=100$, $(\rho_a,\rho_h,\rho_n)=(0.1,0,0.9)$, and from $\mathcal{U}[0.2,1]$, the differences between the CoFu's and S.Lasso's AUC values have p-values 0.002 and $<10^{-9}$ for nonzero effect and community identification, respectively.
\section{Data analysis}
\label{sec:realdata}
TCGA (The Cancer Genome Atlas) is a collaborative effort organized by NCI and has recently published high-quality profiling data on multiple cancer types. The analysis of TCGA data has led to interesting findings. In our analysis, both clinical and genetic data are downloaded from the cBioPortal website.
\subsection{Analysis of cutaneous melanoma data}
\label{sec:mel}
We first consider the SKCM (cutaneous melanoma) data \cite{akbani2015genomic}. As in the literature \cite{jiang2016integrated}, the inclusion criteria are: (1) white patients, (2) no neo-adjuvant therapy before tumor sample collection, (3) the type of skin upon which melanoma arose is non-glabrous skin, (4) no missing values in Breslow thickness and AJCC pathologic tumor stage, and (5) with gene expression measurements. In our analysis, we are interested in the regulation of Breslow thickness, which is an important prognostic marker, by gene expressions. In published studies \cite{chai2017analysis}, similar analysis has been conducted, however, {\it using samples of all tumor stages and with insufficient attention to the potential difference across stages}. Partly motivated by Figure \ref{fig:gene}, our ``hypothesis'' is that the regulation relationships for different stages have commonality as well as difference. There are a total of 240 samples, with 70 in stage I, 60 in stage II, and 110 in stages III and IV.
A total of 18,947 gene expression measurements are available. From the KEGG pathway database downloaded from the Broad Institute, we identify 5,266 unique genes, representing 186 pathways. Matching those gene names with those in the SKCM dataset, we identify 4,243 genes for downstream analysis. Although in principle it is possible to directly apply the proposed approach to these genes, to obtain more reliable analysis results, we further conduct a supervised screening. Specifically, we compute the Pearson correlation coefficient of each gene with the response variable and identify those with p-values less than 0.05. A total of 973 genes are identified. We construct a dense network based on correlations and then generate a sparse one by filtering out edges that are not statistically significant at the 0.05 level \cite{Serrano2009}. The resulted network has 15,891 edges (detailed structure available from the authors). The Louvain method \cite{Blondel2008}, which performs a greedy optimization of community identification in a hierarchical manner, is applied and identifies 46 communities.
\begin{figure}[h] %
\centering
\includegraphics[width=7.5in]{plot/beta_Mela.pdf}
\caption{Analysis of the TCGA SKCM data. Blue crosses correspond to stage I, red circles to stage II, and green filled circles to stage III and IV.}
\label{fig:Mela}
\end{figure}
The analysis results of CoFu are summarized in Figure \ref{fig:Mela}. Briefly, a total of 21 communities, with 126 genes, are identified as associated with the response. Among them, 8 communities behave the same across the three stages, and the rest behave differently. More detailed estimation results are available from the authors. Simply eyeballing Figure \ref{fig:Mela} suggests that some communities, for example 22, 39, and 45, demonstrate significantly different stage-specific properties. Such differences have not been well noted in the literature and deserve additional attention. Literature search suggests that the CoFu identified genes may have important implications. For example, the gene that has the strongest signal in all three stages is ARMC, armadillo repeat containing 2. It belongs to a family of Armadillo repeat proteins, which play important roles in cell-cell adhension, cytoskeletal regulation and intracellular signaling. Other genes that also have strong signals in all three stages include C10orf114 and KTGNR. C10orf114 is also known as CASC10. Over expression of C10orf114 is associated with poor survival in glioma and urothelial cancer (www.proteinatlas.org/ENSG00000204682-CASC10/cell). KTGNR (DNAH5) encodes an axonemal heavy chain of dynein proteins. It works as a force-generating protein with ATPase activity. The TRA2B-DNAH5 fusion has been identified as a novel oncogenic driver in lung cancer \cite{Li2016}. In addition to the genes that are associated with Breslow depth in all three stages, we have also identified genes that have strong signals only in the earlier or later stages. The top three genes that only have strong signals in stage I are DKFZP434B094, AK3 and ANKS1A. AMN and PDCR are found to have strong signals only in stage II. FAM219B and BSDC1 are found to be stage III and IV specific. In addition, genes that are more associated with Breslow depth in later stages are LOC392331, ANKRD20A20P, CRELD2, CEBPG, and others. CEBPG is one of the C/EBP transcription factors that regulate cell growth and differentiation of various tissues. One study has shown that CEBPG is a suppressor of myeloid differentiation in acute myeloid leukemia \cite{Alberichjord2012}.
Different findings are generated by the alternatives. The estimated coefficients are plotted in Figures \ref{fig:lasso_Mela} (S.Lasso) and \ref{fig:single_Mela} (P.Lasso) in Appendix \ref{sec:table}. S.Lasso identifies 38 communities, with 176 genes, as associated with the response variable, and P.Lasso identifies 39 communities, with 105 genes. With their particular properties, S.Lasso identifies all communities (with nonzero effects) as behaving differently across stages, while P.Lasso identifies all communities as behaving the same. Biologically speaking, the CoFu results, which have both commonality and difference, are more sensible.
We also evaluate prediction performance and stability of each method. Specifically, each dataset is randomly divided into a training and testing set, with sizes 2:1. The regression parameters are estimated only using the training set and used to make prediction for the testing set. We use the root mean square error (RMSE) of the response variable to measure prediction. For the three methods, the RMSEs are calculated as 1.077 (P.Lasso), 1.095 (S.Lasso) and 1.005 (CoFu). In addition, for each gene, we compute the proportion of being identified in 100 resamplings, which has been referred to as the Observed Occurrence Index (OOI) in the literature, to measure the stability of this gene. The highest 20 OOIs are shown in Figure \ref{fig:OOI} (Appendix \ref{sec:table}). CoFu has OOIs (0.823) higher than P.Lasso (0.782) and S.Lasso (0.711).
\subsection{Analysis of lung cancer data}
In TCGA, there are two lung cancer datasets, on Lung Adenocarcinoma (LUAD) and Lung Squamous Cell Carcinoma (LUSC), respectively. In the literature, they have been separately analyzed \cite{cancer2014comprehensive,cancer2012comprehensive}, and differences have been acknowledged \cite{sun2017bioinformatics}. However, as they are both non-small cell lung carcinomas, certain commonality is expected. For both LUAD and LUSC, the inclusion criteria are: (1) no neo-adjuvant therapy before tumor sample collection, (2) in stage I of the AJCC pathologic tumor stage measurement, and (3) with FEV1 (forced expiratory volume in 1sec, prebroncholiator) and gene expressions measured. More details on sample selection are provided in Figure \ref{fig:flowchart} (Appendix \ref{sec:table}). In this analysis, the response variable is FEV1, a critical measure of lung function. The final sample sizes are 142 (LUAD) and 89 (LUSC), respectively. For gene expressions, we conduct a similar processing as described above. Specifically, 20,531 gene expressions are initially available for analysis. Matching with the KEGG pathway information leads to 4,243 genes. The p-value based marginal screening further reduces the number of gene expressions to 901. Using the same approach as described above, 41 communities are constructed.
\begin{figure}[h] %
\includegraphics[width=7.5in]{plot/beta_Lung.pdf}
\caption{Analysis of the TCGA lung cancer data. Blue crosses correspond to LUAD, and red circles to LUSC.}
\label{fig:Lung}
\end{figure}
The analysis results of CoFu are summarized in Figure \ref{fig:Lung}. A total of 26 communities, with 54 genes, are identified as associated with the response. Among them, 13 communities behave the same for both LUAD and LUSC. Figure \ref{fig:Lung} suggests that some communities, for example 9 and 13, behave significantly differently for LUAD and LUSC.
Literature review again suggests that the findings are biologically sensible. Specifically, among the identified genes, CCNG2 has the strongest signal for both LUAD and LUSC. CCNG2 encodes protein cyclin G2, which has been shown to be a tumor suppressor in several studies \cite{Wang2016, Yao2017}. A recent study shows that lung cancer patients with higher CCNG2 expressions had longer overall survival. Another gene that has a strong signal in both cancers is BRI3BP, BRI3-binding protein. Over expressions of BRI3BP are found to promote drug induced apoptosis via cross talking between mitochondria and endoplasmic reticulum (ER). We also identify 24 genes that are associated with the response in LUAD but not LUSC. Among them, Chemokine-like receptor 1 (CMKLR1) has the strongest signal. CMLKLR1 is a transmembrane multifunctional receptor and found to play an important role in inflammatory. One genetic variant of CMLKLR1, rs1878022, is found to be significantly associated with poorer survival in advanced stage non-small cell lung cancer \cite{wu2011genome}. Another gene that we find to be associated with lung function in LUAD only is DLGAP5, DLG associated protein 5. DLGAP5 is a mitotic spindle protein and involved in mitosis processes. A study by Schneider et al.\cite{Schneider2017} shows that DLGAP5 expression is higher in lung tumor tissues. Lung cancer patients with the overexpression of DLGAP5 tend to have poorer survival. Genes that have strong signals in LUSC but not LUAD include CALHM2, BTBD3, CLPP, and others. CALHM2 encodes protein calcium homeostasis modulator family member 2, which plays a critical role in the modulation of neural activity via ATP-releasing channel. The BTB domain-containing 3 (BTBD3) gene is found to be upregulated in Hepatocellular carcinoma tissues \cite{Xiao2017}. The genetic variant of BTBD3 is also found to be significantly associated with survival in non-small cell lung cancer patients \cite{Wu2010}. CLPP, caseinolytic mitochondrial matrix peptidase proteolytic subunit, belongs to the peptidase family S14. Its function is to hydrolyze proteins into small peptides in the mitochondria matrix. Increased protein expression is found in type I endometrial cancer patients \cite{Cormio2017}.
The alternative analysis results are presented in Figures \ref{fig:lasso_Lung} (S.Lasso) and \ref{fig:single_Lung} (P.Lasso) in Appendix \ref{sec:table}. S.Lasso identifies 27 communities with 44 genes. No commonality is identified. P.Lasso identifies 31 communities with 44 genes, all of which behave the same for the two cancers. In terms of prediction, the CoFu RMSE is 0.917, lower than S.Lasso (0.999) and P.Lasso (1.023). The OOI results are represented in Figure \ref{fig:OOI} (Appendix \ref{sec:table}). CoFu has the highest OOIs among the three methods.
\subsection{Simulation}
It has been recognized in some studies that simulated data may be ``simpler'' than real data. Here we conduct an additional set of simulation based on the SKCM data analyzed above. Specifically, the observed gene expression data and community structure are used in simulation. The structure of important covariate effects is the same as described above in Section \ref{sec:sim}. The identification results for community and individual effects are summarized in Table \ref{tab:realdata} (Appendix \ref{sec:table}). Although there are some small numerical differences, the observed patterns are similar to those in Section \ref{sec:sim}, providing a strong support to the effectiveness of the proposed method.
\section{Discussion}
In the literature, although the commonality and difference of ``related'' cancers have been noted, effective analysis methods are still lacking. This study fills this knowledge gap by developing a novel community fusion method. The CoFu method has an intuitive formulation and can be effectively realized. Although sharing some similar spirits with the existing fused and contrasted penalization methods, it also has significant advancements by conducting the integrative analysis of multiple datasets, promoting commonality as opposed to similarity, and accommodating the community structure among genes. Numerical studies have demonstrated its superiority over the direct competitors. We have mostly described the proposed method under the linear regression model. As described in Appendix \ref{sec:logit} as well as in the simulation, the proposed method can be extended to the Logit model, a representative of generalized linear models. A closer examination of the penalty function and computation suggests that the CoFu method can be potentially coupled with others, for example prognosis, outcomes and models. More complicated penalties can take the place of Lasso. For example, when it is desirable to accommodate network adjacency, Laplacian penalties can be further imposed. The group Lasso type fusion penalty can also be replaced by other group penalties.
In the first data analysis, the ``stratification'' variable is cancer stage, which has a sound biological basis. It should be noted that, as demonstrated in simulation, the proposed method can accommodate different degrees of commonality/difference. As such, the choice of the stratification variable is not critical. In fact, the proposed method can be applied to ``test'' whether the response-omics relationships are the same with respect to a specific stratification variable.
Limitations of this study may include a lack of theoretical investigation and deeper bioinformatics analysis of the data analysis results.
Such pursuit will be deferred to future research. We will also defer possible extensions as discussed above to future research.
\section*{Acknowledgments}
We thank the associate editor and two reviewers for careful review and insightful comments, which have led to a significant improvement of the article. We thank Pan Zhang for sharing computer code, which helps data generation in simulation.
This study was supported by National Natural Science Foundation of China (11605288, 71771211), MOE (Ministry of Education in China) Project of Humanities and Social Sciences (16YJCZH088), Fund for building world-class universities (disciplines) of Renmin University of China, Bureau of Statistics of China (2016LD01), and National Institute of Health (CA204120, CA216017, CA121974).
\subsection*{Conflict of interest}
The authors declare no potential conflict of interests.
| {'timestamp': '2022-12-01T02:20:25', 'yymm': '2211', 'arxiv_id': '2211.17203', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17203'} | arxiv |
\section{Introduction}
The learning of multiple related tasks is often observed in real-world applications, such as computer vision [\cite{CV}], web research [\cite{web}], bioinformatics [\cite{bioinformatics}], and others. Multi-task learning (MTL) is a common machine learning method that is used to solve this problem. To be more specific, MTL learns multiple related tasks simultaneously while exploiting commonalities and differences across the tasks. This can lead to better generalization performance compared to that from learning each task separately. The key challenge in MTL is how to screen the common information across related tasks while preventing information from being shared among unrelated tasks. To tackle this challenge, a multitude of MTL approaches have been proposed in the last decade. Among these approaches, feature selection approaches [\cite{feature_selection1,feature_selection4}] and task clustering approaches [\cite{Gauss2,trace1}] have been the most commonly investigated.
The feature selection approaches aim to select a subset of the original features to serve as the shared features for different tasks, which can be achieved via the regularization [\cite{feature_selection1}] or sparse prior [\cite{SparsePrior2}] of the coefficient matrix. Compared with other methods, the feature selection methods provide better interpretability. However,
the assumption that all tasks share identical or similar relevant features is too strong to be valid in many applications. Moreover, information can only be shared in the original feature space, which limits the ability to share information across tasks.
Inspired by the idea of data clustering, the task clustering approaches group tasks into several clusters with similar coefficients.
Earlier studies focused on identifying the disjoint task clusters, which can be realized via a two-stage strategy [\cite{TwoStage2}], a Gaussian mixture model [\cite{Gauss2}], or regularizations [\cite{cluster2,representative}]. Such hard clustering may not always reflect the true clustering structure and may result in the inaccurate extraction of information shared among tasks. To this end, recent studies have focused on improvements through allowing partial overlaps between different clusters, such that each task can belong to multiple clusters [\cite{overlap2,Go-MTL,VSTG}]. This is achieved by decomposing the original coefficient matrix into a product of a matrix consisting of coefficient vectors in different clusters and a matrix containing combination weights.
Due to their flexibility and ability to reduce unknown coefficients substantially, task-clustering approaches have attracted widespread attention in the field of MTL. Although great progress has been made in the task-clustering approaches, the existing approaches still have several limitations. First, few task clustering approaches conduct feature selection, which may affect interpretability and generalizability to some degree. Second, most task-clustering approaches assume that task parameters within a cluster lie in a low dimensional subspace, which we have little information about. As a result, two major issues would arise: the cluster structure could become non-identifiable in a latent space, and the characteristics of individual clusters would be blurred. This would limit their applications in areas such as biomedicine and economics, where the reliability and interpretability of results are especially valued.
Motivated by the idea of the semisoft clustering of data [\cite{Zhu2019Semisoft,LOVE}], we propose a novel semisoft task clustering MTL (STCMTL) approach, which can simultaneously reveal the task cluster structure for both pure tasks and mixed tasks and select relevant features. A pure task is a task that belongs to a single cluster, while a mixed task is one that belongs to two or more clusters. The key insights of the STCMTL are as follows: (a) pure and mixed tasks co-exist (which is why the term "semisoft" is used); and (b) each mixed task can be represented by a linear combination of pure tasks in different clusters, where the linear combination weights are nonnegative numbers that sum to one (called memberships) and represent the proportions of the mixed task in the corresponding clusters. The idea of representing a task as a linear combination of a set of pure (or representative) tasks has been widely adopted in the literature [\cite{representative,robust}]. However, these approaches cannot remove the irrelevant features. VSTG-MTL [\cite{VSTG}] is the most relevant method to ours, which can simultaneously perform feature selection and learn an overlapping task cluster structure by encouraging sparsity within the column of the weight matrix. However, this method fails to classify the pure and mixed tasks.
We formulate the semisoft task clustering problem as a constrained optimization problem. A novel and efficient algorithm is developed to solve this complex problem. Specifically, we decompose the original non-convex optimization problem into three subproblems. We then employ the semisoft clustering with pure cells (SOUP) algorithm [\cite{Zhu2019Semisoft}] that was recently proposed for data semisoft clustering to identify the set of pure tasks and estimate the soft memberships for mixed tasks. Extensive simulation studies have demonstrated the superiority of STCMTL to natural competitors in identifying cluster structure and relevant features, estimating coefficients, and especially, time cost. The effectiveness and efficiency of STCMTL are again validated in the four real-world data sets. In addition, STCMTL can be easily extended to other task clustering problems (e.g., robust task clustering) by replacing the SOUP algorithm with other corresponding algorithms.
In summary, the proposed STCMTL approach has the following advantages:
\begin{itemize}
\item It can simultaneously reveal the task cluster structure for both pure and mixed tasks as well as perform feature selection.
\item It provides an identifiable and interpretable task cluster structure.
\item Compared with its direct competitors, it requires much less calculation time and results in more precise feature selection, and it can be easily
extended to other task clustering problems.
\end{itemize}
The rest of the paper is organized as follows. We first introduce the notations and problem formulation in Section 2. The optimization procedure is presented in Section 3. In Section 4, we campare our method's experimental results with 5 other baselines on synthetic and real-world dataset. We rewrite our algotithm to a general framework and provide an alternatives under the framework in Section 5.
\section{Formulation}
Suppose we have $T$ tasks and $D$ features. In task $i (=1,2\ldots,T)$, there are $n_i$ observations. Denote $\mathbf{X}_i=[(\mathbf{x}_i^1)^\top,\ldots, (\mathbf{x}_i^{n_i})^\top]^\top\in\mathcal{R}^{n_i\times D}$ as the input matrix with $\mathbf{x}_i^j\in \mathcal{R}^{1\times D}$ and $\mathbf{y}_i=[y_i^1,\ldots,y_i^{n_i}]^\top\in\mathcal{R}^ {n_i\times 1}$ as the output vector, where $y_i^j \in \mathcal{R}$ for regression problems and $y_i^j \in \{-1,1\}$ for binary classification problems. For each task, consider the linear relationship between the input matrix and output vector:
$$\mathbf{y}_i = f(\mathbf{X}_i\mathbf{w}_i),\ \ i=1,2,\ldots,T, $$
where $f$ is an identify function for regression problems and a logit function for classification problems, and $\mathbf{w}_i\in \mathcal{R}^{D\times 1}$ is the coefficient vector for the $i$th task. Denote $\mathbf{W}=[\mathbf{w}_1, \ldots, \mathbf{w}_T]\in \mathcal{R}^{D\times T}$ as the coefficient matrix to be estimated.
We consider a setting in which $T$ tasks form $K$($K\ll \min\{D,T\}$) clusters, and each cluster $k$ has the unique coefficient vector $\mathbf{u}_k\in \mathcal{R}^{D\times 1}$. Different from many task clustering methods that partition tasks into disjoint clusters, we allow for an overlapping cluster structure in the sense that it allows a task to be a member of multiple clusters. We call the tasks that belong to a single cluster \emph{pure tasks} and the tasks that belong to two or more clusters \emph{mixed tasks}. We assume that the coefficient vector of each task $\mathbf{w}_i$ can be represented by the linear combination of the coefficient vector of the cluster to which this task belongs; that is, $\mathbf{w}_i=\sum_{k=1}^K v_{ki}\mathbf{u}_k$, where $v_{ki}$ is the membership weight that represents the proportions of the $i$th task belonging to cluster $k$ with $0\leq v_{ki}\leq 1$ and $\sum_{k=1}^K v_{ki}=1$. To obtain a more intuitive, and more importantly, identifiable, cluster structure, we assume that each cluster has some pure tasks. Obviously, a pure task in cluster $k$ has $v_{ki}=1$ and zeros elsewhere. Denote a full rank matrix $\mathbf{U}=[\mathbf{u}_1,\ldots,\mathbf{u}_K]\in\mathcal{R}^{D\times K}$ as the cluster coefficients and $\mathbf{V}=[\mathbf{v}_1,\ldots,\mathbf{v}_T]\in\mathcal{R}^{K\times T}$ as the membership matrix with $i$th column $\mathbf{v}_i=[v_{1i},\ldots,v_{Ki}]^\top\in\mathcal{R}^{K\times 1}$ containing the membership weight of task $i$. The above assumption enables us to write the original coefficient matrix as $\mathbf{W}=\mathbf{U}\mathbf{V}$. Formally, we formulate our approach as a constrained optimization problem:
\begin{equation}
\begin{array}{c}
\displaystyle \min _{\mathbf{U}, \mathbf{V}} \sum_{i=1}^{T} \displaystyle\frac{1}{n_i} L\left(\mathbf{y}_i, \mathbf{X}_i \mathbf{U} \mathbf{v}_{i}\right) \\
\text { s.t } \prod_{i=1}^T(v_{ki}-1)=0, \text{for}\ k=1,\ldots, K, \\
\mathbf{V}\geq 0, \mathbf{V}^\top\mathbb{I}_K=\mathbb{I}_T, \\
\parallel \mathbf{U}\parallel_1 \leq \alpha.
\label{main}
\end{array}
\end{equation}
where $L(\cdot,\cdot)$ is the empirical loss function, which is a squared loss for a regression problem and a logistic loss for a binary classification problem;
the first constraint ensures the existence of pure tasks in each cluster $k$; $\mathbf{V} \geq 0$ means that each element in matrix $\mathbf{V}$ is nonnegative; $\mathbb{I}_m$ represents a $m\times 1$ vector with all elements being 1; and $\parallel \mathbf{U}\parallel_1=\sum_{k=1}^K \parallel \mathbf{u}_k\parallel_1$ is the $l_1$ norm, which encourages the sparsity in the cluster coefficients, and $\alpha$ is the constraint parameter.
\section{Optimization and Algorithm}
Traditional constrained optimization algorithms, such as the interior point method and alternating direction method of multipliers (ADMM) method, are time consuming, and will inevitably involve tedious tuning parameters. Recently, [\cite{Zhu2019Semisoft}] proposed SOUP, a novel semisoft clustering algorithm, which can simultaneously identify the pure and mixed samples. Extensive simulation and real-data analysis demonstrate its advantages over direct competitors. Motivated by the idea of SOUP, we develop a new optimization algorithm to solve the problem in Eq. (\ref{main}).
As the standard alternating optimization algorithm, the new algorithm updates the membership matrix $\mathbf{V}$ and cluster coefficient matrix $\mathbf{U}$ alternately. The biggest difference is that the coefficient matrix $\mathbf{W}$ is also updated after updating $\mathbf{V}$ and $\mathbf{U}$.
The key ingredient of the algorithm is to adopt SOUP to extract the overlapping cluster structure from the coefficient matrix $\mathbf{W}$ by identifying the set of pure tasks and then estimating the membership matrix $\mathbf{V}$. Hence, $\mathbf{W}$ is required.
In addition, to increase the numerical stability and accelerate convergence, we modify each column of $\mathbf{W}$ separately before inputting it into SOUP (see more details in the follows). In sum, the new algorithm involves a three-step process: updating $\mathbf{V}$, $\mathbf{U}$, and $\mathbf{W}$.
\subsection{Updating $\mathbf{V}$}
We directly apply the SOUP algorithm to the coefficient matrix $\mathbf{W}$ to reveal the cluster structure among tasks. The SOUP algorithm involves two steps: identifying the set of pure tasks and estimating the membership matrix $\mathbf{V}$. In the following, we introduce the main ideas of the two steps and provide more details in the Appendix.
\noindent\bf{Identify the set of pure tasks}\rm. Pure tasks provide valuable information from which to recover their memberships, further guiding the estimation of the membership weights for the mixed tasks. Define a task similarity matrix: $\mathbf{S}=\mathbf{W}^\top \mathbf{W}\in\mathcal{R}^{T\times T}$. To find the set of pure tasks, SOUP exploits the special block structure formed by the pure tasks in the similarity matrix $\mathbf{S}$ to calculate a purity score for each task. After sorting the purity scores in descending order, the top $\theta$ percent of tasks are declared as pure tasks, denoted as $\mathcal{P}$, and then partitioned into $K$ clusters by $K$-means algorithm.
\noindent\bf{Estimate the membership matrix $\mathbf{V}$}\rm. It is noticed that there is a matrix $\mathbf{A}\in\mathcal{R}^{K\times K}$, such that $\mathbf{V}=\mathbf{A}\mathbf{\Theta}$, where $\Theta\in\mathcal{R}^{K\times T}$ is the matrix consisting of the top $K$ eigenvectors of matrix $\mathbf{S}$. Because we have identified the set of pure tasks $\mathcal{P}$ and their memberships $\mathbf{V}_{\mathcal{P}}$, the desired matrix $\mathbf{A}$ can be automatically determined from $\mathbf{V}_{\mathcal{P}}=\mathbf{A}\mathbf{\Theta}_{\mathcal{P}}$, where $\mathbf{\Theta}_{\mathcal{P}}$ refers to the sub-matrix of matrix $\mathbf{\Theta}$ formed by the columns in set $\mathcal{P}$. As a result, the full membership matrix can be recovered: $\mathbf{V}=\mathbf{A}\mathbf{\Theta}$.
\label{section:update_v}
\subsection{Updating $\mathbf{U}$}
For a fixed membership matrix $\mathbf{V}$, the optimization problem in Eq. (\ref{main}) with respect to the cluster coefficient matrix $\mathbf{U}$, becomes as follows:
\begin{eqnarray*}
&\displaystyle\min _{\mathbf{U}}\displaystyle \sum_{i=1}^{T} \displaystyle\frac{1}{n_i} L\left(\mathbf{y}_i, \mathbf{X}_i \mathbf{U} \mathbf{v}_{i}\right)
\\&\text { s.t } \parallel \mathbf{U}\parallel_1 \leq \alpha.
\end{eqnarray*}
We transform the above constraint problem to the following regularized objective function
\begin{equation}
\label{U_update}
\sum_{i=1}^{T} \frac{1}{n_{i}} L\left(\mathbf{y}_i, \mathbf{X}_i \mathbf{U} \mathbf{v}_{i}\right)+\gamma\parallel \mathbf{U}\parallel_{1},
\end{equation}
where $\gamma$ is the regularization parameter. We optimize the objective function with respect to one column vector $\mathbf{u}_k$ at a time and iteratively cycle through all the columns until the Euclidian distances between $\mathbf{u}_k$'s in two adjacent steps converge. Specifically, for $k\in\{1,\ldots,K\}$, we minimize $M(\mathbf{u}_k)$ with respect to $\mathbf{u}_k$, where
\begin{equation}
\label{U_reg}
M(\mathbf{u}_k)=\sum_{i=1}^{T} \frac{1}{n_{i}} \parallel\mathbf{y}_i-\mathbf{X}_i\sum_{l\neq k}v_{li}\mathbf{u}_l-v_{ki}\mathbf{X}_i\mathbf{u}_{k}\parallel_2^2+\gamma\parallel \mathbf{u}_k\parallel_{1},
\end{equation}
for linear regression problems with a squared loss, and
\begin{equation}
\begin{aligned}
&M(\mathbf{u}_k)= \sum_{i=1}^T \frac{1}{n_i} \sum_{j=1}^{n_i}\Bigg\{\log\Bigg[\exp\left(y_i^j(\mathbf{x}_i^j)^\top \sum_{l \neq k}v_{li}\mathbf{u}_l\right)\\&+\exp\left(-y_i^j v_{ki} (\mathbf{x}_i^j)^\top \mathbf{u}_k\right)\Bigg]+ \log\left[\exp\left(-y_i^j(\mathbf{x}_i^j)^\top\sum_{l \neq k}v_{li}\mathbf{u}_l\right)\right]\Bigg\}\\&+ \gamma\parallel\mathbf{u}_k\parallel_1 ,
\label{U_logit}
\end{aligned}
\end{equation}
for binary classification problems with a logistic loss.
The above problems are solved by using the coordinate descent [\cite{glmnet,logist}], a well-developed method for tackling a regularized regression model.
\label{section:update_u}
\subsection{Updating $\mathbf{W}$}
After updating $\mathbf{V}$ and $\mathbf{U}$, we obtain a new coefficient matrix $\tilde{\mathbf{W}}=\mathbf{U}\mathbf{V}$. To increase the numerical stability and achieve faster convergence, we update each column of the coefficient matrix $\mathbf{W}$ separately with $\tilde{\mathbf{W}}$ as initial values. Specifically, the $i$th column vector $\mathbf{w}_i$ can be updated by solving the following optimization problem, which
optimizes the following objective function
\begin{equation}
\min_{\mathbf{w}_i}\frac{1}{n_i} L(\mathbf{y}_i,\mathbf{X}_i \mathbf{w}_i) + \lambda_i \parallel\mathbf{w}_i\parallel_1, \label{single}
\end{equation}
where $\lambda_i$ is the regularization parameter, which is fixed during iteration (see more details in the following). We again leverage the coordinate descent algorithm to solve the problem efficiently. Note that, in practice, we apply early stopping to the coordinate descent to update each $\mathbf{w}_i$ with a given number $(2\sim 5)$ of iterations until completion.
\subsection{Algorithm}
\label{alg}
Algorithm 1 summarizes the whole procedure to solve the optimization problem in Eq. (\ref{main}). To start the algorithm, it is important to find a reasonable initial value of $\mathbf{W}$. For this purpose, in each task, we learn a regularized regression or logistic regression coefficient:
\begin{equation}
\label{initial}
\mathbf{w}_i^0=\min_{\mathbf{w}_i}\frac{1}{n_i} L(\mathbf{y}_i,\mathbf{X}_i \mathbf{w}_i) + \lambda_i \parallel \mathbf{w}_i\parallel_1,
\end{equation}
which can be solved with the coordinate descent method. The initial value of $\mathbf{W}$ is given by $\mathbf{W}^0=[\mathbf{w}_1^0,\ldots, \mathbf{w}_T^0]$.
\noindent\bf{Tuning parameters}\rm. SOUP has two tuning parameters: $\epsilon$, the fraction of most neighbors to be examined for each task; and $\theta$, the fraction of tasks that are declared as pure tasks. In practice, SOUP is robust with respect to these two parameters. Following the setup in [\cite{Zhu2019Semisoft}], we set $\theta=0.5$ and $\epsilon=0.1$ throughout this study. As for the tuning parameters $\lambda_i$ ($i=1,\ldots, T$) in Eqs. (\ref{single}-\ref{initial}) and $\gamma$ in Eq. (\ref{U_update}), cross-validation over a grid search is the commonly adopted method to select the optimal combination of parameters, but this becomes increasingly prohibitive with increases in $T$. Therefore, instead of first performing regularized regression or logistic regression for the given parameters and then searching for the optimal combination of parameters, we propose conducting parameter tuning with cross-validation inside the algorithm. Specifically, we perform the cross-validation within each task at the initialization step. Hence, at the initialization step, we not only provide an initial estimator $\mathbf{W}^0$ but also find the best tuning parameter $\lambda_i$ for each task. The selected $\lambda_i$ are also used at the step of updating $\mathbf{W}$. Then, we set $\gamma$ as the average of $\lambda_i$'s: $\gamma=\frac{1}{T}\sum_{i=1}^T\lambda_{i}$, where $\lambda_i$ are the parameters determined at the initialization step. As a result, the tuning parameters have been selected inside the algorithm. Since we no longer need to run the algorithm multiple times over a grid space of penalty parameters, we can largely reduce the computational time. The effectiveness and efficiency of the proposed approach to selecting parameters have both been validated in both synthetic and real-world datasets.
\begin{table}
\begin{center}
\scalebox{1}{
\begin{tabular}{l}
\toprule[2pt]
\textbf{Algorithm 1} STCMTL \\
\midrule[1pt]
\textbf{Input:} Training datasets $\{\mathbf{X}_i,\mathbf{y}_i\}_{i=1}^T$ and number of clusters $K$ \\
\textbf{Output:} $\mathbf{U}$ and $\mathbf{V}$ \\
\hline
1: \textbf{Initialization}: $\mathbf{W}^0$; \\
2: \textbf{Repeat} \\
3: \quad Update the membership matrix $\mathbf{V}$ by using SOUP;\\
4: \quad Update the cluster coefficient matrix $\mathbf{U}$ by minimizing
Eq. (\ref{U_update});\\
5: \quad Update the coefficient matrix $\mathbf{W}$ by solving Eq. (\ref{single});\\
6: \textbf{Until} the objective function of Eq. (\ref{main}) converges.\\
\bottomrule[1pt]
\end{tabular}
}
\end{center}
\end{table}
\section{Experiments}
\label{exp}
This section aims to assess the performance of the proposed STCMTL approach on both synthetic and real-world datasets. We compare STCMTL with the following baseline methods:
\textbf{LASSO} [\cite{Lasso}]: The single-task learning method learns a sparse prediction model by applying LASSO for each task separately.
\textbf{CMTL} [\cite{cluster2}]: This MTL method learns a disjoint cluster structure among the tasks and does not conduct feature selection.
\textbf{Trace} [\cite{trace1}]: This MTL method learns a low-rank structure among the tasks by penalizing both the Frobenius norm and trace norm of the coefficient matrix.
\textbf{FLARCC} [\cite{Fused}]: This MTL method achieves feature selection and coefficient clustering across tasks by using LASSO and fused LASSO penalties, respectively.
\textbf{VSTG-MTL} [\cite{VSTG}]: This MTL method is the first method that simultaneously performs feature selection and learns an overlapping cluster structure among tasks using a low-rank approach.
These methods differ in their ability to perform feature selection, task clustering, and prediction, as shown in Table \ref{methods}. LASSO is implemented using the R package "glmnet", and CMTL and Trace using the R package "RMTL". The implementation of VSTG-MTL was released at https://github.com/
JunYongJeong/VSTG-MTL. STCMTL is implemented in a R package and is available at https://github.com/ RUCyuzhao/STCMTL. Suggested by [\cite{VSTG}], for VSTG-MTL, the penalty parameter $\mu$ of $k$-support norm is set equal to the penalty parameter $\gamma_1$ of $l_1$ norm, which reduces the computational burden. The hyper-parameters of all methods are selected via five-fold cross validation over a range of $\{2^{-15},\cdots,2^{3}\}$. The number of clusters for STCMTL, CMTL, and VSTG-MTLare selected from the search grid $\{2,3,...,9\}$.
\begin{table}[]
\centering
\caption{STCMTL and baseline methods}
\label{methods}
\scalebox{0.85}{
\begin{tabular}{lccc}
\toprule[2pt]
& Feature selection & Task clustering & Prediction \\
\hline
STCMTL & $\surd$ & $\surd$ &$\surd$ \\
LASSO & $\surd$ & &$\surd$\\
CMTL & & $\surd$ &$\surd$ \\
Trace & & & $\surd$ \\
FLARCC &$\surd$ & $\surd$ & $\surd$ \\
VSTG -MTL& $\surd$ & $\surd$ & $\surd$ \\
\hline
\end{tabular}}
\end{table}
We evaluate the prediction performance by using the root mean squared error (\textbf{RMSE}) for the regression problem and the error rate (\textbf{ER}) for the classification problem. For the synthetic dataset, we also evaluate the estimation and feature selection performance. Specifically, the estimation is quantified by using the root mean estimation error (\textbf{REE}), which is defined as $||\mathbf{W}-\mathbf{\hat{W}}||_F/\sqrt{T}$, whereas feature selection is quantified by using Matthew’s Correlation Coefficient (
\textbf{MCC}), which is defined as:
$$ \mathrm{MCC}=\frac{\mathrm{TP} \times \mathrm{TN}-\mathrm{FP} \times \mathrm{FN}}{\sqrt{(\mathrm{TP}+\mathrm{FN})(\mathrm{TP}+\mathrm{FP})(\mathrm{TN}+\mathrm{FP})(\mathrm{TN}+\mathrm{FN})}}.$$
\subsection{Synthetic Datasets}
We generate 60 tasks ($T=60$). For the $i$th task, 100 training observations ($n_i=100$) and 100 testing observations are generated from $\mathbf{X}_i \sim \mathcal{N}(0,\mathbf{I}_d)$ and $\mathbf{y}_i = \mathbf{X}_i \mathbf{w}_i+\mathcal{N}(0,0.5\mathbf{I}_{n_i})$. To simulate the high-dimensional scenario ($D>n_i$), which is more challenging than the low-dimensional one, we set $D=200$ and $600$. The 60 tasks are divided into five overlapping clusters ($K=5$), that is, the true coefficient matrix $\mathbf{W}=\mathbf{U}\mathbf{V}$, where $\mathbf{U} \in \mathcal{R}^{D \times K}$ and $\mathbf{V} \in \mathcal{R}^{K \times T}$. For each $\mathbf{W}$ we repeat the data generation process for 10 times and the average performances on the test sets are reported
In the $k$th column of the cluster coefficient matrix $\mathbf{U}$, only the $[5(k-1)+1]$th to the $[5(k+1)]$th components are non-zero, which are generated from two uniform distributions, $\mathcal{U}[-0.5,-0.1]$ and $\mathcal{U}[0.1,0.5]$, randomly and independently; the other components are zeros. The 60 tasks consist of 50 pure tasks, equally assigned to $K$ clusters, and 10 mixed tasks. Without a loss of generality, we set the first 50 tasks as pure tasks and the last 10 as mixed tasks. As a result, for $i=1,\ldots,50$, the membership vectors $\mathbf{v}_i$ only have one component equal to 1, while the others are all equal to zero. For the last 10 mixed tasks, we consider two types of mixing patterns: (a) sparse, where the membership vectors $\mathbf{v}_i$ $(i=51,\ldots,60)$ have positive values for only two components, which are taken randomly from $K$ components; and (b) dense, where the membership vectors $\mathbf{v}_i$ $(i=51,\ldots,60)$ have positive values on all $K$ components. All membership vectors are normalized such that they sum to 1.
\begin{figure}[htbp]
\centering
\subfigure[Sparse]{\includegraphics[width=1.5in]{fig/sparse_cluster.png}}
\subfigure[Dense]{\includegraphics[width=1.5in]{fig/dense_cluster.png}}
\caption{ Results for the synthetic datasets: logarithm of RMSE as a function of the number of clusters $K$.}
\label{clusternumber}
\end{figure}
\begin{table*}[]
\caption{Results for the synthetic datasets: RMSE, REE, and MCC based on 10 repetitions. Each cell shows the mean $\pm$ s.d. }
\label{synthetic}
\scalebox{0.75}{
\begin{tabular}{lllllllll}
\toprule[2pt]
&& & LASSO & CMTL & Trace & FLARCC & VSTG-MTL & STCMTL \\
\hline
\multirow{6}{*}{$D$=200} & \multirow{3}{*}{Sparse} & RMSE & 0.659$\pm$0.015 & 0.651$\pm$0.007 & 0.911$\pm$0.001 & 0.591$\pm$0.011 & 0.543$\pm$0.005 & \bf{0.510$\pm$0.005} \\
& & REE & 0.030$\pm$0.001 & 0.029$\pm$0.006 & 0.054$\pm$0.001 & 0.019$\pm$0.001 & {0.011$\pm$0.001} & \bf{0.007$\pm$0.001} \\
& & MCC & 0.481$\pm$0.021 & 0.109$\pm$0.002 & 0.071$\pm$0.003 & 0.583$\pm$0.023 & 0.705$\pm$0.044 &\bf{0.779$\pm$0.018} \\
& \multirow{3}{*}{Dense} & RMSE & 0.665$\pm$0.016 & 0.650$\pm$0.008 & 0.897$\pm$0.010 & 0.590$\pm$0.011 & \bf{0.515$\pm$0.007} & \bf{0.515$\pm$0.008} \\
& & REE & 0.031$\pm$0.001 & 0.029$\pm$0.006 & 0.053$\pm$0.004 & 0.019$\pm$0.001 & \bf{0.009$\pm$0.001} & \bf{0.009$\pm$0.001} \\
& & MCC & 0.470$\pm$0.018 & 0.111$\pm$0.003 & 0.071$\pm$0.002 & 0.613$\pm$0.080 & 0.722$\pm$0.025 & \bf{0.783$\pm$0.024} \\
\hline
\multirow{6}{*}{$D$=600} & \multirow{3}{*}{Sparse} & RMSE & 0.743$\pm$0.015 & 0.829$\pm$0.011 & 1.038$\pm$0.013 & 0.635$\pm$0.019 & 0.525$\pm$0.010 & \bf{0.516$\pm$0.005} \\
& & REE & 0.022$\pm$0.000 & 0.027$\pm$0.000 & 0.036$\pm$0.000 & 0.016$\pm$0.000 & \bf{0.006$\pm$0.001} & 0.010$\pm$0.002 \\
& & MCC & 0.400$\pm$0.010 & 0.083$\pm$0.002 & 0.070$\pm$0.004 & 0.660$\pm$0.011 & 0.477$\pm$0.070 & \bf{0.715$\pm$0.157} \\
& \multirow{3}{*}{Dense} & RMSE & 0.734$\pm$0.015 & 0.824$\pm$0.011 & 1.017$\pm$0.015 & 0.624$\pm$0.036 & \bf{0.525$\pm$0.010} & {0.526$\pm$0.006} \\
& & REE & 0.022$\pm$0.000 & 0.026$\pm$0.000 & 0.036$\pm$0.000 & 0.018$\pm$0.000 & {0.010$\pm$0.001} & \bf{0.005$\pm$0.001} \\
& & MCC & 0.386$\pm$0.013 & 0.088$\pm$0.002 & 0.073$\pm$0.006 & 0.643$\pm$0.059 & 0.542$\pm$0.084 & \bf{0.717$\pm$0.159}\\
\hline
\end{tabular}}
\end{table*}
With the proposed STCMTL approach, we first examine the effect of the number of clusters $K$ on RMSE. Fig. \ref{clusternumber} presents the logarithm of RMSE as a function of $K$ for a random replicate, where other hyper-parameters are selected by cross-validation inside the algorithm. RMSE reaches the minimum at the true number of clusters, which is five for the synthetic datasets. We also examine a few other replicates and observe similar patterns.
\begin{figure}[]
\centering
\subfigure[True]{\includegraphics[width=0.3 \hsize]{fig/true_600_2.png}}
\subfigure[STCMTL]{\includegraphics[width=0.3 \hsize]{fig/me_600_2.png}}
\subfigure[VSTG-MTL]{\includegraphics[width=0.3 \hsize]{fig/vstg_600_2.png}}\\
\subfigure[True]{\includegraphics[width=0.3 \hsize]{fig/true_600_5.png}}
\subfigure[STCMTL]{\includegraphics[width=0.3 \hsize]{fig/me_600_5.png}}
\subfigure[VSTG-MTL]{\includegraphics[width=0.3 \hsize]{fig/vstg_600_5.png}}
\caption{Results for the synthetic datasets: true and estimated coefficient matrices by STCMTL and VSTG-MTL. The dark- and white-colored entries indicate the nonzero and zero values, respectively.}
\label{variable_selection}
\end{figure}
We then compute the summary statistics based on 10 repetitions. Table \ref{synthetic} presents the simulation results for the synthetic datasets. The values after $\pm$ are the standard deviations of the corresponding metrics values. In general, STCMTL outperforms the five baseline methods in terms of the three evaluation metrics in the majority of scenarios. STCMTL and VSTG-MTL perform significantly better than other methods. This is expected, as LASSO does not consider the task heterogeneity, CMTL and Trace do not conduct feature selection, and FLARCC clusters tasks based on each coefficient separately. For prediction, STCMTL always have the favorable performance, especially in Sparse condition. In terms of estimation, STCMTL has the best or nearly the best performance. Regarding the accuracy of feature selection, STCMTL performs significantly better than the baseline methods. VSTG-MTL provide a passable accuracy when $D=200$ but it clearly suffers when $D$ becomes large. The selection of correct features is crucial in some areas, such as biomedicine, which values the interpretability of results. VSTG-MTL, while it provides comparable prediction and estimation results, performs poorly in feature selection. Fig. \ref{variable_selection} shows the true coefficient matrix and estimated coefficient matrix by using STCMTL and VSTG-MTL with $D=600$, where the dark- and white-colored entries indicate non-zero and zero values, respectively \footnote{For demonstration purpose, we reorder the features and put the features selected by STCMTL or VSTG-MTL on the top of list.}. It can be seen that STCMTL can almost identify the true cluster structure among the tasks and remove most of the irrelevant features. However, VSTG-MTL suffers from selecting more false features, which inevitably affects the identification accuracy of the cluster structure.
As VSTG-MTL is the method that is most relevant to the proposed STCMTL approach, we also compare the computational efficiencies of the two methods under all simulation settings. Table \ref{synthetic_time} shows the time spent in updating $\mathbf{U}$ and $\mathbf{V}$ with the fixed hyper-parameters, and completing the entire training process (including performing five-fold cross-validation), respectively, and their standard deviations for two approaches over 10 repetitions. Clearly, the computational efficiency of STCMTL is significantly higher than that of VSTG-MTL. The reasons for this are summarized as follows:
\begin{itemize}
\item STCMTL only contains a $\ell_1$ norm penalty term on $\mathbf{U}$, and thus, uses the coordinate descent algorithm, a highly efficient algorithm, to update $\mathbf{U}$. Meanwhile VSTG-MTL adopts the ADMM algorithm, a more complex algorithm, to address two penalty terms on $\mathbf{U}$. In particular, the time that VSTG-MTL spends on the updating process $\mathbf{U}$ grows significantly when the number of features $D$ increases from $200$ to $600$.
\item As described in Section \ref{alg}, STCMTL conducts the tuning of penalty parameters with cross-validation only at the initialization step, avoiding running the entire algorithm multiple times on the grid space of the penalty parameters. Hence, considerable time is saved.
\end{itemize}
\begin{table*}[]
\centering
\caption{Results for the synthetic datasets: time consumption (in seconds) of STCMTL and VSTG-MTL based on 10 repetitions. Each cell shows the mean $\pm$ s.d.}
\label{synthetic_time}
\scalebox{0.8}{
\begin{tabular}{lllllll}
\toprule[2pt]
& & & Updating $\bf{U}$ & Updating $\bf{V}$ & Total \\
\hline
\multirow{4}{*}{$D$=200} & \multirow{2}{*}{Sparse} & VSTG-MTL &13.0$\pm$2.3 & \bf{0.8$\pm$0.1}
&4448.7 $\pm$ 308.2 \\
& & STCMTL
& \bf{5.1$\pm$0.8} &0.9$\pm$0.2
& \bf{56.9$\pm$7.2}
\\
& \multirow{2}{*}{Dense} & VSTG-MTL
&12.1$\pm$1.9 & \bf{0.8$\pm$0.1 }
& 4532.9$\pm$191.6 \\
& & STCMTL
&\bf{5.2$\pm$ 0.6} &0.9 $\pm$ 0.1
&\bf{44.1}$\pm$\bf{3.6}
\\
\hline
\multirow{4}{*}{$D$=600} & \multirow{2}{*}{Sparse} & VSTG-MTL
&141.2 $\pm$ 16.8 &\bf{1.1 $\pm$ 0.2}
&39020.2 $\pm$ 1522.6
\\
& & STCMTL
&\bf{48.3$\pm$3.8} & 2.1 $\pm$0.1
&\bf{190.2 $\pm$ 20.8}
\\
& \multirow{2}{*}{Dense}& VSTG-MTL
&128.6 $\pm$ 11.5 &\bf{1.0 $\pm$ 0.1 }
&39169.5 $\pm$ 1921.5 \\
& & STCMTL
&\bf{45.3$\pm$ 3.9} &2.9 $\pm$0.2
&\bf{191.4$\pm$20.2 }
\\
\hline
\end{tabular}}
\end{table*}
In summary, from the synthetic datasets, we can see that STCMTL achieves the most desirable performance in terms of prediction, estimation, and feature selection compared to the five baseline methods. While VSTG-MTL is competitive in some scenarios, it suffers severely from poor feature selection and a prohibitive computational cost compared with STCMTL.
\subsection{Real-World Datasets}
We evaluate the performance of STCMTL on the following four real-world benchmark datasets. \textbf{Isolet data}\footnote{www.zjucadcg.cn/dengcai/Data/data.html} and \textbf{School data}\footnote{http://ttic.uchicago.edu/~argyriou/code/index.html} are two regression tasks datasets, which are widely used in previous works [\cite{isolet2,VSTG,robust}]. Training and test sets are obtained by splitting the dataset $75\%$-$25\%$. \textbf{MNIST data}\footnote{http://yann.lecun.com/exdb/mnist/} and \textbf{USPS data}\footnote{http://www.cad.zju.edu.cn/home/dengcai/Data/MLData.html} are both handwritten 10 digits datasets. We treat these 10-class classification as a multi-task learning problem where each task is the classification of one digit from all the other digits, thus yielding 10 tasks. Following the procedure in [\cite{overlap2,cluster2,VSTG}], each image is preprocessed with PCA, and the dimensionality is reduced to 64 and 87, respectively. For each task, the training (test) set is generated by randomly selecting 100 train (test) observations of the corresponding digit and 100 train (test) observations of other digits.
We apply STCMTL to the four real datasets. Fig. \ref{converge} shows the objective function value by iteration, and we can see that the objective function converges to the optimal value within 20 iterations in most repetitions.
\begin{figure*}[htbp]
\centering
\subfigure[Isolet]{\includegraphics[width=0.24 \hsize]{fig/isolet_converge.png}}
\subfigure[School]{\includegraphics[width=0.24 \hsize]{fig/school_converge.png}}
\subfigure[MNIST]{\includegraphics[width=0.24 \hsize]{fig/mnist_converge.png}}
\subfigure[USPS]{\includegraphics[width=0.24 \hsize]{fig/usps_converge.png}}
\caption{Objective function value versus iteration on four real-world datasets.}
\label{converge}
\end{figure*}
Table \ref{real} summarizes the prediction performance on the test sets of the five methods in the four real-world datasets over 10 repetitions. In the linear regression problem, STCMTL and VSTG-MTL stand out. The two methods' results are comparable, with no statistically significant differences. However, in the classification problem, the STCMTL outperforms all the other baseline methods. In addition, once again, the computational cost of VSTG-MTL is prohibitive compared to STCMTL (Table \ref{real_time}).
\begin{table*}[]
\caption{Results for the real-world datasets: RMSE and ER based on 10 repetitions. Each cell shows the mean $\pm$ s.d. }
\label{real}
\scalebox{0.8}{
\begin{tabular}{lllllllll}
\toprule[2pt]
Dataset& & LASSO & CMTL & Trace & FLARCC & VSTG-MTL & STCMTL \\
\hline
Isolet & RMSE & 0.241$\pm$0.005 & 0.273$\pm$0.003 &0.237$\pm$0.003 & 0.262$\pm$0.006 & {0.193$\pm$0.018} & \bf{0.191$\pm$0.003}\\
School & & 10.638$\pm$0.031 & 10.564$\pm$0.056 & 12.210$\pm$0.053 & 10.771$\pm$0.059 & \bf{10.020$\pm$0.189} &{10.075$\pm$0.107} \\
\hline
MNIST & ER & 0.202$\pm$0.013 & 0.187$\pm$0.007 & 0.165$\pm$0.007 & 0.190$\pm$0.009 & 0.108$\pm$0.012 & \bf{0.088$\pm$0.008} \\
USPS& & 0.196$\pm$0.011 & 0.199$\pm$0.010 & 0.170$\pm$0.009 & 0.184$\pm$0.012 & 0.101$\pm$0.009 & \bf{0.091$\pm$0.008} \\
\hline
\end{tabular}}
\end{table*}
\begin{table*}[]
\centering
\caption{Results for the real-world datasets: time consumption (in seconds) of STCMTL and VSTG-MTL based on 10 repetitions. Each cell shows the mean $\pm$ s.d. }
\label{real_time}
\scalebox{0.8}{
\begin{tabular}{lll|ll|ll|ll}
\toprule[2pt]
& \multicolumn{2}{c}{Isolet} & \multicolumn{2}{c}{School} & \multicolumn{2}{c}{MNIST} & \multicolumn{2}{c}{USPS} \\
& VSTG-MTL & STCMTL & VSTG-MTL & STCMTL & VSTG-MTL & STCMTL & VSTG-MTL & STCMTL \\
\hline
Total & 50029.8$\pm$3657.7 &\bf{525.3$\pm$35.9} & 934.1$\pm$95.6 & \bf{20.8$\pm$2.6} & 2514.4$\pm$99.4 & \bf{209.3$\pm$30.2} & 3077.8$\pm$154.3 & \bf{121.1$\pm$11.1} \\
\bottomrule
\end{tabular}}
\end{table*}
\section{Extension to Robust Task Clustering}
The proposed approach decouples task clustering and feature selection into estimating three tractable sub-problems: the membership matrix $\mathbf{V}$, cluster coefficients matrix $\mathbf{U}$, and coefficient matrix $\mathbf{W}$. The proposed approach employs the SOUP algorithm to identify the membership matrix but it is not the only available option, as numerous other matrix-factorization-based clustering methods have also been proposed. Hence, in practice, we could replace or combine SOUP with other matrix-factorization-based clustering methods to tackle more complex scenarios in task clustering. In this section, we consider task clustering with several outlier tasks and modify the proposed approach to a robust task clustering one.
We assume that there are some outlier tasks that cannot be represented by a linear combination of cluster coefficient vectors $\mathbf{v}_k$'s. To improve the robustness against these outlier tasks, in the step of updating $\mathbf{V}$, we first apply a $l_{12}$-norm-based robust nonnegative matrix factorization (NMF) algorithm to identify the outlier tasks. Then, we estimate $\mathbf{V}$ by using the SOUP algorithm. Specifically, we apply the robust NMF algorithm \cite{RobustNmf} on $\mathbf{W}$, yielding two rank-$K$ matrices, $\mathbf{C}$, and $\mathbf{\Theta}$, such that $\mathbf{W}\approx \mathbf{C}\mathbf{\Theta}$. Then, we define a distance $D_i=\|\mathbf{W}_i-\mathbf{C}\mathbf{\Theta}_i\|_2$ for each task, which measures the discrepancy between the true and estimated coefficients. If $\mathbf{W}$ is precise enough, the distances of the outlier tasks should be much larger than those of the normal tasks; thus, the outlier tasks can be identified. For simplicity, we employ the definition of outliers in bar plots. In words, a task is declared an outlier if it is above 4.5 times the interquartile range (IQR) over the upper quartile of the distance. Practically, we can use other advanced anomaly detection methods. Once the outlier tasks are identified, they are removed from the set of tasks. Then, we apply the SOUP algorithm on the remaining normal tasks to recover their membership weights. The overall procedure is summarized in Algorithm 2 \ref{Ar}, where $\mathbf{B}_\mathcal{S}$ refers to the sub-matrix of matrix $\mathbf{B}$ formed by columns in set $\mathcal{S}$.
We use synthetic datasets to validate the effectiveness of the modified approach in terms of task clustering, feature selection, and robustness against outlier tasks. The data generation procedure is exactly the same as the sparse condition in section 4.1, except we add five outliers tasks, each of which has 10 nonzero coefficients generated from $\mathcal{U}[0.5,1]$. As a result, we have total $T=65$ tasks. We set $D = 100 \text{ and }200$.
\begin{table}
\begin{center}
\begin{tabular}{l}
\toprule[2pt]
\textbf{Algorithm 2} Robust STCMTL\\
\midrule[1pt]
\textbf{Input:} Training datasets $\{\mathbf{X}_i,\mathbf{y}_i\}_{i=1}^T$, number of clusters $K$ and index of $T$ tasks $\mathcal{T}$;\\
\textbf{Output:} matrix $\mathbf{U}$, $\mathbf{V}$ and the set of outlier tasks $\Gamma$ \\
\hline
1: \textbf{Initialization}: $\mathbf{W}^0$, $\Gamma=\emptyset$; \\
2: \textbf{Repeat} \\
3:\quad Apply the robust NMF algorithm on $\mathbf{W}_{\mathcal{T}\setminus \Gamma}$, yielding two rank-$K$
matrices $\mathbf{C}$ and $\mathbf{\Theta}$, \\ such that $\mathbf{W}_{\mathcal{T}\setminus \Gamma}\approx \mathbf{C}\mathbf{\Theta}$; \\
4:\quad For each task $i\in \mathcal{T}\setminus\Gamma$, compute its distance:
$D_i=\|\mathbf{W}_i-\mathbf{C}\mathbf{\Theta}_i\|_2$;\\
5:\quad Update $\Gamma$ by: $\Gamma\leftarrow\Gamma\cup \{i:D_i\geq \text{the upper quartile of}\ \{D_i\}+4.5\times \text{IQR}\}$; \\
6:\quad Update the cluster coefficient matrix $\mathbf{V}_{\mathcal{T}\setminus \Gamma}$ by using SOUP; \\
7:\quad Update the cluster coefficient matrix $\mathbf{U}$ by minimizing Eq. (\ref{U_update});\\
8:\quad Update the coefficient matrix $\mathbf{W}_{\mathcal{T}\setminus \Gamma}$ by solving Eq. (\ref{single}); \\
9: \textbf{Until} the objective function of Eq. (\ref{main}) with tasks in $\Gamma$ removed
converges. \\
\bottomrule[1pt]
\end{tabular}
\label{Ar}
\end{center}
\end{table}
We compare the modified approach with the two baseline methods, LASSO and VSTG-MTL. Table \ref{robust} reports the simulation results for the three methods. It can be observed that the modified approach outperforms the two baseline methods in terms of prediction, estimation, and feature selection.
\begin{table}[]
\centering
\caption{Results for the synthetic datasets with outlier tasks: RMSE, REE, and MCC based on 10 repetitions. Each cell shows the mean $\pm$ s.d.}
\scalebox{0.85}{
\begin{tabular}{lllll}
\toprule[2pt]
& & LASSO & VSTG-MTL & STCMTL (Robust) \\
\hline
& RMSE & 0.836$\pm$0.014 & 0.884$\pm$0.046 & \bf{0.577$\pm$0.029} \\
$D$=100 &REE & 0.067$\pm$0.002 & 0.073$\pm$0.003 & \bf{0.029$\pm$0.006} \\
& MCC & 0.413$\pm$0.012 & 0.647$\pm$0.064 & \bf{0.660$\pm$0.035} \\
\hline
& RMSE & 1.011$\pm$0.019 & 0.878$\pm$0.046 & \bf{0.685$\pm$0.038} \\
$D$=200 &REE & 0.125$\pm$0.001 & 0.073$\pm$0.004 & \bf{0.033$\pm$0.004} \\
& MCC & 0.331$\pm$0.078 & 0.637$\pm$0.066 & \bf{0.731$\pm$0.017}\\
\hline
\end{tabular}
}
\label{robust}
\end{table}
\section{Conclusion}
This study proposes a novel task clustering approach STCMTL, which can simultaneously learn an overlapping structure among tasks and perform feature selection.
Although it is similar in spirit to the existing task clustering methods, it is also significantly more advanced. In the classification of pure and mixed tasks, it produces an identifiable and interpretable task cluster structure and selects relevant features.
STCMTL factorizes the coefficient matrix into a product of the cluster coefficient matrix and membership matrix, and it imposes some constraints on the membership matrix values and sparsities on the cluster coefficient matrix. T4edhe resulting constrained optimization problem is challenging to solve. To circumvent this, a new alternating algorithm is developed, which repeats a three-step process: identifying the set of pure tasks and estimating the membership matrix; updating the cluster coefficient matrix; and updating coefficient matrix until convergence. The tuning of hyper-parameters with validation is conducted inside the algorithm, leading to substantial improvements in computational efficiency. The experimental results show that the proposed STCMTL approach outperforms the baseline methods using synthetic and real-world datasets. Moreover, STCMTL can be extended to other, more complex task clustering problems, such as robust task clustering.
An important limitation of this study is its lack of theoretical investigation. This will be deferred to future research. We also defer additional possible extensions of the proposed approach to future research.
\newpage
| {'timestamp': '2022-12-01T02:20:25', 'yymm': '2211', 'arxiv_id': '2211.17204', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17204'} | arxiv |
\section{Introduction}
The field of Natural Language Processing (NLP) has made significant progress since the introduction of large language models, such as BERT~\citep{devlin2018bert}, GPT-3~\citep{brown2020gpt3} and T5~\citep{raffel2020T5}.
However, most large language models require a stage of pretraining before being applied to the target NLP task, where the pretraining cost could be staggering.
Several libraries have been proposed to alleviate the above problem.
For instance, HuggingFace~\citep{wolf-etal-2020-huggingface} \footnote{Code repository: \url{https://github.com/huggingface/transformers}} provides a huge number of pretrained models, allowing users to download the model directly from the model repository.
It also encourages users to upload their own pretrained models, so that others can utilize the same model without repeating any expensive pretraining process.
Nevertheless, those features are still insufficient for researchers or engineers with privacy concerns or customization needs.
For example, in most hospitals or banks, the data has its own value.
Releasing the model trained on those data will not only compromise user privacy, but can also incur serious security issues.
Due to this very reason, those pretrained models are no longer available online, forcing one to pretrain the whole model from scratch.
However, HuggingFace provides slight acceleration for pretraining models under the limited-resource scenario.
Hence the time cost still remains a huge obstacle.
On the other hand, several other libraries provide significant speed-up for pretraining BERT~\citep{devlin2018bert}. For instance, Academic BERT~\citep{24hbert2021} summarizes a list of tricks to reduce the pretraining time cost, making it possible to surpass BERT Base on GLUE tasks~\citep{wang2018glue} at significantly less cost.
However, this toolkit restricts itself to the original BERT settings and lacks sufficient flexibility for customized models or datasets.
Furthermore, its official repository \footnote{Code repository: \url{https://github.com/IntelLabs/academic-budget-bert}} misses an easy-to-use pipeline and requires users to manually build the working environment, modify its codes and run the programs stage by stage in order to reproduce the reported results.
To resolve those pain points, we propose ExtremeBERT, a toolkit that obtains an-order-of-magnitude acceleration in BERT pretraining.
In the meantime, it supports an easy-to-use pipeline and dataset customization.
\section{Toolkit Overview}
ExtremeBERT is a toolkit designed to support fast language model pretraining under a limited-resource scenario.
It can significantly speed up the pretraining process of BERT through combining several recent accelerating techniques.
Meanwhile, ExtremeBERT supports a wide range of datasets, including customized datasets provided by users and all Huggingface pretraining datasets online \footnote{Huggingface dataset repository: \url{https://huggingface.co/datasets}}.
Those features are seamlessly incorporated in the toolkit and can be customized simply by specifying a YAML configuration file, where running the whole pipeline only requires a one-line command.
The whole toolkit is built upon the code repository of~\citet{24hbert2021}, where most of its acceleration features have been inherited.
On top of that, ExtremeBERT introduces its own acceleration techniques and further improves its already superior speed.
Several missing features and pain points in~\citet{24hbert2021} are also well handled in ExtremeBERT, leading to a much more user-friendly interface.
\subsection{Feature: Easy-to-use Pipeline}
\begin{figure}[h!]
\centering
\includegraphics[scale=0.48]{imgs/pipeline.png}
\caption{Five stages of the ExtremeBERT pipeline and the one-line command.}
\label{fig:pipeline}
\end{figure}
\begin{figure}
\iffalse
\begin{minipage}{.5\textwidth}
\begin{minted}[fontsize=\scriptsize]{yaml}
SYSTEM:
NUM_GPUS: 8
DATASET:
HUGGINGFACE_DATASETS:
- [wikipedia, 20220301.en]
- [bookcorpusopen, plain_text]
PRETRAIN:
NUM_STEPS: 57500
TOKENIZER:
NAME_OR_PATH: bert-large-uncased
\end{minted}
\end{minipage}
\begin{minipage}{.5\textwidth}
\begin{minted}[fontsize=\scriptsize]{yaml}
SYSTEM:
NUM_GPUS: 8
MAX_MEMORY_IN_GB: 16
WANDB:
API_KEY: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
DATASET:
CUSTOMIZED_DATASETS:
- /home/user/data/customized_corpus/
- /home/user/data/pile/
HUGGINGFACE_DATASETS:
- [wikipedia, 20220301.en]
- [bookcorpusopen, plain_text]
PRETRAIN:
NUM_STEPS: 57500
TOKENIZER:
NAME_OR_PATH: bert-large-uncased
\end{minted}
\end{minipage}
\fi
\centering
\includegraphics[scale=0.6]{imgs/config-example_bert.png}
\caption{\textbf{Left:} An example YAML configuration file for BERT Large \texttt{bert-large.yaml}; \textbf{Right:} An example YAML configuration file for a customized BERT model \texttt{bert-customized.yaml}.}
\label{fig:pipeline_config}
\end{figure}
Many frameworks, including Huggingface~\citep{wolf-etal-2020-huggingface} and Academic BERT~\citep{24hbert2021}, require users to manually type input commands or write codes for each stage of the pipeline.
However, this is not only painstaking, it is also inefficient.
This pain point is solved in ExtremeBERT by introducing an one-line command pipeline.
It asks users to provide a configuration file that only includes the necessary information of BERT pretraining.
In addition, ExtremeBERT solely relies on python packages, freeing users from complex environment preparation that is common in many other accelerated frameworks, e.g. the APEX C++ toolkit dependency problem in~\citet{24hbert2021}.
\subsection{Feature: Acceleration}
\begin{wrapfigure}{r}{0.3\textwidth}
\centering
\includegraphics[scale=0.22]{imgs/esd_in_practice_curve.png}
\caption{Illustration of the modified ESD scheduler.}
\label{fig:esd_in_practice_illust}
\end{wrapfigure}
ExtremeBERT inherits all acceleration techniques of Academic BERT~\citep{24hbert2021}, including the DeepSpeed Package~\citep{rasley2020deepspeed}, mixed-precision training, large batch training, insufficient large model training, STILT tricks~\citep{phang2018stilt} and so on.
On top of that, ExtremeBERT adopts a modified Elastic Step Decay (ESD) learning rate scheduler~\citep{pan2021eigencurve} to further accelerate the pretraining process.
\begin{equation}
\label{eq:esd_in_practice}
\begin{aligned}
\eta_t
=&
\begin{cases}
\eta_0,
\quad& t \in \left[0, 1 - r^{\ell}\right] \cdot T,
\\
\eta_0 \cdot \left(\frac{1}{2r}\right)^{i - \ell}
\quad& t \in \left(1-r^{i-1}, 1 - r^{i}\right] \cdot T, i \ge \ell + 1.
\end{cases}
\end{aligned}
\end{equation}
Experiments show that this technique results in $\sim 0.4$ improvements over the linear decay scheduler in the final GLUE score.
\subsection{Feature: Datasets}
ExtremeBERT supports two type of datasets: customized datasets provided by users and datasets supported by Huggingface.
For customized datasets, users only need to convert their corpus into raw text files, where in each text file, articles are assumed to be separated by blank lines. Then by grouping those text files in folders and specifying the folders' paths in the pipeline configuration file, ExtremeBERT will automatically handle the data pre-processing on given datasets, i.e. pre-masking, shuffling, sharding and tokenization.
For Huggingface datasets, as shown in Figure~\ref{fig:pipeline_config}, only require the dataset name and split name to be specified in the pipeline configuration file, e.g. \texttt{bookcorpus} and \texttt{plain\_text}, respectively. ExtremeBERT will then download the corresponding datasets from the Huggingface dataset repository and handle the pre-processing.
On top of that, ExtremeBERT supports large dataset processing on small RAM servers. In the toolkit provided by~\citet{24hbert2021}, it is observed that the pre-processing of Wikipedia and bookcorpus datasets costs more than 60GB memory, rendering it impossible for researchers to use them on small servers such as Google Colab, which typically supports $<25$ GB memory. To solve this issue, ExtremeBERT introduces a time-memory tradeoff mechanism to enable small-RAM pre-processing, which basically utilizes disk serialization to save RAM usage.
By specifying the \texttt{SYSTEM:MAX\_MEMORY\_IN\_GB} field in the pipeline configuration file, as shown in Figure~\ref{fig:pipeline_config}, ExtremeBERT will control the RAM usage for data pre-processing and make sure no out-of-memory issue occurs.
\section{Performance}
\label{sec:exp}
ExtremeBERT provides significant speedup over BERT's original toolkit~\citep{devlin2018bert}.
To quantify this acceleration, we compare the cost of reaching or surpassing the benchmark GLUE score, as shown in Table~\ref{tab:extremebert_glue_overview}. Here all empirical experiments are conducted on BERT Large models with different hyperparameters, the same as the convention in~\citet{24hbert2021}.
For more experimental details, please refer to Appendix~\ref{appendix:glue_experiments}.
\begin{table}[h!]
\scriptsize
\begin{center}
\begin{tabular}{ccccccc}
\toprule
\makecell{Benchmark}
& Toolkit
& \makecell{GPU \\ resource}
& \makecell{GLUE \\ score}
& \makecell{Pretraining \\ Time (days)}
& \makecell{Cost\\(V100 $\times$ days)}
& \textbf{Speedup}
\\
\midrule
\multirow{2}{*}{BERT Base}
& Original Paper
& TPU chips $\times 16$
& 79.6
& $4.0$
& $> 64$
& -
\\
& ExtremeBERT
& GeForce RTX 3090 $\times 8$
& 81.1
& $1.3$
& $\sim 10.4$
& $\bm{6.1 \times}$
\\
\midrule
\multirow{2}{*}{BERT Large}
& Original Paper
& TPU chips $\times 64$
& 82.1
& $4.0$
& $>256$
& -
\\
& ExtremeBERT
& GeForce RTX 3090 $\times 8$
& 82.4
& 3.4
& $\sim 27.2$
& $\bm{9.4 \times}$
\\
\bottomrule
\end{tabular}
\end{center}
\caption{GLUE: results on 9 tasks selected by~\citep{devlin2018bert}.}
\label{tab:extremebert_glue_overview}
\end{table}
Experiment results demonstrate that our toolkit offers roughly one order of magnitude speedup over the original BERT toolkit. This renders it possible for researchers and engineers to pretrain a BERT model from scratch with limited resources.
\section{Conclusion and Future Work}
In this paper, we introduce ExtremeBERT, a resource-friendly framework for BERT pretraining, which supports customized datasets and offers roughly one order of magnitude acceleration over the original BERT pretraining process. To obtain the desired customized pretrained model, users are only a configuration file and one-line command away, where the remaining part will be handled smoothly by ExtremeBERT.
In the future, ExtremeBERT will support more features, including more diverse models, multi-server dataset pre-processing, and SuperGLUE~\citep{wang2019superglue} for finetuning tasks. Our vision is to make the pretraining of language models possible for every researcher and engineer.
\newpage
| {'timestamp': '2022-12-01T02:20:24', 'yymm': '2211', 'arxiv_id': '2211.17201', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17201'} | arxiv |
\section{Conclusion}
\label{sec:conclusion}
We propose AIO-P, or All-in-One Predictors, to broaden the scope of neural performance prediction tasks.
AIO-P
uses $K$-Adapters to
infuse knowledge from different tasks and
accepts Computational Graphs (CG) as input. CG represent
the body and head of an architecture by encoding
all
atomic operations
as nodes with directed edges determined by the network forward pass. At the output, AIO-P incorporates
target scaling techniques,
including one based on FLOPs, to re-scale predictions into the appropriate task metric and ultimately obtain superior performance.
To construct a suitable training set, we devise a shared head approach with latent sampling, which can
pair with any architecture in the search space to produce a pseudo-label that is
highly correlated with the true label.
Experimental results show that AIO-P
can obtain Mean Absolute Error and Spearman's Rank Correlations below 1\% and above 0.5, respectively, when transferred to a wide range of downstream tasks.
Moreover, AIO-P can directly transfer and adequately rank different networks in several foreign model zoos not seen in training for classification and semantic segmentation.
Finally, we use AIO-P to optimize a proprietary facial recognition network to effectively preserve accuracy while reducing FLOPs by over 13.5\%.
\begin{table}[t]
\centering
\caption{Precision (Pr) and Recall (Rc) of a proprietary FR network found by pairing AIO-P with a search algorithm designed to preserve performance while reducing FLOPs.}
\scalebox{0.8}{
\begin{tabular}{l|cc|cc|cc|c} \toprule
& \textbf{Full} & \textbf{Simple} & \textbf{Lighted} & \textbf{Dark} & \textbf{FLOPs}\\ \midrule
Base Model Pr & \textbf{96.3}\% & \textbf{98.7}\% & \textbf{97.9}\% & 96.5\% & 563M \\
AIO-P Search Pr & 96.1\% & \textbf{98.7}\% & \textbf{97.9}\% & \textbf{96.7}\% & 486M\\ \midrule
Base Model Rc & \textbf{91.9}\% & \textbf{98.3}\% & \textbf{96.8}\% & 92.6\% & 563M \\
AIO-P Search Rc & 91.1\% & 98.2\% & 96.6\% & \textbf{93.2}\% & 486M\\ \bottomrule
\end{tabular}
}
\label{tab:properitary}
\end{table}
\section{Introduction}
\label{sec:intro}
Performance evaluation of neural network models is resource and time consuming. Several factors contribute to its expensiveness, such as task complexity, training dataset size, architecture topology, and training time.
It is yet a main component and the bottleneck in Neural Architecture Search (NAS)~\cite{elsken2019neural}. Early NAS approaches train sampled architectures to completion during search \cite{zoph2017NAS} while later approaches adopt weight-sharing supernet approaches \cite{pham2018ENAS, liu2018DARTS, rezaei2021generative, mills2021l2nas, mills2021exploring}, which reduce the computational burden but do not eliminate it. Advanced supernet schemes like Once-for-All (OFA)~\cite{cai2020once} and BootstrapNAS~\cite{munoz2022automated} introduce progressive shrinking to train a reusable supernet. Specifically, OFA supernets are robust enough that individual architectures can be sampled for immediate evaluation on ImageNet~\cite{russakovsky2015imagenet}.
Zero-Cost Proxies (ZCP)~\cite{abdelfattah2021zero} are a recent development aiming to correlate performance with gradient statistics and thus can generalize to any types of network.
However, the efficacy of ZCP methods depend on the architecture and task and may not be always reliable.
Other recent schemes like NAS-Bench-301~\cite{zela2022surrogate}, SemiNAS~\cite{luo2020semi}, TNASP~\cite{lu2021TNASP} and WeakNAS~\cite{wu2021stronger} develop neural predictors
that estimate architecture performance from
network topology and operation features.
However, they model customized architectures in
specific search spaces, e.g., NAS-Bench-101~\cite{ying2019nasbench101} and 201~\cite{dong2020nasbench201} for common benchmark tasks like CIFAR image classification \cite{Krizhevsky09CIFAR}, and cannot be directly transferred to other challenging tasks like pose estimation or segmentation or to architecture with new type of topologies/connections.
In this paper, we propose All-in-One Predictor (AIO-P), a multi-task neural performance predictor which achieves cross-task and cross-search-space transferability via predictor pretraining and domain-specific knowledge injection. AIO-P uses
Computational Graph (CG) to represent neural architectures, which is lower-level information extracted from TensorFlow execution
and thus can model general
types of architectures. We make the observation that many CV architectures consist of a \textit{body} (e.g., ResNet) that performs feature extraction and a \textit{head} that uses extracted features to generate task-specific outputs. Figure~\ref{fig:head_and_body} illustrates how architectures can be constructed for different tasks by combining various types of bodies and heads. Based on such network representations, we introduce an effective transfer learning scheme to first pretrain AIO-P on image classification benchmarks, then infuse domain knowledge from other tasks or architecture spaces efficiently, and finally transfer to a downstream task with minimum or no fine-tuning. Specifically, we propose the following techniques to achieve transferability to downstream tasks:
First, we introduce $K$-Adapters~\cite{wang2021kadapt}, originally used to inject domain knowledge into language models, into a GNN predictor pretrained on network benchmarks for image classification (IC) such that the predictor can infuse knowledge from, e.g., segmentation/detection tasks or other network topologies. We then transfer the learned model to perform predictions on potentially unseen downstream tasks or architectures.
Second, we propose an efficient learning scheme to train AIO-P, and especially adapters, by a pseudo-labeling scheme for task-specific network performance. In order to reduce the high cost associated with labeling each individual architecture's performance on a given task, we propose to train a weight-shared task head for all body architectures in an entire search space, e.g., all variants of MobileNetV3~\cite{howard2019searching} in OFA.
After training the shared head, it can pair with any architecture body and fine-tune for a few minutes to obtain a pseudo-label that is positively correlated with the true label seen when individually training the architecture for several hours.
Moreover, we further propose a
latent representation sampling technique
to enhance the correlations of pseudo labels to true performance labels.
Third, since performance metrics and their distributions differ by task, we use several scaling techniques such as standardization and FLOPs-based transform to rescale labels when adapting AIO-P to a downstream task.
AIO-P learns a unitless understanding of architecture performance that can then revert into a task-appropriate metric like Average Precision (AP) or mean Intersection over Union (mIoU).
Through extensive experiments, we demonstrate that AIO-P pretrained on one or two tasks in addition to classification is able to transfer to predict neural network performance for a diverse range of CV tasks including 2D Human Pose Estimation (HPE), Object Detection (OD), Instance Segmentation (IS), Semantic Segmentation (SS), and Panoptic Segmentation (PS). AIO-P consistently achieves a Mean Absolute Error (MAE) below 1\% on task-specific metrics and a Spearman's Rank Correlation Coefficient (SRCC) above 0.5, outperforming both ZCP and GNN baselines under zero-shot transfer and minimum fine-tuning settings.
In addition, AIO-P is able to correctly rank architectures in foreign model zoos whose body networks are different from those observed in training, including DeepLab~\cite{deeplabv3plus2018} and TF-Slim~\cite{TFSlim}. Finally, by pairing AIO-P with a search algorithm, we can optimize a proprietary facial recognition
model to preserve performance while reducing FLOPs by over 13.5\%.
We open-source\footnote{https://github.com/Ascend-Research/AIO-P} our data,
code, and predictor design to advance research in this field.
\section{Methodology}
\label{sec:methodology}
\begin{figure}
\centering
\includegraphics[width=3.25in]{fig/SESubgraph.pdf}
\caption{Example CG subgraph of a Squeeze-and-Excite (SE) module~\cite{hu2018squeeze} in MBv3. We store properties like kernel size and channels as node features.}
\label{fig:cg_se}
\end{figure}
We cast performance prediction as a supervised learning regression problem where each data sample belongs to a given task domain $t$.
Each task $t$ contains instances $(A_i^t, y_i^t)$ where $A_i$ is an architecture, and $y_i$ is its performance label denoted by a metric value on $t$. For example, $y_i^t$ is the \textit{accuracy} value for an Image Classification (IC) architecture, or \textit{average precision} for Object Detection (OD).
The goal is a neural predictor that can generalize across many tasks and provide accurate performance estimations. In this section, we describe how AIO-P represents architectures as Computational Graphs and uses $K$-adapters to learn task transferable knowledge. Furthermore, we describe how shared task heads and pseudo-labeling let us form a large dataset of training instances. Finally, we discuss label scaling techniques for making accurate predictions across different performance distributions.
\subsection{Network Representation}
A CV architecture usually consists of a `body' that performs feature extraction on an input and a `head' that uses extracted features to make predictions. The `body' structure comes from a given search space while the head comes from a specified task $t$.
The search spaces we consider are from OFA. These include ProxylessNAS (PN)~\cite{cai2018proxylessnas}, MobileNetV3 (MBv3)~\cite{howard2019searching} and ResNet-50 (R50)~\cite{he2016deep}. Architectures bodies from these spaces are pre-trained on ImageNet classification.
Head designs vary with task complexity. For example, a typical IC head uses global average pooling and MLP layers to predict class labels for an entire image.
By contrast, we consider tasks like HPE, OD, and segmentation, which
upsample feature maps with different resolutions to make predictions. Specifically, HPE~\cite{zheng2020deep} generates large heat maps to estimate joint locations, while Semantic Segmentation (SS)~\cite{liu2019auto} upsamples to predict class labels for every pixel in an image. OD~\cite{ren2015faster} uses a Region Proposal Network (RPN) and Region of Interest Poolers (RoI) to estimate bounding box coordinates and classes, while Instance Segmentation (IS) replaces the bounding boxes with pixel-level masks for each instance of a class. Finally, Panoptic Segmentation (PS)~\cite{kirillov2019panoptic} combines IS and SS to generate pixel masks for an image while differentiating individual instances of each class, e.g., masks for every person in a crowd will have different colors. We illustrate this breakdown of how search space bodies pair and interact with task heads in Figure~\ref{fig:head_and_body} and provide finer details for each task head in the supplementary materials.
While prior neural predictors like \cite{white2019bananas} and \cite{wen2020neural}
adopt a customized encoding limited to predefined search space, e.g., NAS-Benchmarks on IC, we use a general encoding that can represent any neural network.
Specifically, we derive Computational Graphs (CG) using the underlying graph structure that libraries like TensorFlow~\cite{tensorflow2015-whitepaper} generate in the forward pass to execute backpropagation.
CGs are fine-grained graph structures where nodes denote individual atomic operations such as convolutions, linear layers, pooling, padding, addition, concatenation, etc.. Node features describe properties like kernel sizes, strides, and channels. Featureless, directed edges denote the flow of latent data across the network, allowing for a task-transferable representation that incorporates the body and task head.
Figure~\ref{fig:cg_se} illustrates how CGs represent one module of a MobileNetV3 (MBv3) body.
Finally, we note that our CG format can be extended to other network types, like those which perform Natural Language Processing tasks such as recurrent or attention-based models or even simple MLP models. However, such experiments are beyond the scope of this paper.
\begin{figure}
\centering
\includegraphics[width=3.25in]{fig/K_Adapter.pdf}
\caption{CG K-Adapter Diagram. We start with a graph encoder pre-trained on NAS-Bench-101 for IC and further extend the design with an adapter. The original encoder is frozen while we train the K-Adapter on a new search space and task, e.g., R50 on OD.}
\label{fig:k_adapt}
\end{figure}
\subsection{$K$-Adapters for Knowledge Infusion}
\label{sec:k_adapt}
AIO-P, as shown in Figure~\ref{fig:k_adapt}, starts with a
GNN~\cite{morris2019weisfeiler} regressor backbone.
The stem consists of an encoding layer that transforms discrete node features, e.g., operation categories, into a continuous format.
The GNN encoder takes the computational graph as input, learns node embeddings using the adjacency matrix, and generates an overall graph embedding by aggregating node embeddings. The graph embedding is fed into an MLP, which outputs a performance prediction.
In all our experiments, we pre-train the GNN regressor to predict classification accuracy
on 50k NAS-Bench-101 CGs.
To predict performance on another downstream CV task, we extend this base GNN regressor with $K$-Adapters to infuse external knowledge from other tasks and datasets beyond image classification. To do this, we discard the original regressor MLP and freeze all remaining weights. We append the $K$-Adapter by pairing each existing GNN layer in the encoder with a new GNN ``Adapter" layer.
Each adapter layer accepts concatenated input from the previous adapter layer and the adjacent GNN layer.
Formally, given the intermediate node embeddings for a graph $x$, we define the forward function to $K$-Adapter layer $GNN_k,i$ as
\begin{equation}
\centering
\label{eq:k_adapt_input}
h_x^{k,i} = GNN^{k,i}(Concat[h_x^{k,i-1}, h_x^{b,i}]),
\end{equation}
where $h_x^{k,i-1}$ and $h_x^{b,i}$ are the intermediate node embeddings produced by the previous $K$-Adapter layer and adjacent
GNN layer in the
backbone, respectively. Like the backbone, the $K$-Adapter produces an overall graph embedding.
We concatenate both graph embedding and feed it into a new MLP predictor.
Note that we can augment the original backbone with multiple $K$-Adapters, where each $K$-Adapter infuses the knowledge from a different task $t$. Hence, the overall predictor can generalize to different downstream tasks with different task head CG structures and labels.
\begin{table}[t]
\centering
\caption{Shared head performance distributions and SRCC on HPE PCK [\%]. We compare performance obtained using body swapping and latent sampling to the ground-truth PCK from individually training architectures.}
\scalebox{0.78}{
\begin{tabular}{l|c|c|c} \toprule
& \textbf{PN} & \textbf{MBv3} & \textbf{R50} \\ \midrule
\#Architectures & 215 & 217 & 215 \\
Ground-Truth & 65.16 $\pm$ 0.80\% & 65.22 $\pm$ 0.77\% & 65.64 $\pm$ 0.88\% \\ \midrule
Body Swap PCK & 52.67 $\pm$ 1.47\% & 43.62 $\pm$ 0.58\% & 49.61 $\pm$ 0.56\% \\
SRCC & 0.574 & 0.443 & 0.246 \\ \midrule
Sampling PCK & 59.57 $\pm$ 1.06\% & 61.58 $\pm$ 0.99\% & 59.46 $\pm$ 6.08\% \\
SRCC & \textbf{0.659} & \textbf{0.576} & \textbf{0.375} \\
\bottomrule
\end{tabular}
}
\label{tab:sample_srcc}
\end{table}
\subsection{Training $K$-Adapters based on Latent Sampling}
\label{sec:shared_head}
To train $K$-adapters,
we need datasets composed of architecture samples and their performance labels on tasks other than IC.
We can obtain task-specific labels by sampling a body from a search space, e.g., OFA, coupling it with a task head, and training it. However, this is costly. Rather than having AIO-P learn on ground-truth labels obtained from individually trained architectures,
we propose a pseudo-labeling method to efficiently obtain task-specific labels to train adapters,
via a specially-trained task head that is \textit{shared} amongst all network bodies in a search space.
A typical approach for training a shared task head is `body swapping', which involves iteratively sampling pre-trained architecture bodies from a
search space, e.g., OFA, attaching them to the shared head and training the head on a few batches of images.
However, note that during body swapping, for each mini-batch of images, the head only samples a single body.
To encourage randomness, rather than sampling body networks, we propose an approach where we directly sample the latent representations of the mini-batch of images from a distribution as if they are
generated by sampled bodies. Yet, this will further mimic random body sampling per image instead of per mini-batch.
Specifically, let $x$ be an image, $\mathcal{S}$ be an architecture search space and $B \in \mathcal{S}$ be a body network. As OFA search spaces each contain roughly $10^{18}$ bodies, we take a subset of architectures $\mathcal{S}'$ and compute the mean $\vec{\mu}(x)$ and standard deviation $\vec{\sigma}(x)$ of their latent representations of image $x$, i.e.,
\begin{equation}
\centering
\label{eq:math_mu}
\vec{\mu}(x) = \mathbb{E}_{B \in \mathcal{S}'}[f_{B}(x)],
\end{equation}
\begin{equation}
\centering
\label{eq:math_sig}
\vec{\sigma}^2(x) = \text{Var}_{B \in \mathcal{S}'}[f_{B}(x)],
\end{equation}
where $f_B$ denotes the function given by network body $B$. We then sample a latent representation $\vec{z}(x) = \vec{\mu}(x) + \vec{\zeta} \circ \vec{\sigma}(x)$ where $\vec{\zeta}$ is a standard normal $\mathcal{N}(0, 1)$ random vector
and $\circ$ is element-wise multiplication. We denote this approach as `latent sampling', where we train the shared task head by $\{(\vec{z}(x), y_x)\}$,
using the sampled latent vector $\vec{z}(x)$ as input to the head and $y_x$ as the ground-truth task label for $x$.
We limit the size of $\mathcal{S}'$ and use a round robin strategy with binning to constantly swap new bodies into $\mathcal{S}'$. We provide procedural details on our round robin strategy,
shared head hyperparameters and resource cost breakdown in the supplementary materials.
To assess the reliability of our pseudo-labelling approach, we form a ground-truth set by individually training several hundred architectures (with bodies sampled from three spaces) on the Leeds Sports Pose-Extended (LSP) dataset for Human Pose Estimation (HPE) and measure performance in terms of Percentage of Correct Keypoints (PCK).
We obtain pseudo-labels by fine-tuning the same bodies when connected to shared heads trained using \textit{body swapping} and \textit{latent sampling}, respectively. We compare the PCK distributions and SRCC between the pseudo-labels
and ground-truth labels.
We do not use the pseudo-labeled architectures from this experiment to train AIO-P. They are only for comparison.
Table~\ref{tab:sample_srcc} shows the results.
We note that latent sampling achieves much better performance on average, relative to the ground truth, while body swapping lags by over 10\%.
Also, the SRCC we observe using the latent sampling approach is positive for all search spaces and more favorable than
body swapping.
\begin{table}[t]
\centering
\caption{AIO-P $K$-Adapter dataset size, across each search space and task. `/' denotes architectures that we individually train (left) and those we label using a shared head (right).}
\scalebox{0.78}{
\begin{tabular}{l|c|c|c} \toprule
\textbf{Task} & PN & MBv3 & R50 \\ \midrule
HPE-LSP & 215/2580 &217/2862 &215/2986 \\
HPE-MPII & 246/- &236/- &236/- \\
OD/IS/SS/PS & 118/1633 &118/1349 &115/1399 \\ \bottomrule
\end{tabular}
}
\label{tab:dataset_size}
\end{table}
\begin{table*}[t]
\centering
\caption{MAE [\%] of AIO-P on three search spaces and six tasks in the zero-shot transfer setting (no fine-tuning), compared to
GNN without and with rescaling by Eqs.~\ref{eq:standardization}, \ref{eq:accTrans}. AIO-P adopts 2 $K$-Adapters, trained on LSP and OD. AIO-P uses Equation~\ref{eq:accTrans} and standardize regression targets. Results averaged across 5 seeds. }
\scalebox{0.73}{
\begin{tabular}{l|ccc|ccc|ccc} \toprule
& & \textbf{ProxylessNAS} & & & \textbf{MobileNetV3} & & & \textbf{ResNet-50} & \\ \midrule
\textbf{Task} & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P \\ \midrule
LSP & 27.27 $\pm$ 0.39\% & 0.72 $\pm$ 0.14\%&\textbf{0.70} $\pm$ 0.23\% & 27.07 $\pm$ 0.53\% &0.74 $\pm$ 0.11\%& \textbf{0.52} $\pm$ 0.01\% & 21.47 $\pm$ 2.56\% & 1.07 $\pm$ 0.07\% &\textbf{0.94} $\pm$ 0.05\% \\
MPII & 8.10 $\pm$ 0.38\% & \textbf{0.34} $\pm$ 0.07\%& 0.42 $\pm$ 0.13\% & 8.91 $\pm$ 0.52\%&0.36 $\pm$ 0.05\%& \textbf{0.27} $\pm$ 0.01\% & 2.48 $\pm$ 1.93\% & 1.11 $\pm$ 0.05\% &\textbf{1.03} $\pm$ 0.07\% \\
OD & 59.53 $\pm$ 0.41\% & 1.15 $\pm$ 0.46\%&\textbf{0.63} $\pm$ 0.09\% & 59.56 $\pm$ 0.37\% &1.24 $\pm$ 0.14\%& \textbf{0.62} $\pm$ 0.04\% & 54.07 $\pm$ 1.31\% & 0.88 $\pm$ 0.18\% &\textbf{0.60} $\pm$ 0.02\% \\
IS & 62.00 $\pm$ 0.34\% & 0.93 $\pm$ 0.18\%&\textbf{0.52} $\pm$ 0.14\% & 61.76 $\pm$ 0.33\% &0.73 $\pm$ 0.07\%& \textbf{0.58} $\pm$ 0.07\% & 56.74 $\pm$ 1.66\% & 0.64 $\pm$ 0.09\% &\textbf{0.48} $\pm$ 0.01\% \\
SS & 53.07 $\pm$ 0.37\% & 0.71 $\pm$ 0.22\%&\textbf{0.50} $\pm$ 0.06\% & 53.40 $\pm$ 0.39\% &0.90 $\pm$ 0.09\%& \textbf{0.56} $\pm$ 0.04\% & 47.90 $\pm$ 2.68\% & 0.52 $\pm$ 0.02\% &\textbf{0.44} $\pm$ 0.02\% \\
PS & 56.19 $\pm$ 0.35\% & 0.76 $\pm$ 0.07\%&\textbf{0.50} $\pm$ 0.10\% & 56.18 $\pm$ 0.33\% &0.74 $\pm$ 0.05\%& \textbf{0.57} $\pm$ 0.04\% & 51.63 $\pm$ 1.69\% & 0.52 $\pm$ 0.04\% &\textbf{0.45} $\pm$ 0.01\% \\ \bottomrule
\end{tabular}
}
\label{tab:main_mae}
\end{table*}
\begin{table*}[t]
\centering
\caption{SRCC on AIO-P on three search spaces and size tasks.
Same configurations as Table~\ref{tab:main_mae}.}
\scalebox{0.73}{
\begin{tabular}{l|ccc|ccc|ccc} \toprule
& & \textbf{ProxylessNAS} & & & \textbf{MobileNetV3} & & & \textbf{ResNet-50} & \\ \midrule
\textbf{Task} & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P \\ \midrule
LSP & 0.593 $\pm$ 0.02 & 0.561 $\pm$ 0.05&\textbf{0.698} $\pm$ 0.01 & 0.259 $\pm$ 0.09 & 0.418 $\pm$ 0.06&\textbf{0.556} $\pm$ 0.01 & -0.302 $\pm$ 0.02 & 0.176 $\pm$ 0.03&\textbf{0.261} $\pm$ 0.02 \\
MPII & 0.711 $\pm$ 0.01 & \textbf{0.767} $\pm$ 0.02&0.753 $\pm$ 0.01 & 0.300 $\pm$ 0.14 & \textbf{0.764} $\pm$ 0.01&0.701 $\pm$ 0.02 & -0.315 $\pm$ 0.02 & 0.446 $\pm$ 0.03&\textbf{0.532} $\pm$ 0.02 \\
OD & 0.558 $\pm$ 0.06 & 0.471 $\pm$ 0.11&\textbf{0.781} $\pm$ 0.03 & \textbf{0.645} $\pm$ 0.05 & 0.087 $\pm$ 0.14& 0.515 $\pm$ 0.05 & -0.489 $\pm$ 0.11 & 0.645 $\pm$ 0.03&\textbf{0.817} $\pm$ 0.01 \\
IS & 0.599 $\pm$ 0.07 & 0.211 $\pm$ 0.10&\textbf{0.831} $\pm$ 0.02 & 0.592 $\pm$ 0.07 & 0.034 $\pm$ 0.03&\textbf{0.602} $\pm$ 0.05 & -0.493 $\pm$ 0.08 & 0.495 $\pm$ 0.04&\textbf{0.817} $\pm$ 0.01 \\
SS & 0.487 $\pm$ 0.03 & 0.262 $\pm$ 0.18&\textbf{0.735} $\pm$ 0.02 & 0.517 $\pm$ 0.08 & -0.367 $\pm$ 0.11& \textbf{0.689} $\pm$ 0.02 & -0.406 $\pm$ 0.03 & 0.589 $\pm$ 0.03&\textbf{0.660} $\pm$ 0.02 \\
PS & 0.562 $\pm$ 0.00 & 0.119 $\pm$ 0.12&\textbf{0.732} $\pm$ 0.03 & \textbf{0.570} $\pm$ 0.07 & -0.009 $\pm$ 0.06& 0.518 $\pm$ 0.04 & -0.455 $\pm$ 0.07 & 0.599 $\pm$ 0.03& \textbf{0.788} $\pm$ 0.02 \\ \bottomrule
\end{tabular}
}
\label{tab:main_srcc}
\end{table*}
\subsection{Label Scaling}
\label{sec:label_scaling}
In addition to having different heads, task performance distributions differ.
PN architectures yield $\sim$75\%
accuracy on ImageNet, and around 40\% SS mIoU on COCO.
but note that performance distributions differ amongst tasks, or even the same task between ground truth and pseudo-labels.
Therefore, we experiment with methods that scale the labels AIO-P learns from to add further task transferability.
Specifically, we employ standardization,
\begin{equation}
\centering
\label{eq:standardization}
\mathcal{Z}(y) = \dfrac{y - \mu}{\sigma},
\end{equation}
where $\mu$ and $\sigma$ are the mean and standard deviation of the label $y$ distribution, respectively. This
approach
fits a set of data into a normal distribution $\mathcal{N}(0, 1)$. Further, we incorporate scaling by FLOPs,
or Floating Point Operations required to perform the forward pass of a network, as a divisor prior to standardization,
\begin{equation}
\centering
\label{eq:accTrans}
y_{F} = y\cdot(\texttt{Log}_{10}(F+1)+1)^{-1},
\end{equation}
where $F$ are the FLOPs of the network with performance $y$, measured in GigaFLOPs (1e9), and the addition of 1 in the denominator assures it will be positive real number. In all cases, if we apply Equation~\ref{eq:accTrans} to labels, we then standardize them using Equation~\ref{eq:standardization}.
\section{Related Work}
\label{sec:related}
\begin{figure}
\centering
\includegraphics[width=3.25in]{fig/body_and_head.pdf}
\caption{Network bodies from classification search spaces can pair with heads for different tasks.
A simple classification head has pooling and a linear layer. Faster R-CNN~\cite{ren2015faster} uses a Feature Pyramid Network (FPN) with
feature maps of different sizes. FPN
feeds a Regional Proposal Network (RPN) and a Region of Interest module (RoI) to
estimate bounding boxes.}
\label{fig:head_and_body}
\end{figure}
Benchmark datasets and neural predictors provide a quick avenue for performance estimation.
Arguably, the most significant difference is how performance is queried. For example, NAS-Bench-101 and 201 contain 423k and 15.6k architectures, respectively. They store individual architecture performances on a look-up table. By contrast, NAS-Bench-301 operates on the DARTS search space, which contains $~10^{18}$ architectures which are too many to evaluate individually.
Instead, they train a neural predictor~\cite{zela2022surrogate, luo2020semi, lu2021TNASP, wu2021stronger}.
In both cases, architecture configurations define the keys to the table or predictor input, and serve to showcase the limitations of these approaches. Specifically, these configurations are for micro, cell-based NAS, where a network is built by stacking identical cell structures.
These configurations generally assume details like latent representation sizes and the number of cells in the network to be constant.
On the other hand, OFA networks~\cite{cai2020once} use macro search spaces where networks are built by individually selecting and then stacking pre-defined blocks.
It searches over the number of blocks in the network and
kernel size and channel expansions~\cite{mills2021profiling} within a block.
Regardless, both approaches assume the stem and head of the network to be
an nonsearchable fixed structure.
This is acceptable when considering one task.
They also abstract multiple operations into pre-defined sequences, e.g., MBConv block, that is specific to the search space and network body and thus may not exist in the head.
By contrast, we aim to predict performance across various tasks with different heads and data sizes. Thus, we require a more robust and generalizable data format. AIO-P uses Compute Graphs (CG) as input, which incorporates full network topological details, latent tensors size, and node features.
A few approaches appear in the literature regarding NAS for CV tasks other than IC. For example, \cite{ding2021learning} use NAS on nine tasks, including IC and SS. They perform a search to find architectures that provide high-performance on multiple objectives. Auto-DeepLab~\cite{liu2019auto} reconfigure DARTS to perform variable upsampling/downsampling and search for a good SS architecture. Next, TransNAS-Bench-101~\cite{duan2021transnas} train architectures from separate micro and macro search spaces on various tasks for several hours and demonstrate the performance of multiple search algorithms. In contrast, we train architectures using the hyperparameters of Detectron2~\cite{wu2019detectron2} and \cite{Zhou_2017_ICCV}. We develop a novel shared head approach to build a generalizable performance predictor that learns on data from multiple CV tasks and predicts the performance of other downstream tasks.
\section{Results}
\label{sec:results}
\begin{table*}[t]
\centering
\caption{SRCC between
AIO-P, ZCP methods and a FLOPs-based predictor on three tasks.
We also include `AIO-P FT', i.e., fine-tuning
on
20 held-out standardization samples.
We bold the best result and italicize the second best.}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c|c|c|c|c} \toprule
\textbf{Space} & \textbf{Synflow} & \textbf{Jacov} & \textbf{Fisher} & \textbf{Gradient Norm} & \textbf{Snip} & \textbf{FLOPs} & \textbf{AIO-P} & \textbf{AIO-P FT}\\ \midrule
PN-LSP & -0.004 $\pm$ 0.03 & -0.057 $\pm$ 0.04& 0.449 $\pm$ 0.03& 0.581 $\pm$ 0.03 &0.624 $\pm$ 0.16& 0.584 $\pm$ 0.01& \textbf{0.698} $\pm$ 0.01& \textit{0.668} $\pm$ 0.03\\
MBv3-LSP & \textbf{0.609} $\pm$ 0.01& 0.029 $\pm$ 0.10&0.129 $\pm$ 0.06& 0.426 $\pm$ 0.03 & 0.466 $\pm$ 0.01& 0.562 $\pm$ 0.01& 0.556 $\pm$ 0.01& \textit{0.567} $\pm$ 0.01\\
R50-LSP & \textbf{0.639} $\pm$ 0.01& -0.071 $\pm$ 0.03&0.515 $\pm$ 0.01& 0.581 $\pm$ 0.02 & \textit{0.646} $\pm$ 0.02& 0.263 $\pm$ 0.02& 0.261 $\pm$ 0.02& 0.264 $\pm$ 0.02\\ \midrule \midrule
PN-MPII & 0.046 $\pm$ 0.07& -0.008 $\pm$ 0.08&0.538 $\pm$ 0.03& 0.733 $\pm$ 0.01 & \textit{0.755} $\pm$ 0.01 & 0.735 $\pm$ 0.00& 0.753 $\pm$ 0.01& \textbf{0.773} $\pm$ 0.02\\
MBv3-MPII & \textit{0.736} $\pm$ 0.01& -0.014 $\pm$ 0.09&0.203 $\pm$ 0.08& 0.679 $\pm$ 0.03 & 0.691 $\pm$ 0.04& \textit{0.736} $\pm$ 0.01& 0.701 $\pm$ 0.02& \textbf{0.744} $\pm$ 0.05\\
R50-MPII & \textbf{0.865} $\pm$ 0.01& 0.111 $\pm$ 0.08&0.709 $\pm$ 0.02& 0.732 $\pm$ 0.02 & \textit{0.849} $\pm$ 0.02& 0.532 $\pm$ 0.02& 0.532 $\pm$ 0.02& 0.532 $\pm$ 0.02\\ \midrule \midrule
PN-SS & 0.022 $\pm$ 0.07& -0.023 $\pm$ 0.13& 0.050 $\pm$ 0.07& 0.141 $\pm$ 0.06 & -0.082 $\pm$ 0.07& 0.608 $\pm$ 0.01& \textit{0.735} $\pm$ 0.02& \textbf{0.849} $\pm$ 0.03\\
MBv3-SS & -0.309 $\pm$ 0.07& 0.042 $\pm$ 0.08&0.022 $\pm$ 0.06& 0.040 $\pm$ 0.06 &0.188 $\pm$ 0.04& 0.445 $\pm$ 0.02& \textit{0.689} $\pm$ 0.02& \textbf{0.822} $\pm$ 0.03\\
R50-SS & -0.255 $\pm$ 0.09& 0.141 $\pm$ 0.10&0.126 $\pm$ 0.059& 0.354 $\pm$ 0.08 & 0.036 $\pm$ 0.07& \textit{0.661} $\pm$ 0.02& 0.660 $\pm$ 0.02& \textbf{0.677} $\pm$ 0.03\\ \bottomrule
\end{tabular}
}
\label{tab:zcp}
\end{table*}
In this Section, we describe our suite of tasks, experimental setup and results. We consider the computer vision tasks of 2D Human Pose Estimation (HPE), Object Detection (OD), Instance Segmentation (IS), Semantic Segmentation (SS) and Panoptic Segmentation (PS).
HPE predicts
joint locations
from an image. We measure 2D HPE performance using Percentage of Correct Keypoints (PCK) and
consider two HPE datasets: MPII~\cite{MPII} and
Leeds Sports Pose-Extended (LSP)~\cite{lsp_extended}, which contain 22k and 11k images, respectively. We
individually train networks for both datasets and
train a shared head for LSP.
OD and IS measure performance in mean Average Precision (mAP), while SS uses mean Intersection over Union (mIoU). PS, a combination of IS and SS, uses Panoptic Quality (PQ), a balance of mAP and mIoU. The task units of each task metric are by percentage [\%]. We consider the 2017 version of MS Common Objects in Context (COCO)~\cite{coco} as our dataset for these tasks, as it contains 118 and 5k training and validation images, respectively. We use Detectron2~\cite{wu2019detectron2} to pair a given body with OD, IS SS, and PS to train on all four tasks simultaneously.
Table~\ref{tab:dataset_size}
enumerates of the number of architectures we have for each search space and task. We use pseudo-labeled architecture CGs to train AIO-P and reserve individually trained ones as held-out test samples. Additionally, we include a more extensive breakdown with performance and FLOPs distributions in the supplementary materials.
\subsection{Training Procedure}
\label{sec:training}
Starting with the GNN backbone,
we append two $K$-Adapter modules. We train these using the pseudo-labeled CGs for two
task domains, OD ans LSP-HPE.
We separately apply Equation~\ref{eq:accTrans} and then standardize the labels of each $K$-Adapter task before training and freeze the weights of the GNN backbone.
To evaluate individually trained test set CGs for a task, we consider the zero-shot transfer context where we provide no data on a target task
prior to inference.
Similar to \citet{lu2021one}, we sample 20 random architectures from the test set to compute standardization parameters $\mu$ and $\sigma$ and exclude these architectures from evaluation.
We also consider a fine-tuning context where we use the same 20 random architectures to train AIO-P prior to inference. As we evaluate multiple methods using different random seeds, we ensure the set of 20 sampled architectures is the same for every seed value.
Also, note that the set of body architectures we individually train on any task are disjoint from the ones we pseudo-label.
We provide granular predictor details and
training hyperparameters in the supplementary materials.
\subsection{Zero-Shot Transfer Performance}
\label{sec:zero_shot}
We consider two predictor evaluation metrics, Mean Absolute Error (MAE) and Spearman's Rank Correlation Coefficient (SRCC). The former gauges a predictor's ability to make accurate estimations on individual labels, while the latter determines a predictor's capacity to correctly rank a population by performance.
We report MAE as a percentage for each task metric,
e.g., PCK for HPE and mIoU for SS, where lower is better. SRCC falls in $[-1, 1]$ and indicates agreement with ground-truth ordering, so higher is better.
Tables~\ref{tab:main_mae} and \ref{tab:main_srcc} list our results for AIO-P
in terms of MAE and SRCC, respectively.
AIO-P achieves the best MAE performance in the majority of scenarios, including every task on MBv3 and R50. The sole exception is a GNN using standardization and FLOPs scaling for MPII by less than 0.1\% MAE, while the unmodified GNN fails to generalize to different task performance distributions.
For
SRCC, AIO-P consistently achieves the best correlation on all R50 tasks and in at least half for PN and MBv3. While both variants of the GNN obtain the high SRCC on at least one search space and task pair, they are overall very inconsistent as the GNN with re-scaled labels achieves negative SRCC on MBv3 and the
unmodified GNN fails
on R50.
Next,
Table~\ref{tab:zcp} compares the ranking performance of AIO-P with Zero-Cost Proxies (ZCP) and FLOPs. Without fine-tuning, AIO-P achieves high correlation performance for all search spaces on MPII and SS, as well as PN and MBv3 for LSP, demonstrating high generalizability. The most competitive ZCP method is Synflow~\cite{tanaka2020pruning}, but only for HPE tasks with MBv3 and R50 as it fails on PN and in the SS context. Gradient norm achieves positive SRCC across all search spaces and tasks but never the best performance. FLOPs are also highly correlated with performance in all settings, except LSP for R50.
Unlike ZCP, the advantage of AIO-P in this context is its ability undergo fine-tuning to boost performance, as shown for the MPII and SS tasks.
Next, we compare Eqs.~\ref{eq:standardization} and \ref{eq:accTrans} with another fine-tuning-based method for intertask prediction.
\begin{table}[t]
\centering
\caption{MAE of AIO-P on MPII, IS and PS for the MBv3 search space (with fine-tuning). A single $K$-Adapter was trained on SS for AIO-P variants.
}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c} \toprule
\textbf{Task} & \textbf{GNN} & \textbf{AIO-P+AdaProxy} & \textbf{AIO-P w/o Eq.~\ref{eq:accTrans}} & \textbf{AIO-P} \\ \midrule
MPII & 0.33\% & 0.35\% & \textit{0.29}\% & \textbf{0.25}\% \\
Inst. Seg. & 0.66\% & \textit{0.47}\% & \textbf{0.39}\% & 0.58\% \\
Pan. Seg. & 0.64\% & \textit{0.51}\% & \textbf{0.46}\% & 0.61\% \\ \bottomrule
\end{tabular}
}
\label{tab:rescale_mae}
\end{table}
\begin{table}[t]
\centering
\caption{SRCC of AIO-P on MPII, IS and PS for the MBv3 search space (with fine-tuning). A single $K$-Adapter was trained for SS on AIO-P variants.}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c} \toprule
\textbf{Task} & \textbf{GNN} & \textbf{AIO-P+AdaProxy} & \textbf{AIO-P w/o Eq.~\ref{eq:accTrans}} & \textbf{AIO-P} \\ \midrule
MPII & \textit{0.680} & 0.574 & 0.650 & \textbf{0.750} \\
Inst. Seg. & 0.547 & \textit{0.677} & \textbf{0.747} & 0.585 \\
Pan. Seg. & 0.568 & \textit{0.627} & \textbf{0.685} & 0.512 \\ \bottomrule
\end{tabular}
}
\label{tab:rescale_srcc}
\end{table}
\subsection{Fine-Tuning Results}
\label{sec:adaproxy}
We now evaluate the transferability of AIO-P on downstream tasks if predictor fine-tuning is allowed based on a small number, i.e., 20,
downstream architectures. As a comparison, we also evaluate AIO-P using
a weight scaling technique proposed in AdaProxy~\cite{lu2021one},
which scales the final MLP layer of a predictor by minimizing the following loss on fine-tuning samples:
\[\min_{\alpha, \vec{b}} |[(\alpha\vec{I}^T + \vec{b}^T) \circ \vec{w}^T]\vec{x} - y|^{2} + \lambda|\vec{b}|,\]
where $\alpha$ is a scalar, $\vec{I}$ is an identity vector, $\vec{w}$ are the weights in the final layer,
$\vec{b}$ is a sparsity vector and $\lambda$ is a regularizer weight. During this minimization, all of the original predictor weights
are frozen.
For this experiment, we consider the MBv3 search space, train a $K$-Adapter on SS and evaluate on MPII, IS and PS.
Tables~\ref{tab:rescale_mae} and \ref{tab:rescale_srcc} list our results in terms of MAE and SRCC, respectively.
We are able to obtain more accurate predictions in terms of MAE and SRCC using some form of standardization rather than AdaProxy. On MPII specifically, Eq.~\ref{eq:accTrans} overcomes the limitations of low inter-task correlation to produce the best MAE and SRCC, while just using standardization is enough to obtain the most accurate IS and PS predictions. Another advantage of our standardization and FLOPs-based transform approach is the absence of tunable hyperparameters, e.g., $\lambda$.
\begin{table}[t]
\centering
\caption{MAE of different $K$-Adapter tasks on the PN search space.
`FT' indicates fine-tuning on 20 held-out target architectures. We bold the best result and italicize the second best.}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c|c} \toprule
\textbf{Task} & \textbf{OD} & \textbf{SS} & \textbf{LSP} & \textbf{OD+SS} & \textbf{OD+LSP} \\ \midrule
MPII & 0.60\% & 0.39\% & \textbf{0.28}\% & \textit{0.35}\% & 0.42\% \\
IS & 0.70\% & \textit{0.56}\% & 1.03\% & 0.61\% & \textbf{0.52}\% \\
PS & \textit{0.75}\% & 0.82\% & 1.03\% & 0.81\% & \textbf{0.50}\% \\ \midrule
MPII FT & \textbf{0.25}\% & \textit{0.26}\% & 0.27\% & 0.27\% & \textit{0.26}\% \\
IS FT & 0.49\% & 0.50\% & \textbf{0.27}\% & 0.50\% & \textit{0.33}\% \\
PS FT & 0.50\% & 0.54\% & \textbf{0.31}\% & 0.52\% & \textit{0.33}\% \\ \bottomrule
\end{tabular}
}
\label{tab:ablation_k_mae}
\end{table}
\begin{table}[t]
\centering
\caption{SRCC of different $K$-Adapter tasks on the PN search space.
`FT' indicates fine-tuning on 20 held-out target architectures. We bold the best result and italicize the second best.}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c|c} \toprule
\textbf{Task} & \textbf{OD} & \textbf{SS} & \textbf{LSP} & \textbf{OD+SS} & \textbf{OD+LSP} \\ \midrule
MPII & \textbf{0.762} & 0.660 & 0.717 & 0.727 & \textit{0.753} \\
IS & 0.749 & 0.728 & \textbf{0.929} & 0.750 & \textit{0.831} \\
PS & 0.650 & 0.669 & \textbf{0.859} & 0.672 & \textit{0.732} \\ \midrule
MPII FT & \textbf{0.793} & \textit{0.790} & 0.764 & 0.779 & 0.773 \\
IS FT & 0.749 & 0.757 & \textbf{0.915} & 0.730 & \textit{0.894} \\
PS FT & 0.670 & 0.671 & \textbf{0.880} & 0.647 & \textit{0.858} \\ \bottomrule
\end{tabular}
}
\label{tab:ablation_k_srcc}
\end{table}
\subsection{Ablation Study}
\label{sec:ablation}
We ablate the effect of different $K$-Adapter training tasks using PN as an example search space. Tables~\ref{tab:ablation_k_mae} and \ref{tab:ablation_k_srcc} show our MAE and SRCC findings, respectively.
We see that using a double $K$-Adapter on OD and LSP helps to generalize MAE and SRCC performance across the downstream tasks. While the best results typically use just OD or LSP, LSP struggles to produce low MAE on IS and PS without fine-tuning. However, we overcome this hurdle when adding another $K$-Adapter for OD.
First, we note that the best results use either OD or LSP, although SS still produces good results. Particularly, LSP struggles to produce low MAE on IS and PS without fine-tuning. Introducing another $K$-Adapter for OD overcomes this hurdle.
Additionally, we compare the GNN backbone to using a single $K$-Adapter, using standardization (Eq.~\ref{eq:standardization}), and then our FLOPs scaling (Eq.~\ref{eq:accTrans}).
Tables~\ref{tab:transform_mae} and \ref{tab:transform_srcc} list our results for MAE and SRCC, respectively. We see that AIO-P with or without Eq.~\ref{eq:accTrans} can obtain top MAE performance in most scenarios in the zero-shot and fine-tuning contexts. However, that is not the case for SRCC, where Eq.~\ref{eq:accTrans} allows AIO-P to achieve correlation metrics above 0.8 with fine-tuning. While the normal GNN is not very competitive, adding a single $K$-Adapter without standardization can improve ranking performance significantly. However, the prediction error is still high due to differences in task performance distributions (Tables~\ref{tab:app_full_architecture_description} and \ref{tab:app_shared_head_architecture_description}). Overall, standardization and Eq.~\ref{eq:accTrans} allow AIO-P to strike a balance between prediction error and ranking correlation.
\begin{table}[t!]
\centering
\caption{MAE performance
comparing the effect of $K$-Adapters as well as Eqs.~\ref{eq:standardization} and \ref{eq:accTrans}
in the zero-shot
and fine-tuning (-FT) contexts.
We consider the R50 search space and train a $K$-Adapter on SS. We bold the best result and italicize the second best.}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c} \toprule
\textbf{Task} & \textbf{GNN} & \textbf{+$K$-Adapter} & \textbf{+ Eq.~\ref{eq:standardization}} & \textbf{AIO-P} \\ \midrule
MPII & 2.48\% & 55.30\% & \textbf{0.39}\% & \textit{2.38}\% \\
IS & 56.74\% & \textit{2.38}\% & \textbf{0.73}\% & \textbf{0.73}\% \\
PS & 51.63\% & 7.39\% & \textit{0.89}\% & \textbf{0.61}\% \\ \midrule
MPII-FT & 0.28\% & \textit{0.77}\% & \textbf{0.15}\% & 1.09\% \\
IS-FT & 0.61\% & 0.85\% & \textbf{0.36}\% & \textit{0.45}\% \\
PS-FT & 0.71\% & 0.61\% & \textbf{0.40}\% & \textit{0.44}\% \\ \bottomrule
\end{tabular}
}
\label{tab:transform_mae}
\end{table}
\begin{table}[t]
\centering
\caption{SRCC performance
comparing the effect of $K$-Adapters.
Same experimental setup as Table~\ref{tab:transform_mae}.}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c|c} \toprule
\textbf{Task} & \textbf{GNN} & \textbf{+$K$-Adapter} & \textbf{+ Eq.~\ref{eq:standardization}} & \textbf{AIO-P} \\ \midrule
MPII & -0.315 & \textbf{0.708} & \textit{0.418} & 0.337 \\
IS & -0.493 & \textbf{0.669} & \textit{0.361} & 0.324 \\
PS & -0.455 & \textbf{0.633} & \textit{0.399} & 0.291 \\ \midrule
MPII-FT & \textit{0.700} & \textbf{0.738} & 0.512 & 0.532 \\
IS-FT & 0.611 & 0.687 & \textit{0.727} & \textbf{0.840} \\
PS-FT & 0.601 & 0.667 & \textit{0.762} & \textbf{0.811} \\ \bottomrule
\end{tabular}
}
\label{tab:transform_srcc}
\end{table}
\subsection{Transfer to Foreign Network Types}
\label{sec:model_zoo}
To further test the transferability of AIO-P to new architecture types not seen in training, we perform inference on several foreign `model zoos', including
model zoos from the DeepLab repository~\cite{deeplabv3plus2018}, which all focus on semantic segmentation (SS),
as well as model zoos from TensorFlow-Slim~\cite{TFSlim} which all report image classification (IC) performance on ImageNet. Each model zoo contains 10 or fewer architecture variants, e.g., Inception~\cite{szegedy2017inception} and EfficientNets~\cite{tan2019efficientnet}.
\subsubsection{DeepLab Semantic Segmentation}
We consider architectures on three different SS datasets: ADE20k~\cite{zhou2017ADE}, Pascal VOC~\cite{everingham2015Pascal}, and Cityscapes~\cite{Cordts2016Cityscapes}. These are different SS datasets than the MS-COCO we use for training OFA-based architectures, so the results further demonstrate the generalizability of AIO-P across datasets, even for the same task. Specifically, we consider the following architecture per dataset:
\begin{enumerate}
\item \textbf{ADE20k} (5): MobileNetV2, Xception65~\cite{chollet2017xception} as well as Auto-DeepLab-\{S, M, L\}~\cite{liu2019auto}.
\item \textbf{Pascal VOC} (6): MobileNetV2, MobileNetV2 w/ reduced depth, Xception65 and Auto-DeepLab-\{S, M, L\}.
\item \textbf{Cityscapes} (8): MobileNetV2, MobileNetV3-Small, MobileNetV3-Large, Xception65, Xception71 and Auto-DeepLab-\{S, M, L\}.
\end{enumerate}
\subsubsection{TensorFlow-Slim Image Classification}
We also consider several architectures that perform IC on ImageNet:
\begin{enumerate}
\item \textbf{ResNets} (6): ResNet-v1-\{50, 101, 152\}~\cite{he2016deep} and ResNet-v2-\{50, 101, 152\}~\cite{he2016identity}.
\item \textbf{Inception} (5): Inception-\{v1, v2, v3, v4\} and Inception-ResNet-v2~\cite{szegedy2017inception}
\item \textbf{MobileNets} (6): MobileNetV1, MobileNetV1-0.5, MobileNetV1-0.25, MobileNetV2, MobileNetV2-1.4; where `-X.Y' flags refer to a multiplier on the number of channels.
\item \textbf{EfficientNets}~\cite{tan2019efficientnet} (8): EfficientNet-\{B0, B1, B2, B3, B4, B5, B6, B7\}.
\end{enumerate}
Using AIO-P pre-trained on ResNet-50 bodies and with a double $K$-Adapter trained on OD and LSP tasks, and then fine-tuned on SS (the task DeepLab performs), we investigate whether AIO-P can adequately rank the architectures in DeepLab and in TensorFlow-Slim, which contain new types of body networks other than ResNet-50.
As shown in Table~\ref{tab:model_zoo}, we note that AIO-P can achieve positive correlation inference on all SS and IC model zoos. In particular, we obtain perfect SRCC on EfficientNets. Moreover, this performance is superior to AIO-P when Eq.~\ref{eq:accTrans} is not present. This is because while standardization improves MAE performance, it does not affect architecture rankings, whereas FLOPs-based transformation does. These findings demonstrate the efficacy of AIO-P and Eq.~\ref{eq:accTrans} in ranking the performance of foreign networks with different connections/topologies.
\begin{table}[t]
\centering
\caption{SRCC of AIO-P on several `model zoos'.
Double horizontal line demarcates SS models from IC models.}
\label{tab:model_zoo}
\scalebox{0.8}{
\begin{tabular}{l|c|c|c} \toprule
\textbf{Model Zoo} & \textbf{\#Archs} & \textbf{AIO-P w/o Eq.~\ref{eq:accTrans}} & \textbf{AIO-P} \\ \midrule
DeepLab-ADE20k & 5 & 0.127 $\pm$ 0.255 & \textbf{0.991} $\pm$ 0.016 \\
DeepLab-Pascal & 6 & 0.392 $\pm$ 0.088 & \textbf{0.939} $\pm$ 0.035 \\
DeepLab-Cityscapes & 8 & 0.572 $\pm$ 0.031 & \textbf{0.925} $\pm$ 0.024\\ \midrule \midrule
Slim-ResNets & 6 & -0.577 $\pm$ 0.183 & \textbf{0.920} $\pm$ 0.106 \\
Slim-Inception & 5 & -0.700 $\pm$ 0.316 & \textbf{0.980} $\pm$ 0.040 \\
Slim-MobileNets & 5 & -0.500 $\pm$ 0.000 & \textbf{0.400} $\pm$ 0.535 \\
Slim-EfficientNets & 8 & \textbf{1.000} $\pm$ 0.000 & \textbf{1.000} $\pm$ 0.000 \\ \bottomrule
\end{tabular}
}
\end{table}
\subsection{Application to NAS}
\label{sec:nas}
Finally, we apply AIO-P to NAS.
Specifically, we use a predictor that achieves high SRCC on the bounding box task OD on R50, to optimize a proprietary neural network designed to perform Facial Recognition (FR) on mobile devices. AIO-P serves as a performance estimator and we pair it with a mutation-based search algorithm that aims to preserve network performance while reducing FLOPs. Although the architecture we optimize does not belong to any of the OFA search spaces we consider in this paper, like the aforementioned model zoos, AIO-P can estimate performance using the CG framework. Additionally, our mutation algorithm proposes edits to CGs that vary from swapping subgraphs of operation sequences to manually pruning the number of channels in a convolution node.
Table~\ref{tab:properitary} lists our results on this task. Specifically, we can maintain performance in most settings while reducing the computational burden by over 13.5\%. In the `dark' setting, where features can be hard to see, our model improves precision and recall by 0.2\% and 0.6\%, respectively. At most, we only lose 0.2\% precision and 0.8\% recall across other settings. Therefore, these findings demonstrate the efficacy of AIO-P in the NAS setting for any general neural network, not simply for well-known search spaces.
\section{Supplementary Material}
\label{sec:supp}
\subsection{Summary of Search Spaces and Tasks}
Figure~\ref{fig:intertask_srcc} illustrates SRCC between different tasks on each search space. Table~\ref{tab:app_full_architecture_description} enumerates the number of architectures we individually train across all search spaces and tasks. It also provides distributions for task performance, FLOPs, and parameters. Moreover, Table~\ref{tab:app_fps} reports Frames Per Second (FPS) distributions all search spaces performing Panoptic Segmentation. Finally, Table~\ref{tab:app_shared_head_architecture_description} provides a statistical breakdown
for architectures fine-tuned using latent sampling shared heads.
\subsection{Training Architectures Individually}
We form test sets for AIO-P by pairing bodies with task heads and training them individually following hyperparameters and learning schedules from previous works.
\subsubsection{Detectron2 (OD/IS/SS/PS)}
Using Detectron2~\cite{wu2019detectron2}, we can train architectures to perform Object Detection (OD), Instance Segmentation, Semantic Segmentation (SS) and Panoptic Segmentation (PS) all at once. Specifically, we adopt the training regime described by the configuration files \texttt{panoptic\_fpn\_R\_50\_1x.yaml}, \texttt{Base-Panoptic-FPN.yaml} as well as \texttt{Base-RCNN-FPN.yaml} when training OFA architectures. This setup includes all four input levels of the Feature Pyramid Net (FPN)~\cite{lin2017feature}, `$P^2$' through `$P^5$' (see the `Task Head Descriptions' subsection for a definition of these terms). Our FPN implementation performs additional downsampling to generate `$P^6$' from `$P^5$'. Specifically, this setup involves freezing pre-trained weights of the first two `stages' of the network that use the highest resolution feature tensors. Under this configuration, an architecture trains using a batch size of 16 for 90k steps with a base learning rate of 0.02, which we reduce at 60k and 80k by a factor of 10. It takes between 24 and 30 hours to train and evaluate a single architecture using 2 Tesla V100 GPUs with 32GB of VRAM, and ResNets take longer than MobileNets.
\subsubsection{Human Pose Estimation (HPE)}
We adopt the default parameters of \cite{Zhou_2017_ICCV} to perform 2D Human Pose Estimation (HPE) on MPII~\cite{MPII} and Leeds Sports Pose-Extended (LSP)~\cite{lsp_extended}. Specifically, we train an architecture for 140 epochs on a given dataset with a batch size of 32. The initial learning rate is 0.001, which we reduce by a factor of 10 at epochs 90 and 120. The size of an input image is 256 $\times$ 256 in this setting, and bodies from all OFA search spaces will downsample it down to a resolution of 8 $\times$ 8, after which we use a series of deconvolutions to upsample and produce joint heatmaps of size 64 $\times$ 64. MPII contains $J = 16$ joints by default, while LSP only contains 14. We adopt a technique from \cite{artacho2020unipose} to estimate labels for the thorax and hip, the two remaining joints. Training an architecture takes a few hours under these settings.
\begin{figure}[H]
\centering
\subfloat[]{\includegraphics[width=3.2in]{fig/ofa_pn_srcc.pdf}}\hspace{0mm}
\subfloat[]{\includegraphics[width=3.2in]{fig/ofa_mbv3_srcc.pdf}}\hspace{0mm}
\subfloat[]{\includegraphics[width=3.2in]{fig/ofa_resnet_srcc.pdf}}
\caption{Inter-task correlations for ProxylessNAS (a), MobileNetV3 (b) and ResNet50 (c). We measure SRCC by comparing the performance values of individually trained architectures across all tasks.}
\label{fig:intertask_srcc}
\end{figure}
\begin{table*}
\centering
\caption{Summary of statistics for individually trained architectures across all three OFA families and CV tasks in terms of number of architectures, task performance [\%], and resource metrics such as FLOPs [G] and parameters [M] for all tasks. For all metrics, we report the mean and standard deviation on one line, and the range on the second line.}
\label{tab:app_full_architecture_description}
\scalebox{0.7}{
\begin{tabular}{l|c|c|c|c|c|c|c} \toprule
\textbf{Family} & \textbf{Classification} & \textbf{LSP HPE} & \textbf{MPII HPE} & \textbf{Obj. Det.} & \textbf{Inst. Seg.} & \textbf{Sem. Seg.} & \textbf{Pan. Seg.} \\ \midrule \midrule
PN (\# Archs) & 8.2k & 215 & 246 & 118 & 118 & 118 & 118 \\ \midrule
Performance [\%] & 75.41 $\pm$ 0.09 & 65.16 $\pm$ 0.80 & 84.33 $\pm$ 0.47 & 33.37 $\pm$ 1.01 & 31.04 $\pm$ 0.82 & 39.61 $\pm$ 0.72 & 36.90 $\pm$ 0.73 \\
& [71.15, 77.81] &[62.77, 66.92] &[82.79, 85.15] &[30.17, 35.62] &[28.33, 32.85] &[37.10, 40.85] &[34.25, 38.49] \\ \midrule
FLOPs [G] & 1.12 $\pm$ 0.14 & 15.73 $\pm$ 0.17 & 15.73 $\pm$ 0.17 & 86.82 $\pm$ 1.07 & 125.50 $\pm$ 1.07 & 63.64 $\pm$ 1.07 & 174.02 $\pm$ 1.07 \\
& [0.69, 1.59] & [15.28, 16.13] &[15.28, 16.26] &[84.09, 89.25] &[122.77, 127.93] &[60.91, 66.07] &[171.29, 176.45] \\ \midrule
Params [M] & 5.30 $\pm$ 0.60 & 12.54 $\pm$ 0.60 & 12.55 $\pm$ 0.61 & 32.36 $\pm$ 0.56 & 20.70 $\pm$ 0.56 & 20.13 $\pm$ 0.56 & 37.67 $\pm$ 0.56 \\
& [3.88, 7.18] & [11.32, 14.13] &[11.32, 14.13] &[31.43, 33.52] &[19.76, 21.86] &[19.19, 21.29] &[36.73, 38.83] \\ \midrule
\midrule
MBv3 (\# Archs) & 7.5k & 217 & 236 & 118 & 118 & 118 & 118 \\ \midrule
Performance [\%] & 76.94 $\pm$ 0.08 & 65.22 $\pm$ 0.77 & 83.38 $\pm$ 0.46& 33.39 $\pm$ 0.89& 31.25 $\pm$ 0.70& 39.27 $\pm$ 0.90& 36.88 $\pm$ 0.73 \\
& [73.56, 78.83] &[62.27, 67.14] &[81.82, 84.39] &[30.54, 35.38] &[28.93, 32.87] &[36.94, 41.07] &[35.02, 38.50] \\ \midrule
FLOPs [G] & 0.90 $\pm$ 0.13 & 14.36 $\pm$ 0.16 & 14.36 $\pm$ 0.16 & 84.70 $\pm$ 1.00 & 123.38 $\pm$ 1.00 & 61.52 $\pm$ 1.00 & 171.84 $\pm$ 1.00 \\
& [0.52, 1.37] &[13.95, 14.76] &[13.95, 14.76] &[82.06, 87.20] &[120.74, 125.89] &[58.88, 64.02] & [169.19, 174.34] \\ \midrule
Params [M] & 6.71 $\pm$ 0.85 & 10.26 $\pm$ 0.88 & 10.24 $\pm$ 0.88 & 36.48 $\pm$ 0.85 & 24.82 $\pm$ 0.85 & 24.24 $\pm$ 0.85 & 41.79 $\pm$ 0.85 \\
& [4.71, 9.89] &[8.51, 12.43] &[8.51, 12.43] &[34.73, 38.64] &[23.06, 26.98] &[22.49, 26.41] &[58.88, 64.02] \\ \midrule
\midrule
R50 (\# Archs) & 10k & 215 & 236 & 115 & 115 & 115 & 115 \\ \midrule
Performance [\%] & 78.19 $\pm$ 0.07 & 65.64 $\pm$ 0.88 & 85.40 $\pm$ 0.40 & 35.86 $\pm$ 1.02 & 32.88 $\pm$ 0.80 & 39.41 $\pm$ 0.71 & 37.98 $\pm$ 0.71 \\
& [75.25, 79.94] &[62.67, 67.80] &[84.14, 86.28] &[32.97, 38.18] &[30.58, 34.57] &[37.58, 40.84] &[35.81, 39.49] \\ \midrule
FLOPs [G] & 5.89 $\pm$ 1.22 & 22.17 $\pm$ 1.97 & 22.16 $\pm$ 1.99 & 133.94 $\pm$ 11.39 & 172.62 $\pm$ 11.39 & 110.76 $\pm$ 11.39 & 221.14 $\pm$ 11.39 \\
& [2.67, 11.39] &[17.68, 27.60] &[17.68, 27.60] & [110.88, 164.95] & [149.57, 203.64] &[87.70, 141.77] & [198.08, 252.15] \\ \midrule
Params [M] & 18.68 $\pm$ 5.79 & 26.57 $\pm$ 6.48 &26.63 $\pm$ 6.60 & 86.73 $\pm$ 6.07 & 75.06 $\pm$ 6.07 & 74.49 $\pm$ 6.07 & 92.03 $\pm$ 6.07 \\
& [7.19, 41.15] &[14.84, 47.75] &[14.84, 47.76] &[76.34, 107.00] &[64.67, 95.34] &[64.10, 94.76] &[81.64, 141.77] \\
\bottomrule
\end{tabular}
}
\end{table*}
\begin{table}
\centering
\caption{Average Frames Per Second for Panoptic Segmentation. We measure on an NVIDIA V100 GPU with 32GB of VRAM using a batch size of 1 on the COCO validation set. We measure the average time to perform inference
(FPS Infer) and including post-processing (FPS).}
\scalebox{0.7}{
\begin{tabular}{l|c|c} \toprule
& \textbf{FPS Infer} & \textbf{FPS} \\ \midrule
PN & 17.15 $\pm$ 0.52 & 7.94 $\pm$ 0.19 \\
& [16.13, 18.71] & [7.45, 8.35] \\ \midrule
MBv3 & 15.72 $\pm$ 0.84 & 6.63 $\pm$ 0.52 \\
& [13.59, 18.66] & [5.60, 8.36] \\ \midrule
R50 & 16.36 $\pm$ 0.72 & 8.16 $\pm$ 0.38 \\
& [14.68, 18.76] & [7.03, 9.10] \\ \bottomrule
\end{tabular}
}
\label{tab:app_fps}
\end{table}
\subsection{Training With A Shared Head}
Obtaining pseudo-labels using a shared head is a two-step process. First, we must train the shared head using latent sampling for a longer period of time than we would train an individual architecture. Second, we pair the shared head with an OFA body and fine-tune it to obtain a pseudo-label. We now describe the hyperparameter settings for both steps, for Detectron2 and HPE, respectively. We apply the same hyperparameter settings to bodies from all three OFA search spaces unless stated otherwise. Assume that the hyperparameters we do not mention here are the same as they are when training individual architectures. For details regarding the hyperparameter $N$, see the subsection `Latent Sampling Strategy'.
\subsubsection{Detectron2 Latent Sampling Head}
We set $N = 3$ and train the shared head for 250k steps, while reducing the learning rate at steps 166k and 220k. Detectron2 shared heads train on a single 32GB V100 GPU using a batch size of 8 for MobileNets and 5 for ResNets. Refer to the subsection on training individual architectures for all other hyperparameters. Between sampling bodies to calculate $\vec{\mu}(x)$ and $\vec{\sigma}(x)$ and performing inference, training a sampling shared head takes around 4-5 days.
\subsubsection{Detectron2 Pseudo-Label Fine-Tuning}
We fine-tune MobileNets for 750 steps, adjusting the learning rate at steps 465 and 635 with a batch size of 16. For ResNets, we increase the steps to 1k, adjust the learning rate at steps 620 and 850, but reduce the batch size to 12. We use 2 V100 GPUs with 32GB of VRAM when fine-tuning, which takes around 10 minutes for MobileNets and 12 for ResNets, although panoptic segmentation inference on COCO~\cite{coco} adds 5 minutes to pseudo-label an architecture.
\subsubsection{HPE Latent Sampling Head}
When training an HPE shared head, we can pre-compute $\vec{\mu}(x)$ and $\vec{\sigma}(x)$ for all images in the LSP training set and save them to disk as a cache. This greatly speeds up shared head training as a single epoch for LSP executes in around 30 seconds on any search space. Therefore, we set $N = 5$ and train a latent sampling shared head for 5k epochs with a batch size of 256. We adopt a cosine schedule~\cite{Loshchilov2017SGDRSG} to adjust the learning rate.
\subsubsection{HPE Pseudo-Label Fine-Tuning}
We fine-tune architectures for 10 epochs using a cosine annealing learning rate schedule. The entire process takes 10-12 minutes, depending on the body.
\begin{table*}
\centering
\caption{Summary of statistics for latent sampling shared head architectures across all three OFA families and CV tasks in terms of the number of architectures, task performance [\%], and resource metrics such as FLOPs [G] and parameters [M].
For all metrics, we report the mean and standard deviation on one line and the range on the second line.}
\scalebox{0.7}{
\begin{tabular}{l|c|c|c|c|c} \toprule
\textbf{Family} & \textbf{LSP HPE} & \textbf{Obj. Det.} & \textbf{Inst. Seg.} & \textbf{Sem. Seg.} & \textbf{Pan. Seg.} \\ \midrule \midrule
PN (\# Archs) & 2.6k & 1.6k & 1.6k & 1.6k & 1.6k \\ \midrule
Performance [\%] & 59.54 $\pm$ 1.06 & 23.86 $\pm$ 0.68 & 23.26 $\pm$ 0.63 & 31.39 $\pm$ 0.45 & 29.73 $\pm$ 0.58 \\
& [55.12, 62.68] & [20.68, 25.35] & [20.22, 24.66] & [29.65, 32.58] & [27.11, 31.03] \\ \midrule
FLOPs [G] & 15.74 $\pm$ 0.18 & 86.85 $\pm$ 1.16 & 125.53 $\pm$ 1.16 & 63.67 $\pm$ 1.16 & 174.05 $\pm$ 1.16 \\
& [15.20, 16.32] & [83.67, 90.57] & [122.35, 129.26] & [60.49, 67.39] & [170.87, 177.77] \\ \midrule
Params [M] & 12.56 $\pm$ 0.61 & 32.41 $\pm$ 0.61 & 20.75 $\pm$ 0.61 & 20.18 $\pm$ 0.61 & 37.72 $\pm$ 0.61 \\
& [11.13, 14.38] & [31.01, 34.18] & [19.34, 22.52] & [18.77, 21.95] & [36.31, 39.49] \\ \midrule
\midrule
MBv3 (\# Archs) & 2.9k & 1.3k & 1.3k & 1.3k & 1.3k \\ \midrule
Performance [\%] & 61.55 $\pm$ 1.01 & 24.25 $\pm$ 0.61 & 24.15 $\pm$ 0.58 & 30.89 $\pm$ 0.33 & 30.12 $\pm$ 0.50 \\
& [57.55, 63.79] & [21.92, 25.77] & [21.92, 25.63] & [29.59, 31.87] & [28.15, 31.44] \\ \midrule
FLOPs [G] & 14.37 $\pm$ 0.17 & 84.72 $\pm$ 1.09 & 123.40 $\pm$ 1.09 & 61.54 $\pm$ 1.09 & 171.85 $\pm$ 1.09 \\
& [13.87, 14.91] & [81.51, 88.16] & [120.19, 126.84] & [58.33, 64.98] & [168.64, 175.29] \\ \midrule
Params [M] & 10.23 $\pm$ 0.85 & 36.47 $\pm$ 0.83 & 24.80 $\pm$ 0.83 & 24.23 $\pm$ 0.83 & 41.77 $\pm$ 0.83 \\
& [8.22, 13.41] & [34.49, 39.62] & [22.83, 27.96] & [22.26, 27.38] & [39.80, 44.93] \\ \midrule
\midrule
R50 (\# Archs) & 3.0k & 1.4k & 1.4k & 1.4k & 1.4k \\ \midrule
Performance [\%] & 59.86 $\pm$ 2.57 & 24.72 $\pm$ 0.63 & 24.35 $\pm$ 0.60 & 30.43 $\pm$ 0.37 & 29.77 $\pm$ 0.52 \\
& [32.27, 62.68] & [22.50, 26.33] & [22.28, 25.85] & [29.19, 31.33] & [27.73, 31.11] \\ \midrule
FLOPs [G] & 21.98 $\pm$ 1.86 & 132.30 $\pm$ 10.65 & 170.99 $\pm$ 10.65 & 109.13 $\pm$ 10.65 & 219.50 $\pm$ 10.65 \\
& [17.31, 29.95] & [106.15, 181.14] & [144.83, 219.82] & [82.97, 157.96] & [193.35, 268.34] \\ \midrule
Params [M] & 25.91 $\pm$ 6.31 & 86.23 $\pm$ 5.81 & 74.56 $\pm$ 5.81 & 73.99 $\pm$ 5.81 & 91.53 $\pm$ 5.81 \\
& [13.40, 49.51] & [75.66, 108.80] & [64.00, 97.13] & [63.43, 96.56] & [80.97, 114.10] \\
\bottomrule
\end{tabular}
}
\label{tab:app_shared_head_architecture_description}
\end{table*}
\subsection{Task Head Descriptions}
Classification architectures progressively reduce the height and width of latent tensors as data passes from input to output. At the lowest resolution, the classification head will either perform a global max pooling operation or reshape the tensor to produce a long vector that can be fed into a linear layer, producing predictions $\mathbb{R}^C$ where $C$ is the number of classes. We remove the global pooling/reshaping layer and all subsequent layers to convert an IS network to perform other CV tasks.
We enumerate the task heads we use to train architectures in greater technical detail. First, we describe the upsampling head for HPE, before continuing with the heads for Detectron2 tasks. Table~\ref{tab:app_task_summary} summarizes the properties of each task, including the size of input images, performance metrics, datasets, and input resolutions to the task head.
\subsubsection{HPE Upsampling}
HPE takes an image as input and outputs a set of joint heatmaps where each heatmap represents the model's estimation of where a given joint resides in the image. We measure 2D HPE performance using Percentage of Correct Keypoints (PCK), specifically [email protected]. A joint prediction is correct if the distance between it and the ground truth is no more than half (@0.5) of the distance between the head (h) and neck joints in the same image.
After removing the global pooling and linear layer from an IC network,
we then append a series of deconvolution operations to the end of the network. These upsample the latent tensors to the desired resolution before a $1 \times 1$ convolution produces joint heatmaps with shape $\mathbb{R}^{J \times H_J \times W_J}$ where $J$ is the number of joints and $H_J$, $W_J$ (usually 64) are the heatmap height and width, respectively.
Compared to the standard IC benchmark ImageNet, which usually crops input images to $224 \times 224$ or less, the cropping for HPE images is slightly larger at $256 \times 256$.
\subsubsection{Feature Pyramid Networks}
We adopt Detectron2~\cite{wu2019detectron2} to implement
OD, IS, SS and PS.
In this framework, tasks build a top of each other, with sequential tasks borrowing modules from earlier ones. So we can
train one architecture on multiple tasks simultaneously and obtain distinct performance labels for each.
The first building block for all
Detectron2 task heads is the Feature Pyramid Network (FPN)~\cite{lin2017feature}. This module is similar to the upsampling HPE head with two exceptions. First, it produces no final output, so the $1 \times 1$ convolution for that joint heatmaps is removed. Second, the FPN connects to the base CNN architecture in several locations via multi-resolution skip-connections. Rather than only receiving the final latent representation of the
body with the smallest resolution, FPN receives a set of inputs with distinct resolutions from the intermediate depths of the body.
When we downsample an image or intermediate latent representation, we halve the height and width and usually increase the number of channels (the amount by which is search space-dependent).
Specifically, let $P^\mathcal{\ell}$ denote a latent representation that we downsample $\mathcal{\ell}$ times, e.g., $P^0$ is the input image size. If this is fed into convolution with a stride of 2, the output will be $P^1$, which has half the height and width.
FPN receives a set of input tensors $\{P^2, P^3, P^4, P^5\}$ from the body and produces an output set of tensors $\{C^2, C^3, C^4, C^5, C^6\}$. FPN computes $C^6$ by downsampling $P^5$ and applying a $1 \times 1$ convolution.
For all resolution levels, $C^j = f^{j}(P^j) + U^{j+1}(C^{j+1})$, where $f^j$ is a $1 \times 1$ convolution and $U^{j+1}$ is an upsampling operation; we use deconvolutions in our implementation. Finally, depending on the
search space, different $P^j$ will have a different number of channels (see Table~\ref{tab:app_family_channels}), whereas the FPN operations enforce a constant number of channels (e.g., $256$) for every $C^j$.
\subsubsection{Object Detection and Instance Segmentation}
OD and IS aim to detect a variable number of class instances (e.g., person, car, even hairdryer) in an image and either draw a bounding box or pixel mask for each instance, respectively.
We measure OD and IS performance in terms of mean Average Precision (AP); the ability of a network architecture to correct detect the number of bounding boxes/masks as well as draw and classify them.
We perform OD using a multi-resolution Faster R-CNN~\cite{ren2015faster},
which consists of a parameterized Region Proposal Network (RPN), Region of Interest (RoI) pooler, and bounding box estimator. The RPN acts as an attention mechanism, dividing the feature tensors into small grids and determining whether each unit in these grids are part of a bounding box or not.
The RoI modules pool the attention results for a given location in an image across different resolutions and passes this information onto the estimator, which predicts the coordinates and class of each bounding box.
Mask R-CNN~\cite{he2017mask} performs IS. It builds atop the Faster R-CNN framework, specifically the RPN, using a different set of
RoI poolers and deconvolutions
to predict pixel masks instead of bounding boxes.
\subsubsection{Semantic and Panoptic Segmentation}
The goal of SS~\cite{deeplabv3plus2018} is to classify every pixel in an image. We quantify SS performance using mean Intersection over Union (mIoU). Unlike OD and IS, the number of labels is known from the number of classes and size of the input image.
The SS task head is similar to that of HPE. Receiving the FPN features as input, it upsamples low-resolution features and predicts class mask predictions. We use deconvolution operations to upsample feature maps $\{C^3, C^4, C^5, C^6\}$ to the same size as $C^2$ and then use a weightless bilinear interpolation to further upsample to the original input size.
Finally, \cite{kirillov2019panoptic} define PS as the ``joint task'' of IS and SS. Like SS, PS predicts masks for each pixel in an image, but uses IS predictions to differentiate individual instances of a given class in an image, e.g., different colors for adjacent vehicles. That is, while SS would assign the same mask color to each person in a crowd of people, PS will assign different colors to each person. The PS performance metric is Panoptic Quality (PQ) which is a combination of IS class AP and SS mIoU.
\subsection{AIO-P Structure}
The backbone GNN for AIO-P consists of an embedding layer that converts node features (e.g., one-hot operation category vectors) into continuous vectors of length 32. The graph is fed into a series of 6 GNN~\cite{morris2019weisfeiler} layers, and a single graph embedding is calculated by taking the mean of all node features. Finally, an MLP regressor with 4 hidden layers and a size of 32 makes predictions.
When adding a $K$-Adapter to the backbone, we re-use the initial embedding layer to generate continuous node features. The $K$-Adapter uses the same kind of GNN layers as the backbone; just the input dimension is doubled to 64. Likewise, the input feature size to the MLP regressor also doubles, but the hidden size remains 32, and the $K$-Adapters also average node embeddings to create a single graph embedding.
If we train multiple $K$-Adapters sequentially, they do not interface with each other when learning, only with the original backbone. Freezing the backbone weights simplifies the training process by removing the order we train each $K$-Adapter from consideration. Finally, when using multiple $K$-Adapters, we perform inference on a downstream target task by taking the average of their predictions.
\subsubsection{Predictor Training}
We train the GNN backbone for 40 epochs on a 40k training partition of our NAS-Bench-101 CG data. We use an initial learning rate of $1e^{-4}$ and a batch size of 32. $K$-Adapters train on pseudo-labeled data for 100 epochs with the same learning rate.
\subsubsection{Fine-Tuning}
We fine-tune AIO-P with or without standardization on 20 random CGs\footnote{We use random seeds to ensure the set of 20 architectures is deterministic across different runs using the same seeds.} for 100 epochs with a batch size of 1. We unfreeze the backbone weights and instead freeze the weights of any $K$-Adapters.
If we substitute standardization for AdaProxy~\cite{lu2021one}, we only fine-tune the scaling weight $\alpha$ and sparsity vector $\vec{b}$. To attain competitive performance with AdaProxy, we fine-tune for 1000 epochs and set $\lambda = 1e^{-5}$.
\subsection{Latent Sampling Strategy}
To generate $\vec{\mu}(x)$ and $\vec{\sigma}(x)$ for an image $x$, we use a subset $\mathcal{S}'$ of bodies rather than the entire search space $\mathcal{S}$ as OFA search spaces contain around $10^{18}$ bodies each. Moreover, repeated inferences on many architectures are costly, placing practical limits on the size of $\mathcal{S}'$, so pure random sampling may not guarantee an unbiased distribution of architectures. Therefore, we select $\mathcal{S}'$ using a round robin strategy with length binning. The size and behavior of an OFA architecture are sensitive to length or the number of computational blocks it contains~\cite{mills2021profiling}. We bin architectures by the number of blocks they contain. For example, for MBv3, the number of blocks is in the range $[10, 20]$, and we divide this range into length bins $\mathcal{I}$ and sample $N$ architectures per bin so that $|\mathcal{S'}| = |\mathcal{I}|N$. Re-writing Equation~\ref{eq:math_mu} with this in mind, we obtain the following:
\begin{table}[t]
\centering
\caption{CV Tasks in terms of dataset, input image resolutions, latent feature resolution size between the base CNN and task head, and evaluation metric. We adopt Detectron2 notation
to refer to latent representation resolutions.}
\label{tab:app_task_summary}
\scalebox{0.73}{
\begin{threeparttable}
\begin{tabular}{c|c|c|c|c} \toprule
\textbf{Task} & \textbf{Dataset} & \textbf{Image} & \textbf{Head Input} & \textbf{Eval.} \\
& & \textbf{Resolution} & \textbf{Resolution} & \textbf{Metric} \\ \midrule
IC & ImageNet & $224^2$ & $P^5$ & Acc. \\ \midrule
HPE & MPII/LSP & $256^2$ & $P^5$ & PCK \\ \midrule
OD & & & \{$P^5$, & AP \\
IS & MS-COCO & $\sim1024^2$\tnote{$\dagger$} & $P^4$, & AP \\
SS & 2017 & & $P^3$, & mIoU \\
PS & & & $P^2$\} & PQ \\ \bottomrule
\end{tabular}
\begin{tablenotes}\footnotesize
\item{$\dagger$}Varies in aspect ratio and resolution from $640$ up to $1333$.
\end{tablenotes}
\end{threeparttable}
}
\end{table}
\begin{table}[t]
\centering
\caption{Number of channels at each resolution level across each OFA search space.
For PN and MBv3, one network stage does not perform downsampling, so we concatenate the output of that stage and the previous stage for $P^4$. For R50, the number of channels is not fixed. It is an adjustable, searchable parameter corresponding to channel multipliers $\{0.65, 0.8, 1.0\}$ per resolution level.}
\scalebox{0.73}{
\begin{tabular}{l|c|c|c|c} \toprule
\textbf{Family} & \textbf{$P^2$} & \textbf{$P^3$} &\textbf{$P^4$} & \textbf{$P^5$} \\ \midrule
PN & 32 & 56 & 104$+$128$=$232 & 1664 \\ \midrule
MBv3 & 32 & 48 & 96$+$136$=$232 & 1152 \\ \midrule
& \{168, & \{336, & \{664, & \{1328, \\
R50 & 208, & 408, & 816, & 1640 \\
& 256\} & 512\} & 1024\} & 2048\} \\ \bottomrule
\end{tabular}
}
\label{tab:app_family_channels}
\end{table}
\begin{equation}
\centering
\label{eq:code_mu}
\vec{\mu}(x) = \dfrac{1}{|\mathcal{I}|N}\sum_{i \in \mathcal{I}}\sum_{j = 0}^{N-1}f_{B_{i, j}}(x).
\end{equation}
Specifically, $\mathcal{I} = 5$ in our experiments. Therefore, the set of bins and their ranges for MBv3 and R50 are $\{[10, 11], [12, 13], [14, 16], [17, 18], [19, 20]\}$. For PN,
the block ranges are slightly different, e.g., $[11, 21]$,
so we shift the bin ranges accordingly.
When training a shared head, we cycle through the bins with every
minibatch and replace the oldest architecture in that bin. If the shared head requires multiple feature resolutions, e.g., FPN, we use the same architecture set to compute $\vec{\mu}(x)$ and $\vec{\sigma}(x)$ for each size, but sample using unique $\zeta$ at each scale.
\subsubsection{Preliminary ImageNet Experiment}
We perform a preliminary experiment to test the efficacy of the latent sampling concept. Specifically, we perform inference on the ImageNet validation set using this technique by sampling the final latent representation before the IC head, and feeding the result into the IC head of the largest body in the search space. Table~\ref{tab:app_sample_imagenet} lists the results, showing that our latent sampling approach can achieve top-1 accuracy performance comparable to what we observe evaluating individual networks.
\subsubsection{Additional Correlation Statistics}
Table~\ref{tab:sample_srcc} shows the performance distribution and SRCC when a set of architectures are individually trained and fine-tuned using a shared head. We repeat this routine for OD/IS/SS/PS using a latent sampling shared head to calculate the SRCC between pseudo-labels and the ground truth for Detectron2 tasks. We enumerate the results in Table~\ref{tab:app_sample_srcc}.
\subsubsection{Body Swapping}
We perform body swapping by changing the body feature extractor paired with the shared head 10 batches. We leverage the pre-trained OFA weights and only update the randomly initialized head weights when training the shared head.
\begin{table}[H]
\centering
\caption{Average ImageNet top-1 accuracy of a handful of randomly selected individual architectures with our latent sampling idea. We set $|\mathcal{B}| = N = 5$.}
\label{tab:app_sample_imagenet}
\scalebox{0.73}{
\begin{tabular}{l|c|c|c} \toprule
& \textbf{PN} & \textbf{MBv3} & \textbf{R50} \\ \midrule
Ind. Archs & 75.41\% & 76.94\% & 78.19\% \\
Sampling & 76.93\% & 77.68\% & 77.12\% \\ \bottomrule
\end{tabular}
}
\end{table}
\begin{table}[H]
\centering
\caption{SRCC values between individually trained architecture performance and when the same architectures are fine-tuned using a latent sampling shared head.}
\scalebox{0.73}{
\begin{tabular}{l|c|c|c} \toprule
\textbf{Task}& \textbf{PN} & \textbf{MBv3} & \textbf{R50} \\ \midrule
LSP-HPE & 0.659 & 0.576 & 0.375 \\
Obj. Det. & 0.622 & 0.570 & 0.501 \\
Inst. Seg. & 0.557 & 0.566 & 0.512 \\
Sem. Seg. & 0.520 & 0.310 & 0.244 \\
Pan. Seg. & 0.505 & 0.510 & 0.603 \\
\bottomrule
\end{tabular}
}
\label{tab:app_sample_srcc}
\end{table}
\subsubsection{ResNet50 Shared Head}
The main difference between a shared head and the head of an individually trained architecture is how we train them.
Structurally, they are identical, at least for PN and MBv3. However, this is not the case for R50, as the number of channels in a latent representation changes depending on the body's structure~\cite{mills2021profiling}. Table~\ref{tab:app_family_channels} lists the channel sizes for all three families. Because the number of channels in R50 is not fixed as it is for PN and MBv3, when designing a shared head for R50, we set the number of channels per resolution level to be the maximum possible, zero-pad tensors with fewer channels and then apply a 1 $\times$ 1 convolution prior to FPN processing.
\begin{table*}[ht!]
\centering
\caption{MAE [\%] of AIO-P on three search spaces and six tasks in the fine-tuning setting, compared to
GNN without and with rescaling by Eqs.~\ref{eq:standardization}, \ref{eq:accTrans}. AIO-P adopts 2 $K$-Adapters, trained on LSP and OD. AIO-P uses Equation~\ref{eq:accTrans} and standardize regression targets. Results averaged across 5 seeds. }
\scalebox{0.73}{
\begin{tabular}{l|ccc|ccc|ccc} \toprule
& & \textbf{ProxylessNAS} & & & \textbf{MobileNetV3} & & & \textbf{ResNet-50} & \\ \midrule
\textbf{Task} & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P \\ \midrule
LSP & 0.55 $\pm$ 0.39\% & 0.56 $\pm$ 0.04\%& \textbf{0.48}$\pm$ 0.02\% & 0.70 $\pm$ 0.14\% & 0.57$\pm$ 0.01\%& \textbf{0.52} $\pm$ 0.01\% & \textbf{0.81} $\pm$ 0.11\% & 0.93$\pm$ 0.05\% & 0.93 $\pm$ 0.05\% \\
MPII & 0.43 $\pm$ 0.22\% & 0.28 $\pm$ 0.02\%& \textbf{0.26}$\pm$ 0.02\% & 0.33 $\pm$ 0.03\% & 0.28$\pm$ 0.02\%& \textbf{0.26} $\pm$ 0.01\% & \textbf{0.28} $\pm$ 0.03\% & 1.11$\pm$ 0.53\% & 1.02 $\pm$ 0.07\% \\
OD & 0.90 $\pm$ 0.16\% & 0.74 $\pm$ 0.07\%& \textbf{0.53}$\pm$ 0.04\% & 0.69 $\pm$ 0.13\% & 0.78$\pm$ 0.05\%& \textbf{0.56} $\pm$ 0.08\% & 0.89 $\pm$ 0.19\% & 0.64$\pm$ 0.05\% & \textbf{0.50} $\pm$ 0.06\% \\
IS & 0.72 $\pm$ 0.15\% & 0.75 $\pm$ 0.09\%& \textbf{0.33}$\pm$ 0.03\% & 0.66 $\pm$ 0.25\% & 0.56$\pm$ 0.04\%& \textbf{0.40} $\pm$ 0.02\% & 0.61 $\pm$ 0.08\% & 0.54$\pm$ 0.03\% & \textbf{0.41} $\pm$ 0.05\% \\
SS & 0.68 $\pm$ 0.12\% & 0.58 $\pm$ 0.04\%& \textbf{0.33}$\pm$ 0.03\% & 0.93 $\pm$ 0.19\% & 0.61$\pm$ 0.06\%& \textbf{0.43} $\pm$ 0.03\% & 0.65 $\pm$ 0.21\% & 0.47$\pm$ 0.01\% & \textbf{0.43} $\pm$ 0.02\% \\
PS & 0.53 $\pm$ 1.00\% & 0.62 $\pm$ 0.04\%& \textbf{0.33}$\pm$ 0.04\% & 0.64 $\pm$ 0.17\% & 0.61$\pm$ 0.03\%& \textbf{0.43} $\pm$ 0.03\% & 0.71 $\pm$ 0.19\% & 0.43$\pm$ 0.04\% & \textbf{0.38} $\pm$ 0.04\% \\ \bottomrule
\end{tabular}
}
\label{tab:app_main_mae}
\end{table*}
\begin{table*}[ht!]
\centering
\caption{SRCC on AIO-P on three search spaces and size tasks.
Same configurations as Table~\ref{tab:app_main_mae}.}
\scalebox{0.73}{
\begin{tabular}{l|ccc|ccc|ccc} \toprule
& & \textbf{ProxylessNAS} & & & \textbf{MobileNetV3} & & & \textbf{ResNet-50} & \\ \midrule
\textbf{Task} & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P & GNN & +Eqs.~\ref{eq:standardization} \& \ref{eq:accTrans} & AIO-P \\ \midrule
LSP & 0.610 $\pm$ 0.018 & 0.583$\pm$ 0.068& \textbf{0.668}$\pm$ 0.034 & 0.449 $\pm$ 0.057 & 0.435$\pm$ 0.090& \textbf{0.567}$\pm$ 0.014 & \textbf{0.397} $\pm$ 0.196 & 0.314$\pm$ 0.059& 0.265$\pm$ 0.021 \\
MPII & 0.770 $\pm$ 0.017 & \textbf{0.803}$\pm$ 0.015& 0.773$\pm$ 0.019 & 0.680 $\pm$ 0.052 & 0.732$\pm$ 0.099& \textbf{0.744}$\pm$ 0.053 & \textbf{0.700} $\pm$ 0.072 & 0.531$\pm$ 0.071& 0.535$\pm$ 0.023 \\
OD & 0.304 $\pm$ 0.460 & 0.589$\pm$ 0.059& \textbf{0.800}$\pm$ 0.048 & 0.283 $\pm$ 0.395 & 0.374$\pm$ 0.126& \textbf{0.703}$\pm$ 0.058 & 0.526 $\pm$ 0.040 & 0.668$\pm$ 0.046& \textbf{0.871}$\pm$ 0.022 \\
IS & 0.277 $\pm$ 0.696 & 0.330$\pm$ 0.140& \textbf{0.894}$\pm$ 0.033 & 0.547 $\pm$ 0.151 & 0.505$\pm$ 0.083& \textbf{0.791}$\pm$ 0.028 & 0.611 $\pm$ 0.026 & 0.590$\pm$ 0.031& \textbf{0.881}$\pm$ 0.024 \\
SS & 0.195 $\pm$ 0.328 & 0.562$\pm$ 0.108& \textbf{0.849}$\pm$ 0.033 & 0.447 $\pm$ 0.140 & 0.653$\pm$ 0.061& \textbf{0.822}$\pm$ 0.028 & 0.552 $\pm$ 0.058 & 0.653$\pm$ 0.023& \textbf{0.677}$\pm$ 0.032 \\
PS & 0.741 $\pm$ 0.043 & 0.297$\pm$ 0.083& \textbf{0.868}$\pm$ 0.036 & 0.568 $\pm$ 0.147 & 0.373$\pm$ 0.032& \textbf{0.786}$\pm$ 0.046 & 0.601 $\pm$ 0.092 & 0.696$\pm$ 0.067& \textbf{0.858}$\pm$ 0.031 \\ \bottomrule
\end{tabular}
}
\label{tab:app_main_srcc}
\end{table*}
\subsection{Computational Graph Structure}
In a CG, each node is an irreducible primitive operation, e.g., tensor operations like mean and concat, weighted layers like convolutions and linear layers, activation functions like ReLU or even upsampling operations. This is in contrast to the pre-defined operation `bundles', e.g., the `Nor\_Conv' operations of NAS-Bench-201~\cite{dong2020nasbench201}, itself a proxy for the sequence `ReLU-Convolution-BatchNorm' which a CG would represent as a subgraph of 3 nodes and 2 directed edges. Node features include the height-width and channel dimensions of the input and output latent tensors, a feature for weight tensor dimensions if applicable (e.g., for convolutions, but not for ReLU), a Boolean on whether bias is enabled, and a one-hot category for the operation type.
\subsection{Additional Results}
Tables~\ref{tab:app_main_mae} and \ref{tab:app_main_srcc} compare AIO-P to the backbone GNN with and without Equations~\ref{eq:standardization} and \ref{eq:accTrans}, this time in the fine-tuning context (whereas before, Tables~\ref{tab:main_mae} and \ref{tab:main_srcc} only consider the zero-shot transfer). AIO-P now achieves the best MAE performance on the PN and MBv3 search spaces and the best SRCC on MBv3. While the GNN can attain high metrics for LSP and MPII in the R50 search space, these are limited results. It cannot generalize that performance to other tasks and search spaces, and the tasks it does well on are also tasks with high PCK ranges similar to classification accuracy, as Table~\ref{tab:app_full_architecture_description} shows.
\subsection{Hardware and Software Details}
Our experimental servers have 8 NVIDIA Tesla V100 GPUs with 32GB of VRAM per card coupled with an Intel Xeon Gold 6140 GPU and 756GB of RAM. Each server runs Ubuntu 20.04.4 LTS.
We create Compute Graphs using models from \texttt{TensorFlow==1.15.0}, specifically, replicating \texttt{PyTorch} models with the \texttt{Keras} API if necessary.
We train architectures using \texttt{PyTorch==1.8.1} and \texttt{Detectron2==0.6} where applicable and use \texttt{PyTorch-Geometric} to train GNNs. | {'timestamp': '2022-12-01T02:21:03', 'yymm': '2211', 'arxiv_id': '2211.17228', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17228'} | arxiv |
\section{Introduction}
Recently, GNNs~\citep{Gil+2017,Sca+2009} emerged as the most prominent graph representation learning architecture. Notable instances of this architecture include, e.g.,~\citet{Duv+2015,Ham+2017}, and~\citet{Vel+2018}, which can be subsumed under the message-passing framework introduced in~\citet{Gil+2017}. In parallel, approaches based on spectral information were introduced in, e.g.,~\citet{Defferrard2016,Bru+2014,Kip+2017}, and~\citet{Mon+2017}---all of which descend from early work in~\citet{bas+1997,Kir+1995,mic+2005,Mer+2005,mic+2009,Sca+2009} and~\citet{Spe+1997}.
By now, we have a deep understanding of the expressive power of GNNs~\citep{Mor+2021b}. To start with, connections between GNNs and Weisfeiler--Leman type algorithms have been shown. Specifically,~\citet{Mor+2019} and~\citet{Xu+2018b} showed that the $$1$\text{-}\textsf{WL}$ limits the expressive power of any possible GNN architecture in terms of distinguishing non-isomorphic graphs. In turn, these results have been generalized to the $k$\text{-}\textsf{WL}, see, e.g.,~\citet{Azi+2020,Gee+2020a,Gee+2020b,Mar+2019,Mor+2019,Morris2020b,Mor+2022b}, and connected to permutation-equivariant function approximation over graphs, see, e.g.,~\citet{Che+2019,geerts2022,Mae+2019}. \citet{barcelo2020} further established an equivalence between the expressiveness of GNNs with readout functions and $\textsf{C}^2$, the $2$-variable fragment of first-order logic with counting quantifiers.
Most previous works focus on graphs that admit labels on vertices but not edges. However, \new{knowledge} or \new{multi-relational graphs}, that admit
labels on both vertices and edges play a crucial role in numerous applications, such as complex question answering in NLP~\citep{fu2020survey} or visual question answering~\citep{huang2022endowing} in the intersection of NLP and vision. To extract the rich information encoded in the graph's multi-relational structure and its annotations, the knowledge graph community has proposed a large set of \new{relational} GNN architectures, e.g.,~\cite{Sch+2019,Vas+2020,Ye+2022}, tailored towards knowledge or multi-relational graphs, targeting tasks such as vertex and link prediction~\citep{Sch+2019,Zhu+2021,Ye+2022}.
Notably, \citet{Sch+2019} proposed the first architecture, namely, \textsf{R\text{-}GCN}, being able to handle multi-relational data. Further, \citet{Vas+2020} proposed an alternative GNN architecture, \textsf{CompGCN}\xspace, using less number of parameters and reported improved empirical performance. In the knowledge graph reasoning area, \textsf{R\text{-}GCN}{} and \textsf{CompGCN}\xspace, being strong baselines, spun off numerous improved GNNs for vertex classification and transductive link prediction tasks~\citep{galkin2020message,yu2020generalized,compgcn_random_proj}. They also inspired architectures for more complex reasoning tasks such as inductive link prediction~\citep{teru2020inductive,ali2021improving,Zhu+2021,zhang2022knowledge} and query answering~\citep{daza2020message,starqe,gnn_qe}.
Although these approaches show meaningful empirical performance, their limitations in extracting relevant structural information, their learning performance, and their relation to each other are not understood well. For example, there is no understanding of these approaches' inherent limitations in distinguishing between knowledge graphs with different structural features, explicitly considering the unique properties of multi-relational graphs. Hence, a thorough theoretical investigation of multi-relational GNNs' expressive power and learning performance is yet to be established to become meaningful, vital components in today's knowledge graph reasoning pipeline.
\paragraph{Present Work.} Here, we initiate the study on deriving a principled understanding of the capabilities of GNNs for knowledge or multi-relational graphs. More concretely:
\begin{itemize}
\item We investigate the expressive power of two well-known GNNs for multi-relation data, \new{Relational GCNs} (\textsf{R\text{-}GCN})~\citep{Sch+2019} and \new{Compositional GCNs} (\textsf{CompGCN}\xspace)~\citep{Vas+2020}. We quantify their limitations by relating them to a suitable version of the established Weisfeiler-Leman graph isomorphism test. In particular, we show under which conditions the above two architectures possess the same expressive power in distinguishing non-isomorphic, multi-relational graphs or vertices with different structural features.
\item To overcome both architectures' expressiveness limitations, we introduce the \krn{k} architecture, which provably overcomes their limitations and show that increasing $k$ always leads to strictly more expressive architectures.
\item Empirically, we confirm our theoretical findings on established small- and large-scale multi-relational vertex classification benchmarks.
\end{itemize}
See Subsection~\ref{related_work} in the appendix for an expanded discussion of related work.
\section{Preliminaries}
As usual, let $[n] = \{ 1, \dotsc, n \} \subset \mathbb{N}$ for $n \geq 1$, and let $\{\!\!\{ \dots\}\!\!\}$ denote a multiset.
A \new{(undirected) graph} $G$ is a pair $(V(G),E(G))$ with a \emph{finite} set of
\new{vertices} $V(G)$ and a set of \new{edges} $E(G) \subseteq \{ \{u,v\}
\subseteq V \mid u \neq v \}$.
For notational convenience, we usually denote an edge $\{u,v\}$ in $E(G)$ by $(u,v)$ or $(v,u)$.
We assume the usual definition of \new{adjacency matrix} $\bm{A}$ of $G$. A \new{colored} or \new{labeled graph} $G$ is a triple $(V(G),E(G),\ell)$ with a \new{coloring} or \new{label} function $\ell \colon V(G) \to \ensuremath{\mathbb{N}}$. Then $\ell(w)$ is a \new{color} or \new{label} of $w$, for $w$ in $V(G)$. The \new{neighborhood} of $v$ in $V(G)$ is denoted by $N(v) = \{ u \in V(G) \mid (v, u) \in E(G) \}$.
An \new{(undirected) multi-relational graph} $G$ is a tuple $(V(G),R_1(G), \dots, R_r(G))$ with a \emph{finite} set of
\new{vertices} $V(G)$ and \new{relations} $R_i \subseteq \{ \{u,v\} \subseteq V(G) \mid u \neq v \}$ for $i$ in $[r]$. The \new{neighborhood} of $v$ in $V(G)$ with respect to the relation $R_i$ is denoted by $N_i(v) = \{ u \in V(G) \mid (v, u) \in R_i \}$. We define \new{colored} (or \new{labeled})
multi-relational graphs in the expected way.
Two graphs $G$ and $H$ are \new{isomorphic} ($G \simeq H$) if there exists a bijection $\varphi \colon V(G) \to V(H)$ preserving the adjacency relation, i.e., $(u,v)$ in $E(G)$ if and only if $(\varphi(u),\varphi(v))$ in $E(H)$. We then call $\varphi$ an \emph{isomorphism} from $G$ to $H$. If the graphs have vertex labels, the isomorphism is additionally required to match these labels. In the case of multi-relational graphs $G$ and $H$, the bijection $\varphi \colon V(G) \to V(H)$ needs to preserve all relations, i.e., $(u,v)$ is in $R_i(G)$ if and only if $(\varphi(u),\varphi(v))$ is in $R_i(H)$ for each $i$ in $[r]$. For labeled multi-relational graphs, the bijection needs to preserve the labels.
We define the atomic type $\mathsf{atp} \colon V(G)^k \to \ensuremath{\mathbb{N}}$ such that $\mathsf{atp}(\vec{v}) = \mathsf{atp}(\vec{w})$ for $\vec{v}$ and $\vec{w}$ in $V(G)^k$ if and only if the mapping $\varphi\colon V(G) \to V(G)$ where $v_i \mapsto w_i$ induces a \emph{partial isomorphism}, i.e., $v_i = v_j \iff w_i = w_j$ and $(v_i,v_j)$ in $E(G) \iff (\varphi(v_i),\varphi(v_j))$ in $E(G)$.
\paragraph{The Weisfeiler-Leman Algorithm.}\label{vr_ext}
The \new{$1$-dimensional Weisfeiler-Leman algorithm} ($1$\text{-}\textsf{WL}), or \new{color refinement}, is a simple heuristic for the graph isomorphism problem, originally proposed by~\citet{Wei+1968}.\footnote{Strictly speaking, $1$\text{-}\textsf{WL}\ and color refinement are two different algorithms. That is, $1$\text{-}\textsf{WL}\ considers neighbors and non-neighbors to update the coloring, resulting in a slightly higher expressive power when distinguishing vertices in a given graph, see~\citet{Gro+2021} for details. For brevity, we consider both algorithms to be equivalent.}\footnote{
We use the spelling ``Leman'' here as A.~Leman, co-inventor of the algorithm, preferred it over the transcription ``Lehman''; see
\url{https://www.iti.zcu.cz/wl2018/pdf/leman.pdf}.}
Intuitively, the algorithm determines if two graphs are non-isomorphic by iteratively coloring or labeling vertices. Given an initial coloring or labeling of the vertices of both
graphs, e.g., their degree or application-specific information, in each iteration, two vertices with the same label get different labels if the number of identically labeled neighbors is not equal. If, after some iteration, the number of vertices annotated with a specific label is different in both graphs, the algorithm terminates and a stable coloring, inducing a vertex partition, is obtained. We can then conclude that the two graphs are not isomorphic. It is easy to see that the algorithm cannot distinguish all non-isomorphic graphs~\citep{Cai+1992}. Nonetheless, it is a powerful heuristic that can successfully test isomorphism for a broad class of graphs~\citep{Arv+2015,Bab+1979,Kie+2015}.
Formally, let $G = (V(G),E(G),\ell)$ be a labeled graph. In each iteration, $t > 0$, the $$1$\text{-}\textsf{WL}$ computes a vertex coloring $C^{(t)} \colon V(G) \to \ensuremath{\mathbb{N}}$,
which depends on the coloring of the neighbors. That is, in iteration $t>0$, we set
\begin{equation*}
C^{(t)}(v) \coloneqq \mathsf{RELABEL}\Big(\!\big(C^{(t-1)}(v),\{\!\!\{ C^{(t-1)}(u) \mid u \in N(v) \}\!\!\} \big)\! \Big),
\end{equation*}
where $\mathsf{RELABEL}$ injectively maps the above pair to a unique natural number, which has not been used in previous iterations. In iteration $0$, the coloring $C^{(0)}\coloneqq \ell$. To test if two graphs $G$ and $H$ are non-isomorphic, we run the above algorithm in ``parallel'' on both graphs. If the two graphs have a different number of vertices colored $c$ in $\ensuremath{\mathbb{N}}$ at some iteration, the $1$\text{-}\textsf{WL}{} \new{distinguishes} the graphs as non-isomorphic. Moreover, if the number of colors between two iterations, $t$ and $(t+1)$, does not change, i.e., the cardinalities of the images of $C^{(t)}$ and $C^{(t+1)}$ are equal, or, equivalently,
\begin{equation*}
C^{(t)}(v) = C^{(t)}(w) \iff C^{(t+1)}(v) = C^{(t+1)}(w),
\end{equation*}
for all vertices $v$ and $w$ in $V(G)$, the algorithm terminates. For such $t$, we define the \new{stable coloring}
$C^{\infty}(v) = C^{(t)}(v)$ for $v$ in $V(G)$. The stable coloring is reached after at most $\max \{ |V(G)|,|V(H)| \}$ iterations~\citep{Gro2017}.
Due to the shortcomings of the $$1$\text{-}\textsf{WL}$ in distinguishing non-isomorphic graphs, several researchers, e.g.,~\citep{Bab1979,Cai1992}, devised a more powerful generalization of the former, today known as the $k$-dimensional Weisfeiler-Leman algorithm ($k$\text{-}\textsf{WL}), see Subsection~\ref{APP:vr_ext} for details.
\paragraph{Graph Neural Networks.}\label{sec:gnn} Intuitively, GNNs learn a vectorial representation, i.e., a $d$-dimensional vector, representing each vertex in a graph by aggregating information from neighboring vertices. Formally, let $G = (V(G),E(G),\ell)$ be a labeled graph with initial vertex features $(\bm{h}_{v}^\tup{0})_{v\in V(G)}$ in $\mathbb{R}^{d}$ that are \emph{consistent} with $\ell$, that is, $\bm{h}_{u}^\tup{0} = \bm{h}_{v}^\tup{0}$ if and only if $\ell(u) = \ell(v)$, e.g., a one-hot encoding of the labelling $\ell$. Alternatively, $(\bm{h}_{v}^\tup{0})_{v\in V(G)}$ can be arbitrary vertex features annotating the vertices of $G$.
A GNN architecture consists of a stack of neural network layers, i.e., a composition of permutation-invariant or -equivariant parameterized functions. Similarly to $1$\text{-}\textsf{WL}, each layer aggregates local neighborhood information, i.e., the neighbors' features, around each vertex and then passes this aggregated information on to the next layer.
GNNs are often realized as follows~\citep{Mor+2019}. In each layer, $t > 0$, we compute vertex features
\begin{equation}\label{eq:basicgnn}
\bm{h}_{v}^\tup{t} \coloneqq \sigma \Big( \bm{h}_{v}^\tup{t-1} \bm{W}^{(t)}_0 + \sum_{{w \in N(v)}} \bm{h}_{w}^\tup{t-1} \bm{W}_1^{(t)} \Big) \in \ensuremath{\mathbb{R}}^{e},
\end{equation}
for $v$ in $V(G)$, where
$\bm{W}_0^{(t)}$ and $\bm{W}_1^{(t)}$ are parameter matrices from $\ensuremath{\mathbb{R}}^{d \times e}$ and $\sigma$ denotes an entry-wise non-linear function, e.g., a sigmoid or a ReLU function.\footnote{For clarity of presentation, we omit biases.} Following \citet{Gil+2017} and \citet{Sca+2009}, in each layer, $t > 0$, we can generalize the above by computing a vertex feature
\begin{equation*}\label{def:gnn}
\bm{h}_{v}^\tup{t} \coloneqq
\mathsf{UPD}^\tup{t}\Bigl(\bm{h}_{v}^\tup{t-1},\mathsf{AGG}^\tup{t} \bigl(\{\!\!\{ \bm{h}_{w}^\tup{t-1}
\mid w\in N(v) \}\!\!\} \bigr)\Bigr),
\end{equation*}
where $\mathsf{UPD}^\tup{t}$ and $\mathsf{AGG}^\tup{t}$ may be differentiable parameterized functions, e.g., neural networks.\footnote{Strictly speaking, \citet{Gil+2017} consider a slightly more general setting in which vertex features are computed by $\bm{h}_{v}^\tup{t+1} \coloneqq
\mathsf{UPD}^\tup{t+1}\Bigl(\bm{h}_{v}^\tup{t},\mathsf{AGG}^\tup{t+1} \bigl(\{\!\!\{ (\bm{h}_v^\tup{t},\bm{h}_{w}^\tup{t},\ell(v,w))
\mid w\in N(v) \}\!\!\} \bigr)\Bigr)$.}
In the case of graph-level tasks, e.g., graph classification, one uses
\begin{equation*}\label{readout}
\bm{h}_G \coloneqq \mathsf{READOUT}\bigl( \{\!\!\{ \bm{h}_{v}^{\tup{T}}\mid v\in V(G) \}\!\!\} \bigr),
\end{equation*}
to compute a single vectorial representation based on learned vertex features after iteration $T$. Again, $\mathsf{READOUT}$ may be a differentiable parameterized function. To adapt the parameters of the above three functions, they are optimized end-to-end, usually through a variant of stochastic gradient descent, e.g.,~\citep{Kin+2015}, together with the parameters of a neural network used for classification or regression.
\paragraph{Graph Neural Networks for Multi-relational Graphs.}
In the following, we describe GNN layers for multi-relational graphs, namely \textsf{R\text{-}GCN}{}~\citep{Sch+2019} and \textsf{CompGCN}\xspace{}~\citep{Vas+2020}. Initial features are computed in the same way as in the previous subsection.
\paragraph{\textsf{R\text{-}GCN}} Let $G$ be a labeled
multi-relational graph. In essence, \textsf{R\text{-}GCN}\ generalizes Equation~\ref{eq:basicgnn} by using an additional sum iterating over the different relations. That is, we compute a vertex feature
\begin{align}\label{eq:rgcn}
\bm{h}_{v, \textsf{R\text{-}GCN}}^\tup{t} \coloneqq \sigma \Big( \bm{h}_{v, \textsf{R\text{-}GCN}}^\tup{t-1} \bm{W}^{(t)}_0 + \sum_{i \in [r]} \sum_{{w \in N_i(v)}}\! \bm{h}_{w,\textsf{R\text{-}GCN}}^\tup{t-1} \bm{W}_i^{(t)} \Big) \in \mathbb{R}^{e},
\end{align}
for $v$ in $V(G)$, where $\bm{W}_0^{(t)}$ and $\bm{W}_i^{(t)}$ for $i$ in $[r]$ are parameter matrices from $\ensuremath{\mathbb{R}}^{d \times e}$, and $\sigma$ denotes a entry-wise non-linear function. We note here that the original \textsf{R\text{-}GCN}{} layer defined in~\cite{Sch+2019} uses a mean operation instead of a sum in the most inner sum of Equation~\ref{eq:rgcn}. We investigate the empirical advantages of these two variations in Section~\ref{sec:experiments}.
\paragraph{\textsf{CompGCN}} Let $G$ be a labeled
multi-relational graph. A \textsf{CompGCN}\xspace layer generalizes~ Equation~\ref{eq:basicgnn} by encoding relational information as edge features. That is, we compute a vertex feature
\begin{align}\label{eq:comp}
\bm{h}_{v, \textsf{CompGCN}\xspace}^\tup{t} \coloneqq \sigma \Big(\bm{h}_{v, \textsf{CompGCN}\xspace}^\tup{t-1} \bm{W}^{(t)}_0 +
\sum_{i \in [r]} \sum_{w \in N_i(v)} \phi \big(\bm{h}_{w, \textsf{CompGCN}\xspace}^\tup{t-1}, \bm{z}_i^{(t)} \big) \bm{W}_1^{(t)} \Big)\in \mathbb{R}^{e},
\end{align}
for $v$ in $V(G)$, where $\bm{W}_0^{(t)}$ and $\bm{W}_1^{(t)}$ are parameter matrices from $\ensuremath{\mathbb{R}}^{d \times e}$ and $\ensuremath{\mathbb{R}}^{c \times e}$, respectively, and $\bm{z}_i^{(t)}$ in $\ensuremath{\mathbb{R}}^{b}$ is the learned edge feature for the $i$th relation at layer $t$. Further, the function $\phi \colon \ensuremath{\mathbb{R}}^d \times \ensuremath{\mathbb{R}}^b \to \ensuremath{\mathbb{R}}^c$
is a \new{composition map}, mapping two vectors onto a single vector in a non-parametric way, e.g., summation, point-wise multiplication, or concatenation. We note here that the original \textsf{CompGCN}\xspace layer defined in~\cite{Vas+2020} uses an additional sum to differentiate between in-going and out-going edges and self loops, see Section~\ref{APP:comp} for details.
\section{Relational Weisfeiler--Leman Algorithm}\label{sec:multi-wl}
In the following, to study the limitations in expressivity of the above two GNN layers, \textsf{R\text{-}GCN}\ and \textsf{CompGCN}\xspace, we define the \new{multi-relational $1$\text{-}\textsf{WL}} ($1$\text{-}\textsf{RWL}). Let $G=(V(G),R_1(G),\dots, R_r(G),\ell)$ be a labeled, multi-relational graph. Then the $1$\text{-}\textsf{RWL}{} computes a vertex coloring $C^{(t)}_{\textsf{R}} \colon V(G) \to \ensuremath{\mathbb{N}}$ for $t > 0$ by interpreting the different relations as edge types, i.e.,
\begin{align}\label{wlscomp}
C^{(t)}_{\textsf{R}}(v) \coloneqq \mathsf{RELABEL} \Big(\!\big(C^{(t-1)}_{\textsf{R}}(v), \{\!\!\{ (C^{(t-1)}_{\textsf{R}}(u), i) \mid i \in [r], u \in\!N_i(v) \}\!\!\} \big)\! \Big),
\end{align}
for $v$ in $V(G)$.
In iteration $0$, the coloring $C^{(0)}_{\textsf{R}} \coloneqq \ell$.
In particular, two vertices $v$ and $w$ of the same color in iteration $(t-1)$ get different colors in iteration $t$ if there is a relation $R_i$ such that the number of neighbors in $N_i(v)$ and $N_i(w)$ colored with a certain color is different. We define the stable coloring $C^{\infty}_{\textsf{R}}$ in the expected way, analogously to the $1$\text{-}\textsf{WL}.
\paragraph{Relationship Between $1$\text{-}\textsf{WL}{} and $1$\text{-}\textsf{RWL}} Since $1$\text{-}\textsf{WL}{} does not consider edge labels it is clear that $1$\text{-}\textsf{RWL}{} is strictly stronger than the $1$\text{-}\textsf{WL}{}. For example, take a pair of isomorphic graphs and label the edges differently in each graphs, making the graph non-isomorphic. Clearly, $1$\text{-}\textsf{RWL}{} will distinguish them while $1$\text{-}\textsf{WL}{} will not.
\paragraph{Relationship Between $1$\text{-}\textsf{RWL}, \textsf{R\text{-}GCN}, and \textsf{CompGCN}\xspace\!\!}
\citet{Mor+2019,Xu+2018b} established the exact relationship between the expressive power of $1$\text{-}\textsf{WL}{} and GNNs.
In particular, $1$\text{-}\textsf{WL}{} upper bounds the capacity of any GNN architecture for distinguishing vertices in graphs. In turn,
over every graph $G$ there is a GNN architecture with the same expressive power as $$1$\text{-}\textsf{WL}$ for distinguishing vertices in $G$. In this section, we show that the same relationship can be established between multi-relational $$1$\text{-}\textsf{WL}$, on the one hand, and the \textsf{R\text{-}GCN}\ and \textsf{CompGCN}\xspace architectures, on the other.
Let $G=(V(G),R_1(G), \dots, R_r(G),\ell)$ be a labeled, multi-relational graph, and let $$\mathbf{W}_\textsf{R\text{-}GCN}^\tup{t} \ = \ \big(\bm{W}^{(t')}_0, \bm{W}^{(t')}_{i} \big)_{t'\leq t, i \in [r]}$$
denote the sequence of \textsf{R\text{-}GCN}\ parameters given by Equation~\ref{eq:rgcn} up to iteration $t$.
Analogously, we denote by $$\mathbf{W}_\textsf{CompGCN}\xspace^\tup{t} \ = \ (\bm{W}^{(t')}_0, \bm{W}^{(t')}_{1},\bm{z}_i^{(t')})_{t'\leq t, i \in [r]}$$ the sequence of
\textsf{CompGCN}\xspace parameters given by Equation~\ref{eq:comp} up to iteration $t$. We first show that the multi-relational $1$\text{-}\textsf{WL}{} upper bounds the expressivity of both the \textsf{R\text{-}GCN}{} and \textsf{CompGCN}\xspace{} layers in terms of their capacity to distinguish vertices in labeled
multi-relational graphs.
\medskip
\begin{theorem}
\label{thm:mrgcn-upper}
{\em Let $G = (V(G), R_1(G), \dots, R_r(G), \ell)$ be a labeled, multi-relational graph. Then for all $t \geq 0$ the following holds:
\begin{itemize}
\item For all choices of initial vertex features consistent with $\ell$, sequences $\mathbf{W}_\textsf{R\text{-}GCN}^{(t)}$ of \textsf{R\text{-}GCN}\ parameters,
and vertices $v$ and $w$ in $V(G)$,
\begin{equation*}
C^{(t)}_{\textsf{R}}(v) = C^{(t)}_{\textsf{R}}(w) \ \ \Longrightarrow \ \ \bm{h}_{v, \textsf{R\text{-}GCN}}^\tup{t} = \bm{h}_{w, \textsf{R\text{-}GCN}}^\tup{t}.
\end{equation*}
\item For all choices of initial vertex features consistent with $\ell$, sequences $\mathbf{W}_\textsf{CompGCN}\xspace^{(t)}$ of \textsf{CompGCN}\xspace
parameters,
composition functions $\phi$, and vertices $v$ and $w$ in $V(G)$,
\begin{equation*}
C^{(t)}_{\textsf{R}}(v) = C^{(t)}_{\textsf{R}}(w) \ \ \Longrightarrow \ \ \bm{h}_{v, \textsf{CompGCN}\xspace}^\tup{t} = \bm{h}_{w, \textsf{CompGCN}\xspace}^\tup{t}.
\end{equation*}
\end{itemize} }
\end{theorem}
Noticeably, the converse also holds. That is, there is a sequence of parameter matrices $\mathbf{W}_\textsf{R\text{-}GCN}^{(t)}$ such that \textsf{R\text{-}GCN}\ has the same expressive power in terms of distinguishing vertices in graphs as the coloring $C^{(t)}_{\textsf{R}}$. This equivalence holds provided the initial labels are encoded by linearly independent vertex features, e.g., using one-hot encodings. The result also holds for \textsf{CompGCN}\xspace as long as the composition map $\phi$ can express vector scaling, e.g., $\phi$ is point-wise multiplication or circular correlation, two of the composition functions studied and implemented in the paper that introduced the \textsf{CompGCN}\xspace architecture \citep{Vas+2020}.
\medskip
\begin{theorem}\label{thm:mrgcn-lower}
{\em Let $G=(V(G), R_1(G), \dots, R_r(G), \ell)$ be a labeled, multi-relational graph. Then for all $t \geq 0$ the following holds:
\begin{itemize}
\item
There are initial vertex features and a sequence $\mathbf{W}_\textsf{R\text{-}GCN}^{(t)}$ of parameters such that for all $v$ and $w$ in $V(G)$,
\begin{equation*}
C^{(t)}_{\textsf{R}}(v) = C^{(t)}_{\textsf{R}}(w) \ \ \Longleftrightarrow \ \ \bm{h}_{v, \textsf{R\text{-}GCN}}^\tup{t} = \bm{h}_{w, \textsf{R\text{-}GCN}}^\tup{t}.
\end{equation*}
\item
There are initial vertex features, a sequence $\mathbf{W}_\textsf{CompGCN}\xspace^{(t)}$ of parameters
and a composition function $\phi$ such that for all $v$ and $w$ in $V(G)$,
\begin{equation*}
C^{(t)}_{\textsf{R}}(v) = C^{(t)}_{\textsf{R}}(w) \ \ \Longleftrightarrow \ \ \bm{h}_{v, \textsf{CompGCN}\xspace}^\tup{t} = \bm{h}_{w, \textsf{CompGCN}\xspace}^\tup{t}.
\end{equation*}
\end{itemize} }
\end{theorem}
\paragraph{On the Choice of the Composition Function for \textsf{CompGCN}\xspace{} Architectures}
As Theorem~\ref{thm:mrgcn-lower} shows the expressive power of the $$1$\text{-}\textsf{RWL}$ is matched by that of the \textsf{CompGCN}\xspace\ architectures if we allow the latter to implement vector scaling in composition functions.
However, not all composition maps that have been considered in relationship with \textsf{CompGCN}\xspace\ architectures admit such a possibility.
Think, for instance, of natural composition maps such as point-wise summation or vector concatenation. Interestingly, we can show that \textsf{CompGCN}\xspace\ architectures equipped with these composition maps are provably weaker in terms of expressive power than the ones studied in the proof of Theorem~\ref{thm:mrgcn-lower}, as they correlate with a weaker variant of $$1$\text{-}\textsf{WL}$ that we define next.
Let $G=(V(G),R_1(G),\dots, R_r(G),\ell)$ be a labeled, multi-relational graph. The \emph{weak multi-relational $1$\text{-}\textsf{WL}} computes a vertex coloring $C^{(t)}_{\textsf{WR}} \colon V(G) \to \ensuremath{\mathbb{N}}$ for $t > 0$ as follows:
\begin{equation*}\label{eq:weak-wlscomp}
C^{(t)}_{\textsf{WR}}(v) \coloneqq \mathsf{RELABEL} \Big(\!\big(C^{(t-1)}_{\textsf{WR}}(v), \{\!\!\{ C^{(t-1)}_{\textsf{WR}}(u) \mid i \in [r], u \in\! N_i(v)\}\!\!\}, |N_1(v)|, \dots, |N_r(v)| \big)\! \Big),
\end{equation*}
for $v$ in $V(G)$. In iteration $0$, the coloring $C^{(0)}_{\textsf{WR}} \coloneqq \ell$. During aggregation, the weak variant does not take information about the relations into account. The only information relative to the different relations is the number of neighbors associated with each of them. We define the stable coloring $C^{\infty}_{\textsf{WR}}$ analogously to the $1$\text{-}\textsf{WL}. As it turns out, this variant is less powerful than the original one.
\medskip
\begin{proposition}
\label{prop:weak-wl-sep}
{\em
There exist a labeled, multi-relational graph $G=(V(G),R_1(G),R_2(G),\ell)$ and two vertices $v$ and $w$ in $V(G)$, such that $C^{(1)}_{\textsf{R}}(v)\neq C^{(1)}_{\textsf{R}}(w)$ but $C^{\infty}_{\textsf{WR}}(v) = C^{\infty}_{\textsf{WR}}(w)$.
}
\end{proposition}
As shown next, the expressive power of \textsf{CompGCN}\xspace\ architectures that use point-wise summation
or vector concatenation is captured by this
weaker form of $1$\text{-}\textsf{RWL}.
\medskip
\begin{theorem}\label{thm:weak-comp-wl}
{\em
Let $G = (V(G), R_1(G), \dots, R_r(G), \ell)$ be a labeled, multi-relational graph. Then for all $t \geq 0$ the following holds:
\begin{itemize}
\item For all choices of initial vertex features consistent with $\ell$,
sequences $\mathbf{W}_\textsf{CompGCN}\xspace^{(t)}$ of \textsf{CompGCN}\xspace\ parameters, and vertices
$v$ and $w$ in $V(G)$,
\begin{equation*}
C^{(t)}_{\textsf{WR}}(v) = C^{(t)}_{\textsf{WR}}(w) \ \ \Longrightarrow \ \ \bm{h}_{v, \textsf{CompGCN}\xspace}^\tup{t} = \bm{h}_{w, \textsf{CompGCN}\xspace}^\tup{t},
\end{equation*}
for either point-wise summation or concatenation as the composition map.
\item There exist initial vertex features and a sequence $\mathbf{W}_\textsf{CompGCN}\xspace^{(t)}$ of \textsf{CompGCN}\xspace\
parameters, such that for all vertices $v$ and $w$ in $V(G)$,
\begin{equation*}
C^{(t)}_{\textsf{WR}}(v) = C^{(t)}_{\textsf{WR}}(w) \ \ \Longleftrightarrow \ \ \bm{h}_{v, \textsf{CompGCN}\xspace}^\tup{t} = \bm{h}_{w, \textsf{CompGCN}\xspace}^\tup{t},
\end{equation*}
for either point-wise summation or concatenation as the composition map.
\end{itemize}
}
\end{theorem}
Together with Proposition \ref{prop:weak-wl-sep} and Theorem \ref{thm:mrgcn-lower}, this result states that \textsf{CompGCN}\xspace\
architectures based on vector summation or concatenation are provably weaker in terms of their capacity to distinguish vertices in graphs than the ones that use vector scaling.
We have shown that \textsf{R\text{-}GCN}{} and \textsf{CompGCN}\xspace{} with point-wise multiplication have the same expressive power in terms of distinguishing non-isomorphic multi-relational graphs or distinguishing vertices in a multi-relational graph. As it turns out, these two architectures actually define the \emph{same} functions. A similar result holds between \textsf{CompGCN}\xspace{} with vector summation/subtraction and concatenation. See Appendix \ref{APP:sec:comparison} for details.
\section{Limitations and More Expressive Architectures}\label{sec:more_exp}
Theorem~\ref{thm:mrgcn-upper} shows that both \textsf{R\text{-}GCN}{} as well as \textsf{CompGCN}\xspace have severe limitations in distinguishing structurally different multi-relational graphs. Indeed, the following results shows that there exists pairs of non-isomorphic, multi-relational graphs that neither \textsf{R\text{-}GCN}{} nor \textsf{CompGCN}\xspace can distinguish.
\medskip
\begin{proposition}\label{upper}
{\em For all $r \geq 1$, there exists a pair of non-isomorphic graphs $G = (V(G), R_1(G), \dots, R_r(G), \ell)$ and $H= (V(H), R_1(H), \dots, R_r(H), \ell)$ that cannot be distinguished by \textsf{R\text{-}GCN}{} or \textsf{CompGCN}\xspace. }
\end{proposition}
We note here that the two graphs $G$ and $H$ from the above theorem can also be used to show that neither \textsf{R\text{-}GCN}{} nor \textsf{CompGCN}\xspace
will be able to compute different features for vertices in $G$ and $H$, making them indistinguishable. Hence, to overcome the limitations of the \textsf{CompGCN}\xspace{} and \textsf{R\text{-}GCN}, we introduce \emph{local $k$-order relational networks} (\krns{k}), leveraging recent progress in overcoming GNNs' inherent limitations in expressive power~\citep{Mor+2019,Morris2020b,Mor+2021b,Mor+2022b}. To do so, we first extend the local $k$-dimensional Weisfeiler--Leman algorithm~\citep{Morris2020b}, see Subsection~\ref{APP:vr_ext}, to multi-relational graphs.
\paragraph{Multi-relational Local $k$\text{-}\textsf{WL}} Given a multi-relational graph $G = (V(G), R_1(G), \dots, R_r(G), \ell)$, we define the \new{multi-relational atomic type} $\mathsf{atp}_r \colon V(G)^k \to \ensuremath{\mathbb{N}}$ such that $\mathsf{atp}_r(\vec{v}) = \mathsf{atp}_r(\vec{w})$ for $\vec{v}$ and $\vec{w}$ in $V(G)^k$ if and only if the mapping $\varphi\colon V(G) \to V(G)$ where $v_g \mapsto w_g$ induces a partial isomorphism, preserving the relations, i.e., we have $v_p = v_q \iff w_p = w_q$ and $(v_p,v_q) \in R_i(G) \iff (\varphi(v_p),\varphi(v_q)) \in R_i(G)$ for $i$ in $[r]$. The \new{multi-relational local $k$\text{-}\textsf{WL}} ($k$-\textsf{RLWL}) computes the coloring $C_{k,r}^{(t)} \colon V(G)^k \to \ensuremath{\mathbb{N}}$ for $t \geq 0$, where $C_{k,r}^{(0)} \coloneqq \mathsf{atp}_r(\vec{v})$, and refines a coloring $C_{k,r}^{(t)}$ (obtained after $t$ iterations of the $k$-\textsf{RLWL}) via the \new{aggregation function}
\begin{equation}\label{eqnmidd_ext_m}
\begin{split}
M_{r}^{(t)}(\vec{v}) \coloneqq \big( &\{\!\! \{ (C_{k,r}^{(t)}(\theta_1(\vec{v},w)), i) \mid w \in N_i(v_1) \text{ and } i \in [r] \} \!\!\}, \dots, \\ &\{\!\! \{ (C_{k,r}^{(t)}(\theta_k(\vec{v},w)),i) \mid w \in N_i(v_k) \text{ and } i \in [r] \} \!\!\} \big),
\end{split}
\end{equation}
where $\theta_j(\vec{v},w)\coloneqq (v_1, \dots, v_{j-1}, w, v_{j+1}, \dots, v_k)$. That is, $\theta_j(\vec{v},w)$ replaces the $j$-th component of the tuple $\vec{v}$ with the vertex $w$. Like the local $k$\text{-}\textsf{WL}~\citep{Morris2020b}, the algorithm considers only the local $j$-neighbors, i.e., $v_i$ and $w$ must be adjacent, for each relation in each iteration and additionally differentiates between different relations. The coloring functions for the iterations of the multi-relational $k$-\textsf{RLWL}{} are then defined by
\begin{equation*}\label{wlsimple_ext_m}
C_{k,r}^{(t+1)}(\vec{v}) \coloneqq (C_{k,r}^{(t)}(\vec{v}), M_{r}^{(t)}(\vec{v})).
\end{equation*}
In the following, we derive a neural architecture, the \krn{k}, that has the same expressive power as the $k$-\textsf{RLWL}{} in terms of distinguishing non-isomorphic multi-relational graphs.
\paragraph{The \krn{k} Architecture.} Given a labeled, multi-relational graph $G$, for each $k$-tuple $\vec{v}$ in $V(G)^k$, a \krn{k} architecture computes an initial feature $\bm{h}_{v}^\tup{0}$ \new{consistent} with its multi-relational atomic type, e.g., a one-hot encoding of $\mathsf{atp}_r(\vec{v})$. In each layer, $t > 0$, a \krn{k} computes a $k$-tuple feature
\begin{align}\label{kgnn}
\begin{split}
\bm{h}_{\vec{v},k}^\tup{t} \coloneqq
\mathsf{UPD}^\tup{t}\Bigl( \bm{h}_{\vec{v},k}^\tup{t-1},\mathsf{AGG}^\tup{t} \bigl(&\{\!\!\{ \phi(\bm{h}_{\theta_1(\vec{v},w),k}^\tup{t-1}, \bm{z}_i^{(t)}) \
\mid w \in N_i(v_1) \text{ and } i \in [r] \}\!\!\}, \dots,\\ &\{\!\!\{ \phi(\bm{h}_{\theta_k(\vec{v},w),k}^\tup{t-1}, \bm{z}_i^{(t)})
\mid w \in N_i(v_k) \text{ and } i \in [r] \}\!\!\} \bigr)\Bigr) \in \mathbb{R}^{e},
\end{split}
\end{align}
where the functions $\mathsf{UPD}^\tup{t}$ and $\mathsf{AGG}^\tup{t}$ for $t > 0$ may be a differentiable parameterized functions, e.g., neural networks.
Similarly to Equation~\ref{eq:comp}, $\bm{z}_i^{(t)}$ in $\ensuremath{\mathbb{R}}^{c}$ is the learned edge feature for the $i$th relation at layer $t$ and $\phi \colon \ensuremath{\mathbb{R}}^d \times \ensuremath{\mathbb{R}}^b \to \ensuremath{\mathbb{R}}^c$ is a composition map. In the case of graph-level tasks, e.g., graph classification, one uses
\begin{equation}\label{readout_k}
\bm{h}_G \coloneqq \mathsf{READOUT}\bigl( \{\!\!\{ \bm{h}_{\vec{v}}^{\tup{T}}\mid \vec{v} \in V(G)^k \}\!\!\} \bigr) \in \mathbb{R}^{e},
\end{equation}
to compute a single vectorial representation based on learned $k$-tuple features after iteration $T$. The following results shows that the $k$-\textsf{RLWL}{} upperbounds the expressivity of any \krn{k} in terms of distinguishing non-isomorphic graphs.
\medskip
\begin{proposition}
\label{thm:ho-upper}
{\em Let $G = (V(G), R_1(G), \dots, R_r(G), \ell)$ be a labeled, multi-relational graph. Then for all $t \geq 0$, $r > 0$, $k \geq 1$, and all choices of $\mathsf{UPD}^\tup{t}$, $\mathsf{AGG}^\tup{t}$, and all $\vec{v}$ and $\vec{w}$ in $V(G)^k$,
\begin{equation*}
C_{k,r}^{(t)}(\vec{v}) = C_{k,r}^{(t)}(\vec{w}) \ \Longrightarrow \ \bm{h}_{\vec{v},k}^\tup{t} = \bm{h}_{\vec{w},k}^\tup{t}.
\end{equation*}}
\end{proposition}
Moreover, we can also show the converse, resulting in the following theorem.
\medskip
\begin{proposition}
\label{thm:ho-lower}
{\em Let $G = (V(G), R_1(G), \dots, R_r(G), \ell)$ be a labeled, multi-relational graph. Then for all $t \geq 0$ and $k \geq 1$, there exists $\mathsf{UPD}^\tup{t}$, $\mathsf{AGG}^\tup{t}$, such that for all $\vec{v}$ and $\vec{w}$ in $V(G)^k$,
\begin{equation*}
C_{k,r}^{(t)}(\vec{v}) = C_{k,r}^{(t)}(\vec{w}) \ \Longleftrightarrow \ \bm{h}_{\vec{v},k}^\tup{t} = \bm{h}_{\vec{w},k}^\tup{t}.
\end{equation*}
}
\end{proposition}
The following result implies that increasing $k$ leads to a strict boost in terms of expressivity of the $k$-\textsf{RLWL}{} and \krn{k} architectures in terms of distinguishing non-isomorphic multi-relational graphs.
\medskip
\begin{proposition}\label{hier_neural}
{\em For $k \geq 2 $ and $r \geq 1$, there exists a pair of non-isomorphic multi-relational graphs $G_r = (V(G_r), R_1(G_r), \dots, R_r(G_r), \ell)$ and $H= (V(H_r), R_1(H_r), \dots, R_r(H_r), \ell)$ such that:
\begin{itemize}
\item For all choices of $\mathsf{UPD}^\tup{t}$, $\mathsf{AGG}^\tup{t}$, for $t > 0$, and $\mathsf{READOUT}$ the $k$-\textsf{RN}{} architecture will not distinguish the graphs $G_r$ and $H_r$.
\item There exists $\mathsf{UPD}^\tup{t}$, $\mathsf{AGG}^\tup{t}$, for $t > 0$, and $\mathsf{READOUT}$ such that the $(k+1)$\text{-}\textsf{RN} will distinguish them.
\end{itemize}}
\end{proposition}
Moreover, the following results shows that for $k=2$ the \krn{k} architecture is strictly more expressive than \textsf{CompGCN}\xspace{} and \textsf{R\text{-}GCN}{} in distinguishing non-isomophics graphs.
\medskip
\begin{corollary}
{\em There exists a \krn{2} architecture that is strictly more expressive than the \textsf{CompGCN}\xspace and the \textsf{R\text{-}GCN}\ architecture in terms of distinguishing non-isomorphic graphs. }
\end{corollary}
\paragraph{\krns{k} for Vertex-level Prediction}
As defined in Equations~\ref{kgnn} and~\ref{readout_k}, an \krn{k} architecture either computes $k$-tuple- or graph-level features. However, it is straightforward to compute a vertex-level features, see, e.g.,~\citet[Section 4.1]{Mor+2022a}.
\paragraph{Scalability} Although the \krn{k} is provably expressive, see Proposition~\ref{hier_neural}, it suffer some high memory requirement. Similar to the $k$\text{-}\textsf{WL}, it's memory complexity can only be lower bounded in~$\Omega(n^k)$, making it not applicable for large knowledge graphs. However, recent progress in making higher-order architectures more scalable, e.g.,~\cite{Bev+2021,Mor+2022a,Qia+2022}, can be straightforwardly lifted to the multi-relational case.
\section{Experimental Study}
\label{sec:experiments}
Here, we investigate to what extend the above theoretical results hold for real-world data distributions. Specifically, we aim to answer the following questions.
\begin{description}
\item[Q1] Does the theoretical equivalence of \textsf{R\text{-}GCN}{} and \textsf{CompGCN}\xspace{} hold in practice?\\
\item[Q2] Does the performance depend on the dimension of vertex features?\\
\item[Q3] Does \textsf{CompGCN}\xspace{} benefit from normalization and learnable edge weights?\\
\item[Q4] Does the theoretical difference in composition functions of \textsf{CompGCN}\xspace{} hold in practice?\\
\end{description}
\paragraph{Datasets.} To answer Q1 to Q4, we investige \textsf{R\text{-}GCN}\ and \textsf{CompGCN}\xspace's empirical performance on the small-scale AIFB (6\,000 vertices) and the large-scale AM (1.6 million vertices)~\citep{ristoski2016collection} vertex classification benchmark dataset; see Section~\ref{app:data} for dataset statistics.
\paragraph{Featurization.}
Most relational GNNs for vertex- and link-level tasks assume that the initial vertex states come from a learnable vertex embedding matrix~\citep{wang2021survey, ali2021bringing}. However, this vertex feature initialization or featurization method makes the model inherently transductive, i.e., the model must be re-trained when adding new vertices. Moreover, such an initialization strategy is incompatible with our Weisfeiler-Leman-based theoretical results since a learnable vertex embedding matrix will result in most initial vertex features being pair-wise different. Here, however, being faithful to the Weisfeiler-Leman formulation, we initialize \emph{all} vertex features with the \emph{same} $d$-dimensional vector, namely, a standard basis vector of $\ensuremath{\mathbb{R}}^{d}$, e.g., $(1, 0, \dots, 0)$ in $\ensuremath{\mathbb{R}}^{d}$.\footnote{We also probed a vector initialized with the \citet{glorot2010understanding} strategy, showing similar results.}
Relation-specific weight matrices in the case of \textsf{R\text{-}GCN}{} and edge features in the case of \textsf{CompGCN}\xspace{} are still learnable. We stress here that such a featurization strategy endows GNNs with inductive properties. Since we are using the same vertex feature initialization, we can run inference on previously unseen vertices or graphs.
\begin{figure}[t]
\centering
\begin{subfigure}[b]{0.60\textwidth}
\centering
\includegraphics[width=0.8\textwidth]{images/exp1.pdf}
\caption{AIFB results with varying input feature dimension.}
\label{fig:exp1_1}
\end{subfigure}
\begin{subfigure}[b]{0.35\textwidth}
\centering
\includegraphics[width=\textwidth]{images/exp1_2.pdf}
\caption{AM results with $dim=4$.}
\label{fig:exp1_2}
\vspace{0pt}
\end{subfigure}
\caption{Vertex classification performance of \textsf{CompGCN}\xspace and \textsf{R\text{-}GCN}\ on smaller (AIFB) and larger (AM) graphs. Initial vertex feature dimensions higher than 4 do not improve the accuracy.}
\end{figure}
\paragraph{Implementation.}
We use the \textsf{R\text{-}GCN}\ and \textsf{CompGCN}\xspace implementation provided by PyG framework~\citep{Fey+2019}. The source code of all methods and evaluation procedures is available at \url{https://github.com/migalkin/RWL}. For the smaller AIFB dataset, both models use two GNN layers. For the larger AM dataset, \textsf{R\text{-}GCN}\ saturates with three layers. Following the theory, we do not use any basis decomposition of relation weights in \textsf{R\text{-}GCN}. We list other hyperparameters in Section~\ref{app:data}.
We report averaged results of five independent runs using different random seeds. We conducted all experiments in the full-batch mode on a single GPU (Tesla V100 32\,GB or RTX 8000).
\paragraph{Discussion.}
Probing \textsf{R\text{-}GCN}\ with different aggregations and \textsf{CompGCN}\xspace on the smaller AIFB (Figure~\ref{fig:exp1_1}) and larger AM (Figure~\ref{fig:exp1_2}) datasets, we largely confirm the theoretical hypothesis of their expressiveness equivalence (\textbf{Q1}) and observe similar performance of both GNNs. The higher variance on AIFB is due to the small test set size (36 vertices), i.e., one misclassified vertex drops accuracy by $\approx 3\%$.
To test if increasing the input vertex feature dimensions leads to more expressive GNN architectures (\textbf{Q2}), we vary the initial vertex feature dimension in $\{2,4,8,\ldots, 64,128\}$ on the smaller AIFB dataset (Figure~\ref{fig:exp1_1}) and do not observe any significant differences starting from $d=4$ and above. Having identified that, we report the best results of compared models on the larger AM graph with the vertex feature dimension $d$ in $\{4,8\}$.
Following the theory where the \texttt{sum} aggregator is most expressive, we investigate this finding on the smaller AIFB dataset for both GNNs. \textsf{R\text{-}GCN}\ with \texttt{mean} aggregation shows slightly better results on the larger AM dataset, which we attribute to the unstable optimization process of the \texttt{sum} aggregator where vertices might have thousands of neighbors, leading to large losses and noisy gradients. We hypothesize that stabilizing the training process on larger graphs might improve performance.
Furthermore, we perform an ablation study (Figure~\ref{fig:exp2}) of main \textsf{CompGCN}\xspace components (\textbf{Q3}), i.e., direction-based weighting (over direct, inverse, and self-loop edges), relation projection update in each layer, and message normalization in the GCN style $\vec{D}^{-\frac{1}{2}}\vec{A}\vec{D}^{-\frac{1}{2}}$; see also Sections~\ref{APP:comp} and~\ref{app:rgcn}.
The crucial components for the smaller and larger graphs are (1) three-way direction-based message passing and (2) normalization. Replacing message passing over three directions (and three weight matrices) with one weight matrix using a single adjacency leads to a significant drop in performance. Removing normalization increases variance in the larger graph. Finally, removing both directionality and normalization leads to significant degradation in predictive performance.
\begin{figure}[t]
\centering
\includegraphics[width=0.65\textwidth]{images/exp2.pdf}
\caption{\textsf{CompGCN}\xspace ablations. Directionality (\emph{-dir}) and normalization (\emph{-norm}) are the most crucial components, i.e., their removal does lead to significant performance drops.}
\label{fig:exp2}
\end{figure}
Studying composition functions (Figure~\ref{fig:exp3}), we do not find significant differences among non-parametric \texttt{mult}, \texttt{add}, \texttt{rotate} functions (\textbf{Q4}); see Section~\ref{APP:comp}.
Performance of an MLP over a concatenation of vertex and edge features
falls within confidence intervals of other compositions and does not exhibit a significant accuracy boost.
\begin{figure}[t]
\centering
\includegraphics[width=0.55\textwidth]{images/exp3.pdf}
\caption{\textsf{CompGCN}\xspace with different composition functions. No significant differences.}
\label{fig:exp3}
\end{figure}
\section{Conclusion}
Here, we investigated the expressive power of two popular GNN architectures for knowledge or multi-relational graphs, namely, \textsf{CompGCN}\xspace{} and \textsf{R\text{-}GCN}. By deriving a variant of the $1$\text{-}\textsf{WL}, we quantified their limits in distinguishing vertices in multi-relational graphs. Further, we investigated under which conditions, i.e., the choice of the composition function, \textsf{CompGCN}\xspace{}, reaches the same expressive power as \textsf{R\text{-}GCN}. To overcome the limitations of the two architectures, we derived the provably more powerful \krn{k} architecture. By increasing $k$, the \krn{k} architecture gets strictly more expressive. Empirically, we verified that our theoretical results translate largely into practice. Using \textsf{CompGCN}\xspace{} and \textsf{R\text{-}GCN}{} in a vertex classification setting over small and large multi-relational graphs shows that both architectures provide a similar performance level. We believe that our paper is the first step in a principled design of GNNs for knowledge or multi-relational graphs.
\section*{Acknowledgements}
Pablo Barcel\'o is funded by Fondecyt grant 1200967, the ANID - Millennium Science Initiative Program - Code ICN17002, and the National Center for Artificial Intelligence CENIA FB210017, Basal ANID. Mikhail Galkin is funded by the Samsung AI grant held at Mila. Christopher Morris is partially funded a DFG Emmy Noether grant (468502433) and RWTH Junior Principal Investigator Fellowship under the Excellence Strategy of the Federal Government and the Länder. Miguel Romero is funded by Fondecyt grant 11200956, the Data Observatory Foundation, and the National Center for Artificial Intelligence CENIA FB210017, Basal ANID.
\bibliographystyle{unsrtnat}
| {'timestamp': '2022-12-01T02:18:13', 'yymm': '2211', 'arxiv_id': '2211.17113', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17113'} | arxiv |
\section{Introduction}
The fact that the network of social relations of an individual influences the individual's behavior - opinions, purchases, voting - is a well known phenomenon and has been studied in several contexts. In particular, the Influence Maximization, aiming at detecting a fixed set size of individuals able to maximize the spread of an opinion, and the Target Set Selection, aiming at detecting the minimum size set of individuals able to convince all the other individuals in the network,
have received a wide attention in the literature and some mathematical models have been proposed to analyze such a kind of diffusion of information over networks, including the linear threshold model \cite{Granovetter1978}, the voter model \cite{Holley1975} and the Independent Cascade Model \cite{GLM2001,KKT2003}, all of which considering relationships inducing {\em positive} feedback effects only.
However, in most network settings also {\em negative} link effects are to be considered.
One way to take into account negative feedbacks is that pursued in
\cite{Chen2011, NazTag2012, Stitch2014, YaWaTru2019}
where it is assumed that individuals may also develop a negative opinion about the feature to be spread and, in this case, they may negatively influence their neighbors.
Differently, in
\cite{Ahmed2013, DV2020, LiChen2013} the possibility that some relations between individuals are ruled by, for instance, antagonism and distrusting (see \cite{EaKlein2010} and references quoted therein) is considered: it is now assumed that node opinions about the feature to be spread are always positive but that receiving positive feedback from an untrusted/antagonist neighbor results in increasing the support to discard the feature. Finally, in
\cite{ GaArRoy2016, HZND2016} the two approaches (positive/negative opinions and positive/ne\-ga\-tive relationships) are jointly considered.
Strictly related to the analysis of the diffusion of information is the analysis of opinion dynamics, in which individuals have a state (that is, an opinion) which evolves over time~\cite{Sirbu2017}. Now, the questions under considerations are something like the following: starting at some given current opinion configuration, will an equilibrium opinion configuration or a given target opinion configuration ever be reached? Or, also, will a given target individuals set ever reach consensus? Different opinion dynamics stochastic models have been considered as to unsigned relations (such as, the French-DeGroot model~\cite{French1956,Degroot1974} and its extensions, the majority rule model~\cite{Galam2002}, and the social impact model~\cite{Lewenstein1992}) and some of these models have been adapted to the case of signed graphs~\cite{Li2015,Shi2016,He2021,Xue2020}. In \cite{Chatterjee2020} a couple of deterministic opinion dynamics models are defined, as a simplification of the Game-of-Life~\cite{Gardener1970}, and their reachability properties are studied. One of the two models, the {\em underpopulation} opinion dynamics, will be furtherly considered in this paper.
\subsection*{Paper contributions}
Letting individuals change their opinion on a majority basis with respect to their neighbors' opinions is a quite natural assumption which has indeed somehow taken into accounts in some of the proposed models. As an example, in the Voter model \cite{CS1973,Moretti2013} each individual has one of two discrete opinions and at each time step a random individual is selected along with one of its neighbours with the first one taking the opinion of the neighbour: here, majority plays an indirect role in that an individual has a greater probability to get the opinion of the majority of its neighbors than the opposite one. The role of the majority's opinion is made explicit in the Majority Rule model first proposed in \cite{Galam2002}. In \cite{Galam2002} agents take discrete opinions ($+1$ or $-1$) and can interact with all other agents (that is, an underlying complete unsigned graph is considered); at each time step a group of $r$ agents is randomly selected and all of them take the majority opinion within the group.
In this paper the {\em deterministic Majority Rule} opinion dynamics is introduced and studied, which can be considered as the deterministic counterpart of the Majority Rule model proposed in \cite{Galam2002}.
In the Deterministic Majority Rule individuals operate in an underlying directed signed (non-complete) graph, where an incoming positive (negative) arc to an individual describes that the individual trusts (respectively, distrusts) that neighbor; at each time step each individual takes the majority opinion within the set of its neighbors, where, like in \cite{Li2015}, an opinion passing through a negative arc is complemented (that is, a distrusted neighbor with a negative opinion is equivalent to a trusted neighbor with a positive opinion, and a distrusted neighbor with a positive opinion is equivalent to a trusted neighbor with a negative opinion).
Three reachability-related problems are here considered with respect to the Deterministic Majority rule: given a signed graph in a given {\em opinion configuration} (that is, an assignment of a positive or negative opinion to each of its nodes), will an equilibrium opinion configuration ({\sc ReachEquilibrium}) / a given target opinion configuration ({\sc Reachability}) / an opinion configuration in which all nodes in a given target set agree ({\sc ReachTarget}) ever be reached?
The achievement of this paper is showing that, while the link signs are ininfluent to the complexity of the aforementioned reachability problems, such complexity dramatically changes when considering directed or undirected graphs. This is formalized in the following theorem.
\begin{theorem} \label{thm::reachdirected}
The problems {\sc Reachability}, {\sc ReachTarget} and {\sc ReachE\-qui\-librium} considered with respect to the Deterministic Majority Rule are \mbox{\textsc{PSpace}}-complete even when restricted to unsigned directed graphs.
\end{theorem}
\begin{theorem} \label{thm::reachundirected}
The problems {\sc Reachability}, {\sc ReachTarget} and {\sc ReachE\-qui\-librium} are in \mbox{\textsc{P}}\ when restricted to signed undirected graphs.
\end{theorem}
The proof of the above theorems is deferred to the full version of this paper. Instead, in this extended abstract the generalization of a result in \cite{Chatterjee2020} which is functional to the proof of Theorem \ref{thm::reachundirected} will be formally stated and proved.
The proof of Theorem \ref{thm::reachundirected} strongly relies on the fact that the number of opinion configurations met by an undirected unsigned graph during its opinion evolution occurring with respect to the Majority Deterministic rule and starting at any initial opinion configuration is polynomially bounded on the size of the graph. A similar polynomial bound had already been proved in \cite{Chatterjee2020} in the case in which an undirected unsigned graph evolves according to the {\em underpopulation} rule defined in that paper as a simplification of the Game-of-Life rule.
Actually, both the deterministic Majority Rule and the underpopulation rule fall within a general framework rule introduced in this paper that will be referred to as {\em local threshold-based opinion dynamics} rule: for a given pair of computable integer threshold functions $\theta^+$ and $\theta^-$, at any step each individual decides whether changing its opinion or not based on the values $\theta^+(k)$ and $\theta^-(k)$, $k$ being the number of the individual's neighbors. As it will be described in Section \ref{sec::preliminaries}, the deterministic Majority Rule occurs when $\theta^+(k)$ and $\theta^-(k)$ are close to $k/2$, and the underpopulation rule occurs when $\theta^+(k)=i_1$ and $\theta^-(k)=i_2$, for some pair of constants $i_1$ and $i_2$.
Specifically, after having provided the needed definitions in Section \ref{sec::preliminaries}, in Section \ref{sec::mainlemmaproof} the following theorem will be formally stated and proved.
\medskip
\noindent
{\bf Theorem 3.} {\em For any undirected unsigned graph $G=(V,E)$ of maximum degree $\Delta$ and for any initial opinion configuration $\omega$ of $G$, the number of opinion configurations met by $G$ during its opinion evolution starting at $\omega$ and occurring with respect to any local threshold-based dynamics rule is at most}
$$ 4|E|+2|V|+4 \Delta (\Delta +1)|V|+2.$$
\section{Preliminary definitions and notations} \label{sec::preliminaries}
A directed {\em signed} graph $G=(V,A, \lambda)$ is a directed graph together with an arc-labeling function $\lambda: A \rightarrow \{-1,1\}$. An undirected signed graph $G=(V,E, \lambda)$, is similarly defined with $\lambda$ being an edge labeling function, that is, $\lambda: E \rightarrow \{-1,1\}$.
Within this paper, for any node $v$ of a directed (undirected) signed graph $G$, $N(u)$ denotes the set of of in-neighbors (respectively, neighbors) of $u$.
An \textit{opinion configuration} of a signed graph $G$ is a node-labeling function $\omega: V \rightarrow \{-1,1\}$, stating whether a given node is in favor or against a specific topic. Nodes influence each other so that their opinions change over time. In particular, the neighbors of a node $u$ influence the opinion $u$ gets over time: positive in-neighbors positively influence $u$, that is, their influence works in favour of $u$ getting their same opinion, while negative in-neighbors negatively influence $u$, that is, their influence works in favour of $u$ getting their opposite opinion. In this respect, for any in-neighbor $v$ o any nodef $u$, we say that $v$ {\em pushes} $u$ to 1 at $\omega$ if $\omega(v)=1$ and $\lambda(v,u)=1$ or $\omega(v)=-1$ and $\lambda(v,u)=-1$, and that
$v$ {\em pushes} $u$ to $-1$ at $\omega$ if $\omega(v)=-1$ and $\lambda(v,u)=1$ or $\omega(v)=1$ and $\lambda(v,u)=-1$.
An \textit{opinion dynamics} is a functional $\mathbf{d}$ which specifies, for a given signed graph $G$ and an opinion configuration $\omega$ of $G$, the next opinion configuration $\mathbf{d}(G,\omega)$ of $G$.
The \textit{opinion configuration evolution set} of a signed graph $G$ in a configuration $\omega$ with respect to an opinion dynamics $\mathbf{d}$ (or, in short, the $\mathbf{d}$-{\em evolution set} of $G$) is the sequence $\mathcal{E}_{\mathbf{d}}(G,\omega)= \langle \omega_1=\omega, \omega_2, \ldots , \omega_T \rangle$ of distinct opinion configurations such that $T \leq 2^{|V|}$ (the number of configurations of $V$) and
\begin{itemize}
\item for $t=2, \ldots ,T$, $\omega_t=\mathbf{d}(G,\omega_{t-1})$, and
\item there exists $h \leq T$ such that $\omega_h=\mathbf{d}(G,\omega_{T})$.
\end{itemize}
Whenever it happens that $h=T$, $\omega_T$ is said an {\em equilibrium configuration}.
With a slight abuse of notation, the sequence $\mathcal{E}_{\mathbf{d}}(G,\omega)$ shall be dealt with as a set as well.
This paper focuses on the \textit{deterministic majority} opinion dynamics $\mathbf{d}_M$
in which a node with positive (respectively, negative) opinion changes its opinion only if more than half of its in-neighbors push it to $-1$ (respectively, 1).
Formally, for any node $u$ and for any opinion configuration $\omega$, $\mathbf{d}_M(G,\omega)=\omega'$ is defined as
\[\omega'(u) = \left\lbrace
\begin{array}{ll}
1 & \mbox{if $\sum_{v \in N(u)}\lambda(v,u)\omega(v)>0$}, \\
\omega(u) & \mbox{if $\sum_{v \in N(u)}\lambda(v,u)\omega(v) = 0$}, \\
-1 & \mbox{if $\sum_{v \in N(u)}\lambda(v,u)\omega(v) < 0$}.
\end{array}
\right.
\]
A dynamics $\mathbf{d}$ is \textit{local} when the new opinion of a node depends only on its current opinion, the current opinions of its in-neighbors, and the signs of the arcs connecting them to it. A dynamics $\mathbf{d}$ is \textit{threshold-based} when it is ruled by a pair of {\em threshold functions} $\theta^+: \mathbf{N} \rightarrow \mathbf{N}$ and $\theta^-: \mathbf{N} \rightarrow \mathbf{N}$ in the following way: for any node $u$ and for any opinion configuration $\omega$, $\mathbf{d}(G,\omega)=\omega'$ is defined as
\[\omega'(u) = \left\lbrace
\begin{array}{ll}
1 & \mbox{if $\omega(u)=1$ and $P(u)\geq \theta^+(|N(u|))$} \\
& \mbox{or $\omega(u) =-1$ and $P(u)\geq \theta^-(|N(u)|)$}, \\
-1 & \mbox{if $\omega(u)=1$ and $P(u)< \theta^+(|N(u)|)$} \\
& \mbox{or $\omega(u) =-1$ and $P(u)< \theta^-(|N(u)|)$,}
\end{array}
\right.
\]
where $P(u)$ is the number of in-neighbours $v$ of $u$ pushing $u$ to 1. Notice that, without loss of generality, the bounds $\theta^+(u) \leq \Delta+1$ and $\theta^-(u) \leq \Delta+1$ for any $u \in V$ can be assumed, where $\Delta$ is the maximum node in-degree in $G$.
It can be easily verified that the deterministic Majority Rule is the local threshold-based dynamics corresponding to having $\theta^+(k)=\left\lceil\frac{k}{2}\right\rceil$ and $\theta^-(k)=\left\lfloor\frac{k}{2}\right\rfloor+1$.
The \textit{underpopulation} opinion dynamics considered in \cite{Chatterjee2020} is another noticeable example of a local threshold-based opinion dynamics which corresponds to having $\theta^+(k)=t_{1}$ and $\theta^-(k)=t_{2}$ for some pair of constants $t_{1},t_{2}\in\mathbf{N}$.
\section{Local threshold-based dynamics in undirected unsigned graphs: size of the opinion configuration evolution set} \label{sec::mainlemmaproof}
Aim of this subsection is proving that, for any local threshold-based dynamics $\mathbf{d}$, the size of $\mathcal{E}_{\mathbf{d}}(G,\omega)$ is polynomially bounded by the size of $G$. This will be accomplished by exploiting
the same reasoning applied in \cite{Chatterjee2020} for proving the same result in the case of the underpopulation rule, properly modified to let it works for a generic local threshold-based dynamics.
For the sake of readability (and for keeping the notation as close as possible to that in \cite{Chatterjee2020}), within this section the opinion $-1$ will be replaced by $0$, that is, we shall assume that an opinion configuration is a function $\omega: V \rightarrow \{ 0,1 \}$; needless to say, this does not change anyway the model.
Let $G=(V,E)$ be an undirected unsigned graph, let $\omega$ be an opinion configuration of $G$ and let $\mathcal{E}_{\mathbf{d}}(G,\omega)= \langle \omega_1=\omega, \ldots , \omega_T \rangle$ be the $\mathbf{d}$-evolution set of $G$, where $\mathbf{d}$ is any local threshold-based dynamics. For $v \in V$, the {\em history}
of $v$ is the
string $\omega_1(v) \omega_2(v) \ldots \omega_T(v) \in \{ 0,1 \}^T$, that is, the history of $v$ is the sequence of opinions that $v$ gets during the $\mathbf{d}$-evolution of $G$ starting at $\omega$ before an opinion configuration is repeated (recall that $\mathbf{d}(\omega_T)=\omega_h$ for some $h \leq T$). For $1 \leq i \leq j \leq T$, the {\em period} $\omega_{[i,j]}(v)$ in the history of $v$ is the string $\omega_i(v) \omega_{i+1}(v) \ldots \omega_j(v)$.
In what follows, a sequence $y= y_1y_2 \ldots y_h \in \{ 0,1,? \}^h$ will be used as a shortcut to the set of all sequences in which every ? inside $y$ is replaced by 0 and by 1: as an example, $?1?$ stands for the set of sequences $010, 011, 110, 111$. Given a pair of sequences $y= y_1y_2 \ldots y_h \in \{ 0,1,? \}^h$ and $z=z_1z_2 \ldots z_h \in \{ 0,1 \}^h$, $y$ {\em matches} $z$ (in symbols, $y \approx z$) if $y_i=z_i$ whenever $y_i \in \{ 0,1 \}$ (no matter what happens if $y_i=?$), for every $i=1, \ldots ,h$.
Given a node $v$ and a sequence $y\in\{0,1,?\}^h$, let $[y,v]$ be the number of matches of $y$ inside the history of node $v$, that is,
\[
[y,v] = \big\lvert \{ i \in \{ 1, \ldots , T-h+1 \}: y \approx \omega_{[i,i+h-1]}(v) \} \big\rvert ,
\]
and let $[y] = \sum_{v \in V} [y,v]$ be the total number of matches of $y$ inside the histories of all nodes in $V$.
Hence, next lemma shows that the total number of matches of 110, 100, 011 and 001 inside the histories of all nodes in $V$ is upper-bounded by a polynomial in the size of $G$.
\begin{lemma} \label{lemma::1?0+0?1}
For any undirected unsigned graph $G$ and for every $t \geq 3$,
\[ [110]+[100]+[011]+[001] \leq 4|E|+2|V| + 4|V| \Delta (\Delta +1), \]
where $\Delta$ is the maximum node degree in $G$.
\end{lemma}
\begin{proof}
For any $y= y_1y_2 \ldots y_h \in \{ 0,1,? \}^h$, with $h \leq T$, denote as $[y]^1$ the number of nodes whose history starts with the sequence $y$ and as $[y]^T$ the number of nodes whose history ends with the sequence $y$. Hence, $0 \leq [y]^1 \leq |V|$, $0 \leq [y]^T \leq |V|$.
The first step is bounding $[001] + [011]$. To this aim, notice that, trivially, $[00] = [00]^1 + [000] + [100]$ and $[00]=[00]^T + [000] + [001]$; from the two equalities it follows that
\begin{equation} \label{eq::from00_t}
| [100] - [001] | = | [00]^1 - [00]^T | \leq |V| ;
\end{equation}
similarly, $[11] = [11]^1 + [011] + [111]$ and $[11]=[11]^T + [110] + [111]$, so that
\begin{equation} \label{eq::from11_t}
| [011] - [110] | \leq |V|.
\end{equation}
Hence,
\begin{equation} \label{eq::0?1}
[001] + [011]
\ \leq \ [100] + |V| + [110] +|V| \ = \ [1?0] + 2 |V|.
\end{equation}
In order to bound $[1?0]$ some more notation is needed. First of all, for any $1 \leq k \leq \Delta$, $V_k$ is the subset of $V$ containing all the nodes of degree $k$.
For $y \in \{ 0,1,? \}^*$ such that $|y| \leq T$, $[y,k]$ denotes the total number of matches of $y$ inside the history of all nodes in $V_k$ with $[y] = \sum_{k=1}^{\Delta} [y,k]$, since $\{ V_k \}_{1 \leq k \leq \Delta}$ is a partition on $V$; $[y,k]_t^T$ and $[y,k]^0$ are defined accordingly.
Let $y,z \in \{ 0,1,? \}^*$ be such that $|y|=|z| \leq T$. Then,
\begin{small}
\[ [y,z,k] = \sum_{u \in V_k} \sum_{v \in N(u)} | \{ i \in \{ 0, \ldots, T-|y| \} :
\omega_{[i+1,i+|y|]}(u) \approx y \ \wedge \ \omega_{[i+1,i+|z|]}(v) \approx z \}| \]
\end{small}
is the number of corresponding matches of $y$ and $z$ inside the histories of any pair of nodes $u$ and $v$ such that $(u,v) \in E$ and $u \in V_k$. Similarly,
\begin{small}
\[ [y,z] = \sum_{u \in V} \sum_{v \in N(u)} | \{ i \in \{ 0 \ldots T-|y| \}: \omega_{[i+1,i+|y|]}(u) \approx y \ \wedge \ \omega_{[i+1,i+|z|]}(v) \approx z \}| \]
\end{small}
is the number of corresponding matches of $y$ and $z$ inside the histories of all pair of nodes $u$ and $v$ such that $(u,v) \in E$. Since $\{ V_k \}_{1 \leq k \leq \Delta}$ is a partition on $V$, then $[y,z] = \sum_{k=1}^{\Delta} [y,z,k]$.
Finally,
\[ [y,z,k]^0 = \sum_{u \in V_k \ : \ \omega_{[1,|y|]}(u) \approx y} \left| \{ v \in N(u): \ \omega_{[1,|z|]}(v) \approx z \} \right| \]
and $[y,z]^0$, $[y,z,k]^T$ and $[y,z]^T$ are defined similarly.
Notice that, by the edge simmetry, for every $y,z \in \{ 0,1,? \}^*$ such that $|y|=|z| \leq T$, it holds that $[y,z] = [z,y]$ and so it is $[?1, 1?] = [1?, ?1]$. Let us now compute in two different ways the two sides of the last equality:
\begin{eqnarray*}
[?1, 1?] & = & [?1, 1?]^1 + [0?1, ?1?] + [1?1, ?1?] \\
& = & [?1, 1?]^1 + [001, ?1?] + [011, ?1?] + [1?1, ?1?]
\end{eqnarray*}
\begin{eqnarray*}
[1?, ?1] & = & [1?, ?1]^T + [1?0, ?1?] + [1?1, ?1?] \\
& = & [1?, ?1]^T + [100, ?1?] + [110, ?1?] + [1?1, ?1?].
\end{eqnarray*}
Hence,
by equalizing the last terms in the two chains of equalities above,
$$ | [001, ?1?] + [011, ?1?] - [100, ?1?] - [110, ?1?] | = | [?1, 1?]^1 - [1?, ?1]^T |. $$
Similarly as before, it holds that $0 \leq [?1, 1?]^1 \leq 2|E|$ and $0 \leq [?1, 1?]_t^T \leq 2|E|$, so that
\begin{equation} \label{eq::edges1}
-2|E| \leq [001, ?1?] + [011, ?1?] - [100, ?1?] - [110, ?1?] \leq 2|E|.
\end{equation}
As far as $[001, ?1?] , [011, ?1?] , [100, ?1?] $ and $[110, ?1?]$ are concerned, by the definition of $\mathbf{d}$, the following holds. Since the state of a node $u$ changes from $0$ to $1$ if and only if at least $\theta^-(|N(u)|)$ of its neighbors are in state $1$ and since a node $u$ in state $0$ remains in state $0$ if and only if less than $\theta^-(|N(u)|)$ of its neighbors are in state $1$, then
$$[001, ?1?,k] \geq \theta^-(k) [001, k]_t \mbox{\hspace*{0.1cm} and \hspace*{0.1cm}}[100, ?1?,k] \leq \left( \theta^-(k)-1\right) [100, k]_t $$
and, similarly,
$$[011, ?1?,k] \geq \theta^+(k) [011, k]_t \mbox{\hspace{0.1cm} and \hspace*{0.1cm}}
[110, ?1?,k] \leq \left( \theta^+(k) -1 \right) [110, k]_t. $$
Hence,
\begin{small}
\begin{align*}
& [001, ?1?] - [100, ?1?] + [011, ?1?] - [110, ?1?] = \\
& \sum_{k =1}^{\Delta} \left\lbrace [001, ?1?,k] - [100, ?1?,k] + [011, ?1?,k] - [110, ?1?,k] \right\rbrace \geq\\
& \sum_{k =1}^{\Delta} \left\lbrace \theta^-(k) [001,k] - \left( \theta^-(k)-1\right) [100,k]
+ \theta^+(k) [011,k] - \left( \theta^+(k) -1 \right) [110,k] \right\rbrace = \\
& \sum_{k =1}^{\Delta} \left\lbrace \theta^-(k) ([001,k] - [100,k]) + [100,k]
+ \theta^+(k) ([011,k] - [110,k]) + [110,k] \right\rbrace = \\
& [100] + [110] + \sum_{k =1}^{\Delta} \left\lbrace \theta^-(k)( [001,k] - [100,k] )
+ \theta^+(k) ([011,k] - [110,k]) \right\rbrace.\\
\end{align*}
\end{small}
And, by (\ref{eq::edges1}), this implies
\begin{small}
\begin{align*}
[100] + [110] &\leq 2|E| +\sum_{k =1}^{\Delta} \left\lbrace \theta^-(k) ( [100,k] - [001,k] )
+ \theta^+(k) ([110,k] - [011,k] \right\rbrace. \\
\end{align*}
\end{small}
By the same reasonings to those leading to Equations (\ref{eq::from00_t}) and (\ref{eq::from11_t}), it holds that $|[100,k] - [001,k]| \leq |V|$ and $|[110,k] - [011,k]| \leq |V|$. Hence, by recalling that $\theta^+(u) \leq \Delta+1$ and $\theta^-(u) \leq \Delta+1$,
\begin{small}
\[ [100] + [110] \leq
2|E| +|V| \sum_{k =1}^{\Delta} \left\lbrace \theta^-(k)+\theta^+(k) \right\rbrace
\leq 2|E| + |V| \Delta (2\Delta +2).
\]
\end{small}
Finally, by (\ref{eq::0?1}), the assertion follows
\end{proof}
The next theorem then follows from the above Lemma.
\begin{theorem} \label{thm::undirectedstable-lengthoftransient}
For any local threshold-based opinion dynamics $\mathbf{d}$, for any undirected unsigned graph $G=(V,E)$ and for any opinion configuration $\omega$ of $G$,
$\left| \mathcal{E}_{\mathbf{d}}(G,\omega) \right| \leq 4|E|+2|V|+4 \Delta (\Delta+1) |V| +2$.
\end{theorem}
\begin{proof}
Let $T=\left| \mathcal{E}_{\mathbf{d}}(G,\omega) \right|$. Since the opinion configurations in $\mathcal{E}_{\mathbf{d}}(G,\omega)$ are distinct, then, in particular, for any $1 \leq t \leq T-2$, $\omega_t \neq \omega_{t+2}$. This means that, for any $1 \leq t \leq T-2$, there exists $u_t \in V$ such that $\omega_t(u_t) \neq \omega_{t+2}(u_t)$.
As a consequence, for any $1 \leq t \leq T-2$, the string $\omega_t(u_t) \omega_{t+1}(u_t) \omega_{t+2}(u_t)$ is one in the set $\{ 001,011,100,110 \}$.
Hence, $[001]+[011]+[100]+[110] \geq T-2$ and,
by Lemma \ref{lemma::1?0+0?1},
$$T-2 \leq 4|E|+2|V|+4 \Delta (\Delta+1) |V|. $$
\end{proof}
\bigskip
\noindent
{\bf Aknowledgements.} The author wishes to thank Pierluigi Crescenzi an Giorgio Gambosi for fruitful discussions and for having read preliminary versions of this paper.
\bibliographystyle{elsarticle-num}
| {'timestamp': '2022-12-01T02:19:25', 'yymm': '2211', 'arxiv_id': '2211.17159', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17159'} | arxiv |
\section{Introduction}\label{sec: intro}
Theorems that lift the complexity of a function in a weaker model of computation to that of the complexity of a closely related function in a stronger model, have proved to be extremely useful and is a dominant theme of current research (see, for example,~\cite{GPW18,CKLM19,GPW20,CFKMP21,LMMPZ22}). One early use of this theme is in the celebrated work of Raz and McKenzie~\cite{RM99}, that built upon the earlier work of Edmonds et al.~\cite{ERIS91} to yield a separation of the hierarchy of monotone circuit complexity classes within NC. The central tool of that work is an argument lifting the query complexity of a (partial) relation $f$ to the two-party communication complexity of the composed relation $f \circ g$, where $g$ is a two-party function, now commonly called a gadget. It required much technical innovation to prove the natural intuition that, if the gadget $g$ is obfuscating enough, the best that the two players can do to evaluate $f \circ g$ is to follow an optimal decision tree algorithm $\mathcal{Q}$ for $f$, solving the relevant instance of $g$ to resolve each query of $\mathcal{Q}$ encountered along its path of execution. The major utility of this theorem lies in the fact that it reduces the difficult task of proving communication complexity lower bounds to the much simpler task of proving decision tree complexity lower bounds. Indeed, this point was driven home more recently, in the beautiful work of G{\"{o}}{\"{o}}s, Pitassi and Watson \cite{GPW18}, who established tight quadratic gaps between communication complexity and (rectangular) partition number, resolving a longstanding open problem. This was, arguably, largely possible as the task was reduced to finding an appropriate analog of that separation in the query world. This last work triggered a whole lot of diverse work on such lifting theorems. Such theorems have been proved for the randomized model \cite{GPW20,CFKMP21}, models with application to data-structures \cite{CKLM18}, proof and circuit complexity (see, for example, \cite{RNV16,GGKS20,GKMP20}), quantum computing \cite{ABK21}, extended formulations \cite{KMR17} etc.
Most of these lifting theorems work with gadgets whose size is at least logarithmic in the arity of the outer function. A current challenge in the area is to break this barrier and prove lifting with sub-logarithmic gadget size (see, for example, \cite{LMMPZ22}), ultimately culminating in constant-size gadgets. It is not clear whether existing ideas/methods can be pushed to achieve this. Faced with this, we consider lifting decision-tree (DT) complexity to intermediate models that are more complex than DT but simpler than 2-party communication. Parity decision tree (PDT) is a natural choice for such a model. Indeed, in tackling another major open problem in communication complexity, the Log-Rank Conjecture (LRC), researchers have realized the importance and utility of such intermediate models. For instance, the natural analogue of LRC is open for PDTs (see \cite{TWXZ13,TXZ16}) giving rise to a basic conjecture in Fourier analysis. The analogue of LRC was recently proved for AND-decision trees~\cite{KLMY21} bringing forth interesting techniques. Further, the randomized analog of LRC, known as the Log-Approximate-Rank Conjecture (LARC) was recently disproved \cite{CMS20} using a surprisingly simple counter-example. The key to discovering this counter-example lay in finding the corresponding counter-example against the analog of the LARC for PDTs.
Taking cue from these developments, we consider lifting DT complexity using small gadgets to PDT and allied complexity in this work. We are able to find an interesting property of gadgets, which we call `stifling', that we prove is sufficient for enabling such lifting even with constant gadget size.
We define a Boolean function $g : \{0, 1\}^m \to \{0, 1\}$ to be \emph{$k$-stifled} if for all subsets of $k$ input variables and for all $b \in \{0, 1\}$, there exists a setting of the remaining $m - k$ variables that forces the value of $g$ to $b$ (i.e., the values of the $k$ variables are irrelevant under the fixing of these $m - k$ variables). Formally,
\begin{definition}\label{def: stifled}
Let $g : \{0, 1\}^m \to \{0, 1\}$ be a Boolean function. We say that $g$ \emph{is $k$-stifled} if the following holds:
\begin{align*}
&\forall S \subseteq [m]~\textnormal{with}~|S| \leq k~\textnormal{and}~\forall b \in \{0, 1\},\\ &\exists~z \in \{0, 1\}^{[m] \setminus S}~\textnormal{such that for all}~x \in \{0, 1\}^m ~\textnormal{with}~ x|_{[m] \setminus S} = z, g(x) = b.
\end{align*}
\end{definition}
We refer the reader to \Cref{sec: notation} for formal definitions of complexity measures.
We obtain a lifting theorem from decision tree complexity ($\mathsf{DT}(\cdot)$) of a function $f$ to parity decision tree size ($\mathsf{PDTsize}(\cdot)$, denoting the minimum number of nodes in a parity decision tree computing the function) of $f$ composed with a gadget $g$ that is stifled.\footnote{We remark here that even a lifting theorem from $\mathsf{DT}(f)$ to deterministic communication complexity of $f \circ g$ would not imply \Cref{thm: pdt size lifting} as a black box. This is because deterministic communication complexity can be much larger than the logarithm of PDTsize (for instance, for the Equality function). However a lifting theorem from randomized decision tree complexity of $f$ to randomized communication complexity of $f \circ g$ does imply a lifting theorem from \emph{randomized} decision tree complexity of $f$ to PDTsize of $f \circ g$ (see Claim~\ref{claim: randomized lifting implies dt-pdtsize lifting} and the following discussion).}
\begin{theorem}\label{thm: pdt size lifting}
Let $g:\{0,1\}^m \to \{0,1\}$ be a $k$-stifled function and let $f \subseteq \{0, 1\}^n \times \mathcal{R}$ be a relation. Then,
\[
\mathsf{PDTsize}(f \circ g) \geq 2^{\mathsf{DT}(f) \cdot k}.
\]
\end{theorem}
In order to prove this, we start with a PDT for $f \circ g$ of size $2^d$, say, and construct a depth-$d/k$ DT for $f$ by `simulating' the PDT.
Using a similar simulation, we also give lower bounds on the \emph{subspace} decision tree complexity of $f \circ g$, where subspace decision trees are decision trees whose nodes can query indicator functions of arbitrary affine subspaces. Let $\mathsf{sDT}(\cdot)$ denote subspace decision tree complexity.
\begin{theorem}\label{thm: sdt depth lifting}
Let $g:\{0,1\}^m \to \{0,1\}$ be a $k$-stifled function, and let $f \subseteq \{0, 1\}^n \times \mathcal{R}$ be a relation. Then,
\[
\mathsf{sDT}(f \circ g) \geq \mathsf{DT}(f) \cdot k.
\]
\end{theorem}
We observe in \Cref{claim: sdt lifting implies depth-size lifting} that the bounds in the above two theorems are equivalent up to logarithmic factors. More precisely we show that \Cref{thm: pdt size lifting} follows (up to a constant factor in the exponent in the RHS) from \Cref{thm: sdt depth lifting}, and that \Cref{thm: sdt depth lifting} follows (up to a $\log n$ factor in the RHS) from \Cref{thm: pdt size lifting}.
It is easy to see that both of the above theorems individually imply a lifting theorem from $\mathsf{DT}(f)$ to $\mathsf{PDT}(f \circ g)$. We choose to state this as a separate theorem since it is interesting in its own right, and we feel that the proof of \Cref{thm: pdt depth lifting} gives more intuition.
\begin{theorem}\label{thm: pdt depth lifting}
Let $g:\{0,1\}^m \to \{0,1\}$ be a $k$-stifled function, and let $f \subseteq \{0, 1\}^n \times \mathcal{R}$ be a relation. Then,
\[
\mathsf{PDT}(f \circ g) \geq \mathsf{DT}(f) \cdot k.
\]
\end{theorem}
Examples of stifled gadgets (functions that are $k$-stifled for some integer $k \geq 1$) are the well-studied Indexing function and the Inner Product Modulo 2 function, as we show in \Cref{claim: ind property p} and \Cref{claim: ip stifled}. It is worth noting that we obtain tight lifting theorems for \emph{constant-sized} gadgets. Although there is no gadget of arity $1$ or $2$ that is stifled, both the Indexing gadget on three bits and the Majority gadget on three bits are stifled. Define the Majority function on $n$ input bits by $\mathsf{MAJ}_n(x) = 1$ iff $|\cbra{i \in [n]: x_i=1}| \geq n/2$.
Define the Indexing function as follows.
\begin{definition}[Indexing Function]
For a positive integer $m$, define the Indexing function, denoted $\mathsf{IND}_m : \{0, 1\}^{m + 2^m} \to \{0, 1\}$, by
\[
\mathsf{IND}_m(x, y) = y_{\mathsf{bin}(x)},
\]
where $\mathsf{bin}(x)$ denotes the integer in $[2^m]$ represented by the binary expansion $x$.
\end{definition}
In the above definition, we refer to $\cbra{x_i : i \in [m]}$ as the \emph{addressing variables}, and $\cbra{y_j : j \in [2^m]}$ as the \emph{target variables}.
\begin{definition}[Inner Product Modulo 2 Function]
For a positive integer $m$, define the Inner Product Modulo 2 Function, denoted $\mathsf{IP}_m : \{0, 1\}^{2m} \to \{0, 1\}$, by
\[
\mathsf{IP}_m(x_1, \dots, x_n, y_1, \dots, y_n) = \oplus_{i = 1}^n (x_i \wedge y_i).
\]
\end{definition}
We show that $\mathsf{IND}_m$ is $m$-stifled for all integers $m \geq 1$, and $\mathsf{IP}_m$ is $1$-stifled for all integers $m \geq 2$. We refer the reader to \Cref{app: stifled proofs} for proofs of the three claims below. We also show in \Cref{app: stifled proofs} that the Majority function $\mathsf{MAJ}_m$ on $m$ input bits is $(\lceil m/2 \rceil - 1)$-stifled and no Boolean function on $m$ input bits is $\lceil m/2 \rceil$-stifled (hence, `Majority is stiflest').
\begin{claim}\label{claim: ind property p}
For all integers $m \geq 1$, the function $\mathsf{IND}_m$ is $m$-stifled.
\end{claim}
\begin{claim}\label{claim: ip stifled}
For all integers $m \geq 2$, the function $\mathsf{IP}_m$ is $1$-stifled.
\end{claim}
We also show that a random Boolean function (the output on each input is chosen independently to be 0 with probability 1/2 and 1 with probability 1/2) on $m$ input variables (where $m$ is sufficiently large) is $(\log m/2)$-stifled with high probability.
\begin{claim}\label{claim: random stifled}
Let $g : \{0, 1\}^m \to \{0, 1\}$ be a random Boolean function with $m$ sufficiently large. Then with probability at least $9/10$, $g$ is $((\log m)/2)$-stifled.
\end{claim}
\Cref{thm: pdt depth lifting},~\Cref{thm: sdt depth lifting} and~\Cref{thm: pdt size lifting} imply the following results for the Indexing gadget in light of \Cref{claim: ind property p}.
\begin{corollary}\label{cor: indexing lifting}
Let $f \subseteq \{0, 1\}^n \times \mathcal{R}$ be a relation. Then for all positive integers $m$,
\begin{align*}
\mathsf{PDT}(f \circ \mathsf{IND}_m) & \geq \mathsf{DT}(f) \cdot m\\
\mathsf{sDT}(f \circ \mathsf{IND}_m) & \geq \mathsf{DT}(f) \cdot m,\\
\mathsf{PDTsize}(f \circ \mathsf{IND}_m) & \geq 2^{\mathsf{DT}(f) \cdot m}.
\end{align*}
\end{corollary}
We now show that the Parity function witnesses tightness of the above corollary. It is easy to see that for all relations $f$,
\[
\mathsf{PDT}(f \circ \mathsf{IND}_m) \leq \mathsf{DT}(f) \cdot (m + 1).
\]
In fact, our proof can be modified to show $\mathsf{PDT}(f \circ \mathsf{IND}_m) \geq \mathsf{DT}(f) \cdot m + 1$ (see \Cref{rmk: improved simulation}). Let $\oplus_n$ denote the Parity function on $n$ input variables. It outputs 1 if the number of 1s in the input is odd, and 0 otherwise. It is well known that $\mathsf{DT}(\oplus_n) = n$.
We have $\mathsf{PDT}(\oplus_n \circ \mathsf{IND}_m) \leq \mathsf{DT}(\oplus_n) \cdot m + 1 = nm + 1$: query all the $m$ addressing variables in each block to find out the relevant variables using $nm$ queries. The output of the function (which is the parity of all relevant target variables) can now be computed using a single parity query. Thus our result is tight.
Since $\mathsf{IP}_m$ is $1$-stifled for all integers $m \geq 2$ (\Cref{claim: ip stifled}), we analogously obtain the following results for the Inner Product Modulo 2 gadget.
\begin{corollary}\label{cor: ip lifting}
Let $f \subseteq \{0, 1\}^n \times \mathcal{R}$ be a relation. Then for all positive integers $m \geq 2$,
\begin{align*}
\mathsf{PDT}(f \circ \mathsf{IP}_m) & \geq \mathsf{DT}(f),\\
\mathsf{sDT}(f \circ \mathsf{IP}_m) & \geq \mathsf{DT}(f),\\
\mathsf{PDTsize}(f \circ \mathsf{IP}_m) & \geq 2^{\mathsf{DT}(f)}.
\end{align*}
\end{corollary}
Since a random gadget on $m$ inputs is $(\Omega(\log m))$-stifled (Claim~\ref{claim: random stifled}), we obtain analogous results for random gadgets as well.
\subsection{Consequence for proof complexity}
A central question in the area of proof complexity is ``Given an unsatisfiable CNF $\mathcal{C}$, what is the size of the smallest polynomial-time verifiable proof that $\mathcal{C}$ is unsatisfiable?'' To give lower bounds on the size of such proofs for explicit formulas $C$, the question has been studied with the restriction that the proof must come from a simple class of proofs. Two of these classes are relevant to us: resolution and linear resolution. Resolution is now well understood and strong lower bounds on the size of resolution based proofs are known for several basic and natural formulas, like the pigeonhole principle, Tseitin formulas and random constant-width CNFs. However, linear resolution introduced by Raz and Tzameret \cite{RT08}, where the clauses are conjunctions of affine forms over $\mathbb{F}_2$, are poorly understood. In fact, it remains a tantalizing challenge to prove super-polynomial lower bounds on the size of linear resolution proofs for explicit CNFs. One promising way to make progress on this question is to prove a lifting theorem that lifts ordinary resolution proof-size lower bounds for a CNF to linear resolution proof-size lower bounds for a lifted CNF. Indeed, relatively recently, riding on the success and popularity of lifting theorems on communication protocols, Garg, G{\"{o}}{\"{o}}s, Kamath and Sokolov \cite{GGKS20} showed that ordinary resolution proof-size complexity, among other things, can be lifted to cutting plane proof-size complexity. However, lifting to linear resolution proof-size still evades researchers.
A first step towards the above would be to lift \emph{tree-like} resolution proof-size bounds to tree-like linear resolution proof-size bounds. Although lower bounds for tree-like linear resolution proof-size were established by Itsykson and Sokolov \cite{IS20}, there was no systematic technique known that would be comparable to the generality of a lifting theorem. Our lifting theorem provides the first such technique as explained below.
The starting point is the well-known fact that the size of the smallest tree-like resolution proof that $\mathcal{C}$ is unsatisfiable is the same as the size of the smallest decision tree that computes the relation $S_{\mathcal{C}} := \cbra{(x,C):C\text{ is a clause of }\mathcal{C}\text{ and }C(x)=0}$. Similarly, the size of the smallest tree-like $Res(\oplus)$~(linear resolution over $\mathbb{F}_2$) proof that $\mathcal{C}$ is unsatisfiable is the same as the size of the smallest parity decision tree that computes $S_{\mathcal{C}}$.
Let $\mathcal{C}$ be a CNF with $n$ variables and $t$ clauses, each of width at most $w$. For a gadget $g: \{0, 1\}^m \to \{0, 1\}$, we define the CNF $\mathcal{C} \circ g$ as follows. For each clause $C \in \mathcal{C}$, take the clauses of a canonical CNF computing $\Gamma_C : (y_1,\dots,y_n) \in (\{0, 1\}^m)^n \mapsto C(g(y_1),g(y_2),\dots,g(y_n))$. Note that $\Gamma_C$ is a function of at most $mw$ variables, and thus can be expressed as a CNF with at most $2^{mw}$ clauses, each of width at most $mw$. Define $\mathcal{C} \circ g$ to be the CNF whose clauses are $\bigcup_{C \in \mathcal{C}} \Gamma_C$.
Our results in this paper yield PDT lower bounds against $S_{\mathcal{C}} \circ g$ given DT lower bounds against $S_{\mathcal{C}}$. To compute $S_{\mathcal{C}} \circ g$ we get as input $y = (y_1,\dots,y_n) \in (\{0, 1\}^m)^n$ and we have to output a clause $C \in \mathcal{C}$ such that $C(x)=0$ where $x = (g(y_1),\dots,g(y_n))$. On the other hand to compute $S_{\mathcal{C} \circ g}$ we get as input $y$ and we have to output a clause $D \in \bigcup_{C \in \mathcal{C}} \Gamma_C$ such that $D(y)=0$. However if $D(y) = 0$ and $D \in \Gamma_C$, then by definition of $\Gamma_C$, $C(x)=0$ where $x = (g(y_1),\dots,g(y_n))$. Hence computing $S_{\mathcal{C} \circ g}$ is sufficient to compute $S_{\mathcal{C}} \circ g$ and our lower bounds against $S_{\mathcal{C}} \circ g$ translate to lower bounds against $S_{\mathcal{C} \circ g}$, bringing us back to the realm of proof complexity.
Our size lifting (\Cref{thm: pdt size lifting}) is particularly relevant, when applied with $g$ as the Indexing gadget on 3 bits, for example. Let $\mathcal{C}$ be a 3-CNF $\mathcal{C}$ with $n$ variables and $t$ clauses, with tree-like resolution width at least $d$. Our theorem implies a tree-like $Res(\oplus)$~size lower bound of $2^d$ for the CNF $\mathcal{C} \circ \mathsf{IND}_1$, with $3n$ variables and $O(t)$ clauses, each of maximum width at most $9$.
\subsection{Related work}
Independently and concurrently with our work, Beame and Koroth~\cite{BK22} obtained closely related results. They show that a particular property of a gadget, conjectured recently by Lovett et al.~\cite{LMMPZ22} to be sufficient for lifting using constant size, is in fact insufficient to yield constant-size lifting. Using properties special to Indexing, they obtain a lifting theorem from decision tree height complexity of $f$ to the complexity of $f \circ \mathsf{IND}$ in a restricted communication model that they define, where $\mathsf{IND}$ has constant size. Further, modifying the proof of this result they also lift decision tree complexity of $f$ to PDT size complexity of $f \circ \mathsf{IND}$.
We, on the other hand, prove directly a lifting theorem for PDT size, from deterministic decision tree height, that works for any constant size gadget that satisfies the abstract property of stifling. Examples of such gadgets are $\mathsf{IND}$, $\mathsf{IP}$, Majority and random functions. While there are some similarities between our and their arguments, especially in the use of row-reduction, our proof is entirely linear algebraic with no recourse to information theory.
\section{The simulation}
In \Cref{sec: notation} we introduce necessary notation for proving our theorems. In \Cref{sec: overview simulation} we give an overview of the simulation for \Cref{thm: pdt depth lifting} (i.e., we show an algorithm that takes a low-depth PDT computing $f \circ g$ and constructs a low-depth DT computing $f$). We do this for the sake of simplicity; the simulations used to prove \Cref{thm: pdt size lifting} and \Cref{thm: sdt depth lifting} are small modifications of the simulation used to prove \Cref{thm: pdt depth lifting}. In \Cref{sec: simulation alg} we show the simulation in full detail, with a key subroutine explained in \Cref{sec: rowreduce}. We then analyze correctness of the simulation in \Cref{sec: correctness}. We conclude the proofs of all of our theorems in \Cref{sec: all simulation theorems}.
\subsection{Notation}\label{sec: notation}
Throughout this paper, we identify $\{0, 1\}$ with $\mathbb{F}_2$. We identify vectors in $\mathbb{F}_2^n$ with their characteristic set, i.e., a vector $x \in \mathbb{F}_2^n$ is identified with the set $\cbra{i \in [n] : x_i = 1}$. For vectors $a, b \in \mathbb{F}_2^n$, let $\langle a, b \rangle$ denote $\sum_{i = 1}^n a_ib_i$ modulo 2. We say a vector in $\mathbb{F}_2^n$ is non-zero if it does not equal $0^n$. For a positive integer $n$ we use the notation $[n]$ to denote the set $\cbra{1, 2, \dots, n}$ and the notation $[n]_0$ to denote the set $\cbra{0, 1, \dots, n-1}$. Throughout this paper $\mathcal{R}$ denotes an arbitrary finite set. When clear from context, `$+$' denotes addition modulo 2.
\subsubsection{Decision trees and complexity measures}
A \emph{parity decision tree} (PDT) is a binary tree whose leaf nodes are labeled in $\mathcal{R}$, each internal node is labeled by a parity $P \in \mathbb{F}_2^n$ and has two outgoing edges, labeled $0$ and $1$.
On an input $x \in \{0, 1\}^n$, the tree's computation proceeds from the root down as follows: compute $\mathsf{val}(P,x) := \ip{P}{x}$ as indicated by the node's label and follow the edge indicated by the computed value. Continue in a similar fashion until reaching a leaf, at which point the value of the leaf is output. When the computation reaches a particular internal node, the PDT is said to \emph{query} the parity label of that node.
A decision tree (subspace decision tree, respectively), denoted DT (sDT, respectively), is defined as above, except that queries are to individual bits (indicator functions of affine subspaces of $\mathbb{F}_2^n$, respectively) instead of parities as in PDTs.
A DT/PDT/sDT is said to compute a relation $f \subseteq \{0, 1\}^n \times \mathcal{R}$ if the output $r$ of the DT/PDT/sDT on input $x$ satisfies $(x, r) \in f$ for all $x \in \{0, 1\}^n$.
The DT/PDT/sDT complexity of $f$, denoted $\mathsf{DT}(f)/\mathsf{PDT}(f)/\mathsf{sDT}(f)$, is defined as
\[
\mathsf{DT}(f)/\mathsf{PDT}(f)/\mathsf{sDT}(f) := \min_{T : T~\text{is a DT/PDT/sDT computing}~f} \textnormal{depth}(T).
\]
The decision tree size (parity decision tree size, respectively) of $f$, denoted $\mathsf{DTsize}(f)$ ($\mathsf{PDTsize}(f)$, respectively), is defined as
\[
\mathsf{DTsize}(f)/\mathsf{PDTsize}(f) := \min_{T : T~\text{is a DT/PDT computing}~f} \textnormal{size}(T),
\]
where the size of a tree is the number of leaves in it.
\subsubsection{Composed relations and simulation terminology}
For positive integers $n,m$, a relation $f \subseteq \{0, 1\}^n \times \mathcal{R}$, a function $g : \{0, 1\}^{m} \to \{0, 1\}$ and strings $\cbra{y_i \in \{0, 1\}^{m} : i \in [n]}$, we use the notation $g^n(y_1, \dots, y_n)$ to denote the $n$-bit string $(g(y_1), \dots, g(y_n))$. The relation $f \circ g \subseteq (\{0, 1\}^{m})^{n} \times \mathcal{R}$ is defined as $(y_1, \dots, y_n, r) \in (f \circ g) \iff (g(y_1), \dots, g(y_n), r) \in f$.
We view the input to $f \circ g$ as an $mn$-bit string, with the bits naturally split into $n$ \emph{blocks}. A parity query $P$ to an input of $f \circ g$ can be specified as an element of $(\mathbb{F}_2^{m})^{n}$. For $i \in [n]$ and a parity query $P$, $P|_i \in \mathbb{F}_2^{m}$ refers to the restriction of $P$ to the $i$th block. For a parity query $P$ and a set of indices $S \subseteq [m] \times [n]$, $P|_S$ refers to the restriction of $P$ to the set of indices $S$.
We say parity $P$ \emph{touches block $i$} or $P$ \emph{touches a set $S$} if $P|_i$ is non-zero or $P|_S$ is non-zero, respectively.
A string $y' \in (\{0, 1\}^{m})^n$ is said to be a \emph{completion} of a partial assignment $y \in (\{0,1,*\}^{m})^{n}$ if $y'_i = y_i$ for all $i \in [m] \times [n]$ with $y_i \neq *$.
For a node $N$ in a PDT and bit $a \in \{0, 1\}$, we use $\textnormal{child}(N, a)$ to denote the node reached on answering the parity at the node $N$ as $a$.
For a parity $P$ and a partial assignment $y$ such that $y_i \neq *$ for all $i \in P$, $\mathsf{val}(P,y)$ denotes $\ip{P}{y}$.
\subsection{Overview of the simulation}\label{sec: overview simulation}
In this subsection we sketch and describe our simulation algorithm with the goal of proving \Cref{thm: pdt depth lifting}. The proofs of \Cref{thm: pdt size lifting} and \Cref{thm: sdt depth lifting} follow along similar lines, and are formally proved in \Cref{sec: all simulation theorems}.
We prove Theorem~\ref{thm: pdt depth lifting} via a simulation argument: given a PDT of depth $d$ for $f \circ g$, we construct a DT of depth at most $d/k$ for $f$.
On input $x \in \{0, 1\}^n$, our decision tree algorithm simulates the PDT traversing a path from its root to a leaf, and outputs the value that the PDT outputs at that leaf. During this traversal the decision tree algorithm queries bits of $x$. It also keeps track of a partial assignment $y \in (\{0,1,*\}^{m})^{n}$ satisfying the following property that guarantees correctness: For all $w \in \{0, 1\}^n$ consistent with the queried bits of $x$ there is a completion $y'$ of $y$ such that
\begin{itemize}
\item $g^n(y') = w$, and
\item the path traversed by the PDT on input $y'$ is the same as that traversed in the simulation.
\end{itemize}
This ensures that once the simulation reaches a leaf of the PDT, every input $w$ that is consistent with the queried bits of $x$ has the same output as the output at the leaf. That is, the simulation is a valid query algorithm for $f$.
To carry out the simulation we assign to every parity query along the path a block that the parity query touches, unless its output value is already determined by $y$. We say that the parity query has that block \emph{marked}. At a high level, if a block has been marked by only a few parity queries, then we have enough freedom in the block to do the following:
\begin{itemize}
\item set its output (i.e., the value of $g$ on the variables in the block) to any bit we wish by setting some of the variables in the block (this uses the stifling property of $g$), and
\item retroactively complete this partial assignment so that each of the parity queries marking the block evaluate to any bit of our choosing on the completed input. \end{itemize}
We use these to prove the property that guarantees correctness. The first point helps us in getting a partial assignment $y$ such that $g^n(z) = w$ for all completions $z$ of $y$, and the second helps us complete it to a $y'$ that reaches the leaf we want it to reach. A formal statement of the required properties is in \Cref{claim: correctness}.
During the simulation once a block, say block $i$, has been marked by $k$ parity queries we carefully choose $k$ bits of the block that we will keep unset in our partial assignment throughout the simulation. These $k$ bits are what allow us to perform the completion as in the second bullet above. We then query the value of $x_i$ and set the other $m-k$ bits in block $i$ to ensure that the output of block $i$ is set to $x_i$. The fact that we can do this crucially uses the assumption that the gadget $g$ is $k$-stifled. In the process above, every parity in the PDT simulation marks at most one block, and a variable $x_i$ is not queried until the $i$th block is marked $k$ times. Thus the depth of the resultant DT is at most $d/k$.
A situation that may arise is when a parity $P$ marks block $i$ but a previous parity query $P'$ that marked block $i$ has $P|_i = P'|_i$, for example. However, at some point we may be required to set $P|_i$ to $0$ and $P'|_i$ to $1$ in order to follow the path in the simulation, which is impossible.
To avoid such issues we preprocess each parity query $P$ to ensure that when it marks block $i$, $P|_i$ is not in the linear span of $\cbra{P'|_i : P' \text{ is an earlier parity that marks block }i}$. The simulation algorithm is given in \Cref{alg:pdt to dt} with the preprocessing subroutine given in \Cref{alg:rowreduce}. \Cref{alg:pdt to dt} uses two other functions, described below.
\begin{definition}\label{def: propp fn}
Let $g : \{0, 1\}^m \to \{0, 1\}$ be a $k$-stifled Boolean function. We define the function $\mathsf{STIFLE}_g$ to be a canonical function that takes as input a set $S \subseteq [m]$ with $\@ifstar{\oldabs}{\oldabs*}{S} \leq k$ and a bit $b$ and outputs a partial assignment $y \in \{0,1,*\}^m$ such that
\begin{itemize}
\item for all $i \in [m]$, $i \in S \iff y_i = *$, and
\item for all completions $y'$ of $y$, $g(y') = b$.
\end{itemize}
\end{definition}
The existence of such a function in the definition above is guaranteed since $g$ is $k$-stifled.
\begin{definition}\label{def: findvars}
Define the function $\mathsf{FINDVARS}$ to be a canonical function that takes as input a set $\cbra{P_1,\dots,P_{\ell}}$ of $\ell$ linearly independent vectors in $\mathbb{F}_2^{m}$ and outputs a set $S$ of $\ell$ indices in $[m]$ such that $\cbra{P_i|_S}_{i \in [\ell]}$ are also linearly independent vectors.
\end{definition}
The existence of such a function in the definition above is guaranteed by the fact that an $\ell \times m$ matrix of rank $\ell$ has $\ell$ linearly independent columns, and the $\ell \times \ell$ matrix defined by restricting the original matrix to these columns also has rank $\ell$.
\subsection{The simulation algorithm}\label{sec: simulation alg}
In Algorithm~\ref{alg:pdt to dt}, we start with a PDT $T$ of size $2^{d}$ for $f \circ g$, and an unknown input $x \in \{0, 1\}^n$. Our simulation constructs a decision tree for $f$ of depth at most $d/k$.\footnote{Our algorithm is designed to work with $k \geq 1$. For instance, Line~\ref{line: markandkth} is intended to catch the $k$th time a block is marked, which does not make sense for $k=0$.\label{footnote: kgreaterthanzero}} This would prove \Cref{thm: pdt size lifting}.
We use the following notation in Algorithm~\ref{alg:pdt to dt}:
\begin{itemize}
\item $\mathsf{num}$ is the number of parity queries simulated in $T$ so far.
\item $M$ is an array storing parity queries made so far (after processing).
\item $A$ is an array storing the answers to the parities in $M$. These are such that answering the queries in $M$ with the answers in $A$ is equivalent to answering the queries in the PDT to reach the node reached by the simulation algorithm.
\item For all $i \in [n]$, $\mathsf{MARK}[i]$ is the set of indices in $M$ of parity queries that have the $i$th block marked. That is, $\mathsf{MARK}[i] = \cbra{j \in [\mathsf{num}]_0 : M[j] \text{ marks block }i}$.
\item $y$ is the partial assignment stored by the simulation algorithm. It is initialized to $(*^m)^n$.
\item For all $i \in [n]$, $\mathsf{FREE}[i]$ is the set of indices in block $i$ of $y$ that have not yet been set. That is, $\mathsf{FREE}[i] = \cbra{(i,j) : j \in [m], y_{i,j} = *}$. It is initialized to $\cbra{i} \times [m]$ for each $i \in [n]$.
\item $Q$ is the set of indices of $x$ queried during the simulation.
\end{itemize}
The algorithm starts at the root node of the PDT and does the following for each parity query $P$ it comes across in its traversal down the PDT (Line~\ref{line: simulationloop}).
\begin{itemize}
\item In Line~\ref{line: rowreduce} it processes the parity query using the \textsf{ROW-REDUCE}~subroutine. The subroutine outputs a parity $P'$, a `correction' bit $b$ and an index $j \in [n]$ denoting which block was marked by the parity (or $\bot$ if no block was marked).
As stated in Claim~\ref{clm: processedequivalence}, these outputs satisfy the following: for all $y \in \{0, 1\}^{mn}$,
\[ \Big[\mathsf{val}(M[i], y) = A[i]\, \forall i \in [\mathsf{num}]_0\Big] \implies \Big[\mathsf{val}(P, y) = 0 \iff \mathsf{val}(P', y) = b\Big]. \]
In other words, for all inputs consistent with the answers to the previous parity queries made along the path, $P$ evaluates to $0$ if and only if $P'$ evaluates to $b$.
\item It adds $P'$ to the list $M$ of processed parities in Line~\ref{line: mnump'}. There are now two possibilities:
\begin{itemize}
\item If $P'$ does not mark a block (Line~\ref{line: nomark}), then
all variables appearing in $P'$ are already set in $y$ (see \Cref{claim: processedstructure}). Hence $A[\mathsf{num}]$ is set to $\mathsf{val}(P',y)$ (Line~\ref{line: setval}) and the simulation algorithm answers $\mathsf{val}(P',y)+b$ to the original parity query at the current node (Line~\ref{line: setchild}).
\item If $P'$ marks block $j$:
\begin{itemize}
\item If this is the $k$th parity to mark block $j$ (Line~\ref{line: markandkth}), the simulation queries the value of $x_j$ (Line~\ref{line: query}). It then uses the $\mathsf{FINDVARS}$ function to select $k$ bits in the $j$th block to keep unset (Line~\ref{line: freechoice}). It sets the remaining $m-k$ bits of the $j$th block of $y$ using the $\mathsf{STIFLE}_g$ function to ensure that the output of the $j$th block is $x_j$ (Line~\ref{line: setvars}). The stifling property of $g$ is crucially used in this step.
\item The algorithm sets the value of $A[\mathsf{num}]$ (in Line~\ref{line: gotosmallerchild}) such that the simulation algorithm answers the parity query at the current node (Line~\ref{line: setchild}) so as to go to the smaller subtree.
\end{itemize}
\end{itemize}
\end{itemize}
When it reaches a leaf it outputs the value at that leaf.
\begin{algorithm}
\caption{Simulation of a PDT $T$ for $f \circ g$ to obtain a DT for $f$}\label{alg:pdt to dt}
\begin{algorithmic}[1]
\Require $x \in \{0, 1\}^n$
\State $P_0 \gets \textnormal{root}(T)$ \Comment{Starting the simulation of the PDT}
\State{$\mathsf{num} \gets 0$}
\State{$M \gets []$}
\State{$A \gets []$}
\State{$\mathsf{MARK}[i] \gets \emptyset\,\forall i \in [n]$}
\State{$y \gets (*^{m})^{n}$}
\State{$\mathsf{FREE}[i] \gets \cbra{i} \times [m]\,\forall i \in [n]$}
\State{$Q \gets \emptyset$}
\While{$P_\mathsf{num}$ is not a leaf of $T$}\label{line: simulationloop}
\State{$P',b,j \gets$ \textsf{ROW-REDUCE}($P_{\mathsf{num}}, M, A, \mathsf{MARK}, \mathsf{FREE}$)}\label{line: rowreduce}\Comment{Process the current parity query and return the processed query, a correction bit and the index of the marked block.}
\State{$M[\mathsf{num}] \gets P'$}\label{line: mnump'}
\If{$j = \bot$}\label{line: nomark}\Comment{If no block has been marked}
\State{$A[\mathsf{num}] \gets \mathsf{val}(M[\mathsf{num}],y)$}\label{line: setval}\Comment{By Claim~\ref{claim: processedstructure}, all variables appearing in $M[\mathsf{num}]$ have been set in $y$.}
\Else\label{line: elsemarked}
\State{$\mathsf{MARK}[j] \gets \mathsf{MARK}[j] \cup \bra{\mathsf{num}}$}\label{line: markjappend}
\If{$\@ifstar{\oldabs}{\oldabs*}{\mathsf{MARK}[j]} = k$}\label{line: markandkth}\Comment{If this is the $k$th time the $j$th block is marked}
\State{Query $x_j$}\label{line: query}
\State{$Q \gets Q \cup \cbra{j}$}\label{line: updateq}\Comment{Update set of queried variables.}
\State{$S \gets \mathsf{FINDVARS}(\cbra{M[i]|_j : i \in \mathsf{MARK}[j]})$}\label{line: freechoice}\Comment{Select $k$ bits of block $j$ that will remain unset in $y$.}
\State{$y|_j \gets \mathsf{STIFLE}_g(S,x_j)$}\label{line: setvars}\Comment{Set other bits in block $j$ to force the $j$th block to output value~$x_j$. This is possible since~$g$ is $k$-stifled.}
\State{$\mathsf{FREE}[j] \gets \cbra{j} \times S$}\label{line: update free}
\EndIf
\State{$b' \gets \argmin_{a} \textnormal{size}(\textnormal{child}(P_{\mathsf{num}},a))$}\label{line: b'choice}
\State{$A[\mathsf{num}] \gets b'+b$}\label{line: gotosmallerchild}
\EndIf
\State{$P_{\mathsf{num}+1} \gets \textnormal{child}(P_\mathsf{num},A[\mathsf{num}]+b)$}\label{line: setchild}\Comment{If no block was marked (Line~\ref{line: nomark}-\ref{line: setval}), go to the child as dictated by the set variables. Else, go to the child with the smaller subtree, as ensured by Lines~\ref{line: b'choice} and~\ref{line: gotosmallerchild}.}
\State{$\mathsf{num} \gets \mathsf{num} + 1$}
\EndWhile
\State{Output the value output at $P_\mathsf{num}$}
\end{algorithmic}
\end{algorithm}
\subsection{The \textsf{ROW-REDUCE}~subroutine}\label{sec: rowreduce}
We now discuss the \textsf{ROW-REDUCE}~subroutine, which describes how to process an incoming parity and choose which block it should mark.
Algorithm~\ref{alg:rowreduce} takes as inputs $P$,$M$,$A$,$\mathsf{MARK}$,$\mathsf{FREE}$, each of which are described below.
\begin{itemize}
\item $P$ is the new parity query to be processed.
\item The previously processed parity queries are stored in $M$.
\item The answers given in the simulation to the parities in $M$ are stored in $A$.
\item $\mathsf{MARK}[i]$ is the set of indices of parity queries that have the $i$th block marked.
\item $\mathsf{FREE}[i]$ is the set of unset variables in block $i$ in the partial assignment (referred to as $y$ in \Cref{sec: overview simulation}) of the input to $f \circ g$ that the simulation keeps.
\end{itemize}
\begin{algorithm}
\caption{The \textsf{ROW-REDUCE}~routine}\label{alg:rowreduce}
\begin{algorithmic}[1]
\Require $P$,$M$,$A$,$\mathsf{MARK}$,$\mathsf{FREE}$
\State{$\textsf{markedindex} \gets \bot$}
\State{$P' \gets P$}
\State{$b \gets 0$}
\For{$j$ from $1$ to $n$}\label{line: forloop}
\If{$P'|_{\mathsf{FREE}[j]}$ is in the linear span of $\bra{M[i]|_{\mathsf{FREE}[j]}: i \in \mathsf{MARK}[j]}$}\label{line: iflinspan}
\State{Let $S \subseteq \mathsf{MARK}[j]$ be such that $P'|_{\mathsf{FREE}[j]} = \sum_{i \in S} M[i]|_{\mathsf{FREE}[j]}$.}
\State{$P' \gets P' + \sum_{i \in S} M[i]$}\label{line: zeroout}\Comment[.65]{Observe that $P'|_{\mathsf{FREE}[j]} = 0^{\mathsf{FREE}[j]}$ after this step.}
\State{$b \gets b + \sum_{i \in S} A[i]$}\label{line: zerooutb}
\Else\label{line: else}
\State{$\textsf{markedindex} \gets j$}\label{line: setmarkedindex}
\State{\textbf{break}}\label{line: break}\Comment[.65]{Ensure that no more than 1 block is marked.}
\EndIf
\EndFor
\State{\Return{$P',b,\textsf{markedindex}$}}
\end{algorithmic}
\end{algorithm}
The processed parity $P'$ is initialized to $P$, and a correction bit $b$ is initialized to $0$. In Line~\ref{line: forloop}, we go through the blocks of variables in order looking for a block to assign the incoming parity to.
The check made on Line~\ref{line: iflinspan} is to see whether this parity can mark the current block $j$. It cannot mark block $j$ if its restriction to $\mathsf{FREE}[j]$ is in the linear span of the restrictions of earlier parities that marked block $j$. We detail what the algorithm does based on this check below.
\begin{itemize}
\item In Lines~\ref{line: iflinspan} to~\ref{line: zerooutb}, we consider the case where the parity being processed, restricted to the $j$th block, is a linear combination of the restrictions of earlier parities that marked the $j$th block. That is, there is a set $S \subseteq \mathsf{MARK}[j]$ such that $P'|_{\mathsf{FREE}[j]} = \sum_{i \in S} M[i]|_{\mathsf{FREE}[j]}$. In Line~\ref{line: zeroout} we update the parity by adding $\sum_{i \in S} M[i]$ to $P'$. This ensures that $P'|_{\mathsf{FREE}[j]} =0$. Then in Line~\ref{line: zerooutb} we update the correction bit $b$ by adding $\sum_{i \in S} A[i]$ to it. This is so that the following holds for all $y$.
\[ \Big[\mathsf{val}(M[i], y) = A[i]\, \forall i \in [\mathsf{num}]_0\Big] \implies \Big[\mathsf{val}(P, y) = 0 \iff \mathsf{val}(P', y) = b\Big]. \]
\item In Lines~\ref{line: else} to~\ref{line: break}, we consider the case when the current parity restricted to $\mathsf{FREE}[j]$ is not a linear combination of the restrictions of the earlier parities that marked the $j$th block. In this case we have the current parity mark the $j$th block (Line~\ref{line: setmarkedindex}) and then return $P',b,j$.
\end{itemize}
Notice that a block is marked only in the latter case. If this case does not occur for any of the $[n]$ blocks, then no block is marked and the procedure returns $P',b,\bot$.
\subsection{Correctness}\label{sec: correctness}
We first address the fact that we primarily deal with the values of the processed parities rather than the original parity queries from the PDT. The following claim says that answering the processed parity is in fact equivalent to answering the original parity from the PDT.
\begin{claim}\label{clm: processedequivalence}
Let $P',b,j$ be the output of \textsf{ROW-REDUCE}~when run with its first three inputs being $P,M$ and $A$. Let $\mathsf{num}$ be the number of entries in $M$. Then for all $y \in \{0, 1\}^{mn}$,
\[ \Big[\mathsf{val}(M[i], y) = A[i]\, \forall i \in [\mathsf{num}]_0\Big] \implies \Big[\mathsf{val}(P, y) = 0 \iff \mathsf{val}(P', y) = b\Big]. \]\end{claim}
\begin{proof}
The output $P'$ is computed from the input $P$ only through modifications by Line~\ref{line: zeroout} of Algorithm~\ref{alg:rowreduce}. That is, there is some subset $S \subseteq [\mathsf{num}]_0$ such that $P' = P + \sum_{i \in S} M[i]$. The output $b$ is also modified alongside the modifications of $P'$ so that $b = \sum_{i \in S} A[i]$.
Hence for any input $y$, $\mathsf{val}(P',y) = \mathsf{val}(P,y) + \sum_{i \in S} \mathsf{val}(M[i],y)$. The claim immediately follows.
\end{proof}
As a corollary, we get that analyzing inputs that answer all the processed parities according to the answer array $A$ is the same as analyzing inputs that follow the path taken by the PDT simulation.
\begin{corollary}\label{cor: processedsimulation}
The following statement is a loop invariant for the while loop in Line~\ref{line: simulationloop} of Algorithm~\ref{alg:pdt to dt}. For all $y \in \{0, 1\}^{mn}$,
\[ \Big[\mathsf{val}(M[i], y) = A[i]\, \forall i \in [\mathsf{num}]_0\Big] \iff \Big[y \text{ reaches }P_{\mathsf{num}}\Big]. \]
\end{corollary}
\begin{proof}
The loop is initially entered with the array $M$ being empty and $P_{\mathsf{num}}$ being the root of the PDT. Clearly the statement holds at this point. We now prove by induction that it is a loop invariant.
Suppose the statement holds at the beginning of an execution of the loop. $M[\mathsf{num}]$ is populated in this execution by the parity output by the \textsf{ROW-REDUCE}~subroutine in Line~\ref{line: rowreduce}. By Claim~\ref{clm: processedequivalence} and the fact that the statement held at the beginning of the execution, every input $y$ that reaches the node $P_{\mathsf{num}}$ satisfies $\mathsf{val}(M[\mathsf{num}],y) = \mathsf{val}(P_{\mathsf{num}},y) + b$. In Line~\ref{line: setchild} we go to the node $P_{\mathsf{num}+1} = \textnormal{child}(P_{\mathsf{num}},A[\mathsf{num}]+b)$. Hence the inputs that reach $P_{\mathsf{num}+1}$ are exactly those that reach $P_{\mathsf{num}}$ and satisfy $M[\mathsf{num}] = A[\mathsf{num}]$. We then increment $\mathsf{num}$ and the loop ends, so the statement holds at the end of an execution of the loop.
\end{proof}
We now show that the processed parities are very structured.
\begin{claim}\label{claim: processedstructure}
Let $\mathsf{num}$ be the number of queries made by the simulated PDT at a certain point in the simulation. Recall that the processed parities are stored in $M[0]$ to $M[\mathsf{num}-1]$.
\begin{enumerate}
\item Let $i \in [\mathsf{num}]_0$. If the parity $M[i]$ marks block $j$ (i.e., $i \in \mathsf{MARK}[j]$), then for every block $j_1<j$,
\[ M[i] \cap \mathsf{FREE}[j_1] = \emptyset \]
where $M[i]$ is viewed as the set of indices $\cbra{\alpha \in [m] \times [n] : M[i]_{\alpha} = 1}$.\\
If $M[i]$ does not mark any block, then the above holds for all $j_1 \in [n]$.
\item For every block $j \in [n]$, the parities $\bra{M[i]|_{\mathsf{FREE}[j]} : i \in \mathsf{MARK}[j]}$ are linearly independent.
\end{enumerate}
\end{claim}
\begin{proof}
We prove the two properties in order.
\begin{enumerate}
\item We prove the first property by induction on $i$.
\begin{itemize}
\item Let's assume that the property holds for all $i'<i$. Note that $M[i]$ is the processed parity output by \textsf{ROW-REDUCE}~when it was called to process $P_i$. Similarly $j$ is the block marked by \textsf{ROW-REDUCE}~during the same call. During the processing, the algorithm ran through all blocks $j_1 < j$ in order (or $j_1 \leq n$ if no block was marked) and took the branch of Line~\ref{line: iflinspan} of Algorithm~\ref{alg:rowreduce} in each. To prove that $M[i] \cap \mathsf{FREE}[j_1] = \emptyset$ for each $j_1 < j$, we use a second induction on $j_1$.
\begin{itemize}
\item When the algorithm looks at block $j_1$ (i.e., in the $j_1$th iteration of Line~\ref{line: forloop} in Algorithm~\ref{alg:rowreduce}), we assume that the partially processed parity $P'$ has, for each $j_2<j_1$, $P' \cap \mathsf{FREE}[j_2] = \emptyset$. When looking at block $j_1$, the algorithm may process $P'$ further by adding to it some previously processed parities that had marked block $j_1$ (Line~\ref{line: zeroout}). But any previously processed parity would be stored in $M[i']$ for some $i'<i$. By our first induction hypothesis we know that any such $M[i']$ that had marked block $j_1$ has, for each $j_2<j_1$, $M[i'] \cap \mathsf{FREE}[j_2] = \emptyset$. Hence even after adding such parities to $P'$ it still holds that for each $j_2<j_1$, $P' \cap \mathsf{FREE}[j_2] = \emptyset$. The added parities explicitly ensure that $P' \cap \mathsf{FREE}[j_1] = \emptyset$ and so for each $j_2 \leq j_1$, $P' \cap \mathsf{FREE}[j_2] = \emptyset$. This completes the second induction.
\end{itemize}
Since this second induction proves the required statement for all $j_1<j$, this completes the first induction as well.
\end{itemize}
\item For the second property we note that if a processed parity $P'$ marks a block $j$ (Line~\ref{line: setmarkedindex} of Algorithm~\ref{alg:rowreduce}), then $P'|_{\mathsf{FREE}[j]}$ is not in the linear span of $P''|_{\mathsf{FREE}[j]}$ for previous parities $P''$ that have block $j$ marked (since the \textbf{if} condition Line~\ref{line: iflinspan} was not satisfied). Hence the set of parities that mark a block are necessarily linearly independent. Moreover, when $\mathsf{FREE}[j]$ is modified (see Line~\ref{line: freechoice} of Algorithm~\ref{alg:pdt to dt}), it is chosen to be the output of the function $\mathsf{FINDVARS}$ on input $\cbra{M[i]|_j : i \in \mathsf{MARK}[j]}$. By the definition of $\mathsf{FINDVARS}$, this ensures that $\cbra{M[i]|_{\mathsf{FREE}[j]} : i \in \mathsf{MARK}[j]}$ remains linearly independent.
\end{enumerate}
\end{proof}
We finally prove the correctness of the simulation.
\begin{claim}\label{claim: correctness}
For any string $w \in \{0, 1\}^n$ consistent with the queried bits of $x$ there is an input $y$ to $f \circ g$ that reaches the leaf $P_{\mathsf{num}}$ and satisfies $g^n(y) = w$.
\end{claim}
\begin{proof}
Fix a string $w \in \{0, 1\}^n$ consistent with the queried bits of $x$. We start with the partial assignment $y$ maintained by the PDT simulation and complete it.
\begin{itemize}
\item \textbf{Fixing variables in $y$ to ensure $g^n(y) = w$}:
The bits of $y$ that are already fixed ensure that for any queried bit $x_j$, $g(y|_j) = w_j$ (these are set in Line~\ref{line: setvars} of Algorithm~\ref{alg:pdt to dt}).
Now for each unqueried bit $x_j$, first note that $\ell := \@ifstar{\oldabs}{\oldabs*}{\mathsf{MARK}[j]} < k$ (otherwise Line~\ref{line: query} of Algorithm~\ref{alg:pdt to dt} ensures that $x_i$ is queried). We do the following:
\begin{itemize}
\item Get a set $S = \mathsf{FINDVARS}(\cbra{M[i]|_j}_{i \in \mathsf{MARK}[j]})$ of $\ell$ indices such that $\cbra{M[i]|_S}_{i \in \mathsf{MARK}[j]}$ are still linearly independent.
\item Assign $y|_j$ to be $\mathsf{STIFLE}_g(S,w_j)$ to ensure that all the bits of $y|_j$ indexed in $S$ are unset, those outside are set, and all completions of $y|_j$ evaluate to $w_j$ when $g$ is applied to them. This is possible since $g$ is $k$-stifled and $\ell < k$.\footnote{It suffices to assume $\ell \leq k$ here. See \Cref{rmk: improved simulation} for a discussion on how we can modify our simulation to exploit this.} We will continue to use $\mathsf{FREE}[j]$ to refer to the set $S$.
\end{itemize}
Now we are guaranteed that any extension of $y$ with bits set as above will yield the string $w$ when $g^n$ is applied to it.
Before we move on to ensuring that $y$ reaches the leaf $P_{\mathsf{num}}$, let us make the useful observation that at this point $|\mathsf{MARK}[j]| = |\mathsf{FREE}[j]|$ for all $j \in [n]$. We have ensured this for all $j$ that were unqueried by the simulation. For those that were queried, note that the simulation only queries $x_j$ when $|\mathsf{MARK}[j]|=k$, and on querying $x_j$, $\mathsf{FREE}[j]$ is modified to have size $k$ (Lines~\ref{line: markandkth} and~\ref{line: update free} of Algorithm~\ref{alg:pdt to dt}). By Claim~\ref{claim: processedstructure}, we know that $\bra{M[i]|_{\mathsf{FREE}[j]} : i \in \mathsf{MARK}[j]}$ are linearly independent parities. Hence in Algorithm~\ref{alg:rowreduce}, when processing block $j$, Line~\ref{line: iflinspan} will always fire and block $j$ is never marked again. This ensures that $\mathsf{MARK}[j]$ and $\mathsf{FREE}[j]$ do not get modified again.
\item \textbf{Extending $y$ to guarantee that it reaches the leaf $P_{\mathsf{num}}$}:
By \Cref{cor: processedsimulation} the inputs $y$ that reach the leaf $P_{\mathsf{num}}$ are exactly those that answer $A[i]$ to each processed parity query $M[i]$.
We analyze each parity query in $M$. There are two cases: one where the current parity query under consideration marks a block, and the other where the parity query under consideration does not mark a block.
\begin{itemize}
\item \textbf{When $i \notin \bigcup_j \mathsf{MARK}[j]$:} By Claim~\ref{claim: processedstructure} the only non-zero entries of $M[i]$ are variables that have previously been set in $y$ (in Line~\ref{line: setvars} of Algorithm~\ref{alg:pdt to dt}). Hence the parity query $M[i]$ has to evaluate to $\mathsf{val}(M[i],y)$ when queried on any extension of $y$, and indeed $A[i]$ is set to $\mathsf{val}(M[i],y)$ in Line~\ref{line: setval} of Algorithm~\ref{alg:pdt to dt}.
\item \textbf{When $i \in \bigcup_j \mathsf{MARK}[j]$:}
Let $I = \bigcup_j \mathsf{MARK}[j]$. Note that $|I| = \sum_j \@ifstar{\oldabs}{\oldabs*}{\mathsf{MARK}[j]}$ since at most one block gets marked for each parity. Since $\@ifstar{\oldabs}{\oldabs*}{\mathsf{FREE}[j]} = \@ifstar{\oldabs}{\oldabs*}{\mathsf{MARK}[j]}$ for all $j \in [n]$, there are still $\@ifstar{\oldabs}{\oldabs*}{I}$ unset bits of $y$. Let us refer to these variables by $\mathsf{unset}(y)$ and their complement by $\mathsf{set}(y)$.
\newcommand{\mathcal{M}}{\mathcal{M}}
\newcommand{\mathcal{A}}{\mathcal{A}}
\newcommand{b}{b}
Let us now construct a matrix $\mathcal{M} \in \mathbb{F}_2^{I \times [mn]}$ where the rows are indexed by $I$ and row $i$ is the vector $M[i]$. We also consider the column vector $b \in \mathbb{F}_2^{I}$ where the rows are indexed by $I$ and the entry $b_i = A[i]$.
Our goal is to find a column vector $v \in \mathbb{F}_2^{[mn]}$ such that $v_{\mathsf{set}(y)} = y_{\mathsf{set}(y)}$ and $\mathcal{M} v = b$. Setting the unset bits of $y$ according to $v$ would give us what we want, a completion of $y$ that answers $A[i]$ to each parity query $M[i]$. To this end let us write the matrix $\mathcal{M}$ as follows (after an appropriate permutation of columns).
\[
\mathcal{M} = \begin{bmatrix}
\mathcal{A} &| & \mathcal{A}'
\end{bmatrix},
\]
where the first set of columns corresponds to indices in $\mathsf{unset}(y)$, and the second set of columns corresponds to indices in $\mathsf{set}(y)$.
Let $b' = \mathcal{A}'v_{\mathsf{set}(y)}$. If we find a setting of $v_{\mathsf{unset}(y)}$ such that $\mathcal{A} v_{\mathsf{unset}(y)} = b+b'$, then $\mathcal{M} v = b$ and this would conclude the proof. We prove the existence of such a setting by noting below that the rows of $\mathcal{A}$ are independent and hence its image is $\mathbb{F}_2^{I}$. To prove the independence of the rows of $\mathcal{A}$, view $\mathcal{A}$ as a block matrix made up of submatrices $\bra{\mathcal{A}|_{i,j}}_{i,j \in [n]}$ with $\mathcal{A}|_{i,j}$ containing the rows $\mathsf{MARK}[i]$ and columns $\mathsf{FREE}[j]$ (see Figure~\ref{fig: matrix A}). Note that submatrices of the form $\mathcal{A}|_{i,i}$ are square matrices since $\@ifstar{\oldabs}{\oldabs*}{\mathsf{MARK}[i]} = \@ifstar{\oldabs}{\oldabs*}{\mathsf{FREE}[i]}$ for all $i \in [n]$.
\begin{figure}
\centering
\begin{tikzpicture}
\foreach \i in {1,2,4}
\foreach \j in {1,2,4}
{
\node at (1.5*\i,-1.5*\j) {$\mathcal{A}|_{\ifthenelse{\j=4}{n}{\j},\ifthenelse{\i=4}{n}{\i}}$};
}
\foreach \i in {1,2,4}
{
\node at (1.5*3,-1.5*\i) {$\cdots$};
\node at (-0.5,-1.5*\i) {$\mathsf{MARK}[\ifthenelse{\i=4}{n}{\i}]$};
\draw [decorate,decoration = {calligraphic brace}] (0.4,-1.5*\i-0.7) -- (0.4,-1.5*\i+0.7);
\node at (1.5*\i,-1.5*3) {$\vdots$};
\node at (1.5*\i,-0.1) {$\mathsf{FREE}[\ifthenelse{\i=4}{n}{\i}]$};
\draw [decorate,decoration = {calligraphic brace}] (1.5*\i-0.7,-0.6) -- (1.5*\i+0.7,-0.6);
}
\node at (1.5*3,-1.5*3) {$\ddots$};
\draw[thick] (0.75,-0.75) -- (0.6,-0.75) -- (0.6,-6.75) -- (0.75,-6.75);
\draw[thick] (6.75,-0.75) -- (6.9,-0.75) -- (6.9,-6.75) -- (6.75,-6.75);
\end{tikzpicture}
\caption{The structure of the matrix $\mathcal{A}$. $\mathcal{A}|_{i,i}$ is a linearly independent submatrix for each $i \in [n]$, and
$\mathcal{A}|_{i,j}$ is the all-$0$ matrix when $i>j$.}
\label{fig: matrix A}
\end{figure}
By \Cref{claim: processedstructure} and the way we defined $\mathsf{FREE}[i]$ using the $\mathsf{FINDVARS}$ function (ensuring that the restriction of parities in $\mathsf{MARK}[i]$ to $\mathsf{FREE}[i]$ preserves independence),
\begin{itemize}
\item $\mathcal{A}|_{i,i}$ is a linearly independent submatrix for each $i \in [n]$, and
\item $\mathcal{A}|_{i,j}$ is the all-$0$ matrix when $i>j$.
\end{itemize}
The independence of the rows of $A$ easily follows from this `upper triangular'-like structure.
\end{itemize}
\end{itemize}
\end{proof}
We require the following observation for the proof of \Cref{thm: sdt depth lifting} since we work with a slightly modified simulation algorithm there.
\begin{observation}\label{obs: markedanswersirrelevant}
The correctness analysis of Algorithm~\ref{alg:pdt to dt} described in this section still holds if we set $A[\mathsf{num}]$ to $b_{\mathsf{num}} \in \{0, 1\}$ in Line~\ref{line: gotosmallerchild}, where $b_{\mathsf{num}}$ is an arbitrary function of the history of the simulation.
\end{observation}
Finally we observe that the number of queries made by the simulation is at most $d/k$.
\begin{observation}\label{obs: cost}
Algorithm~\ref{alg:pdt to dt} makes at most $d/k$ queries to $x$.
\end{observation}
\begin{proof}
First observe that every parity in the simulation marks at most one block.
The query $x_j$ is made by the simulation (Line~\ref{line: query}) only when $\mathsf{MARK}[j]$ gets $k$ elements in it (Line~\ref{line: markandkth}). So the number of queries made is at most $\@ifstar{\oldabs}{\oldabs*}{\bigcup_{j \in [n]} \mathsf{MARK}[j]}/k \leq d/k$, since the number of iterations in the simulation (captured by $\mathsf{num}$) is at most the depth of the PDT, which is $d$ by assumption.
\end{proof}
It follows from the correctness of \Cref{alg:pdt to dt} and the observation above that $\mathsf{PDT}(f \circ g) \geq \mathsf{DT}(f) \cdot k$ (proving \Cref{thm: pdt depth lifting}). We observe below that our simulation can be modified so as to give a stronger bound of $\mathsf{PDT}(f \circ g) \geq \mathsf{DT}(f) \cdot k + 1$. Note that this bound is tight since $\mathsf{PDT}(\oplus_n \circ \mathsf{IND}_1) \leq n+1$, for instance.
\begin{remark}\label{rmk: improved simulation}
Note that we query $x_j$ in Algorithm~\ref{alg:pdt to dt} when the $j$th block is marked for the $k$th time. The reason behind this is that we can handle a block being marked $k$ times while still having the freedom to set its output by the stifling property of $g$. Moreover this might not be true after the block is marked for the $(k+1)$th time. However querying $x_j$ in \emph{the same iteration} where the $j$th block is marked for the $k$th time (Lines~\ref{line: markandkth} and~\ref{line: query}) is premature. We can modify our algorithm so as to query $x_j$ after block $j$ is marked $k$ times \emph{and} a new parity \emph{attempts to} mark it for the $(k+1)$th time. With this modification, once we query $x_j$ and set variables so that its output is fixed, the parity can no longer mark block $j$ and needs to be reprocessed using Algorithm~\ref{alg:rowreduce} with the updated value of $\mathsf{FREE}[j]$ so that it either triggers a query in a later block (in which case we repeat this process), marks a later block, or marks no block at all. If the set of queries to $x$ is denoted by $Q$, then the number of parity queries being made by the simulation is at least $|Q|k + 1$: When the last of the queries in $Q$ is made, say $x_j$, then the $j$th block and all blocks corresponding to previously queried variables had already been marked $k$ times \emph{before} the parity query appeared that triggered the query of $x_j$. Hence there were at least $|Q|k$ parity queries processed \emph{before} the parity query that resulted in the simulation querying $x_j$. As a result we get
\[
\mathsf{PDT}(f \circ g) \geq \mathsf{DT}(f) \cdot k + 1.
\]
\end{remark}
\subsection{Simulation theorems}\label{sec: all simulation theorems}
In this section we conclude the proofs of \Cref{thm: pdt depth lifting}, \Cref{thm: sdt depth lifting}, \Cref{thm: pdt size lifting}, \Cref{cor: indexing lifting} and \Cref{cor: ip lifting}.
\begin{proof}[Proof of \Cref{thm: pdt depth lifting}]
It follows from the correctness of Algorithm~\ref{alg:pdt to dt} described in the previous section, and Observation~\ref{obs: cost}.
\end{proof}
\begin{proof}[Proof of \Cref{thm: pdt size lifting}]
Consider a PDT $T_P$ for $f \circ g$ of size $s$. Suppose the DT $T$ we get for $f$ from the simulation makes $d$ queries on a worst-case input, say on $x \in \{0, 1\}^n$.
Note that whenever a parity marks a block in the simulation algorithm (i.e., Line~\ref{line: elsemarked} fires), the algorithm then chooses to go to the child with the smaller subtree (Lines~\ref{line: gotosmallerchild} and~\ref{line: setchild}). So in Line~\ref{line: setchild}, the size of the subtree rooted at $P_{\mathsf{num}+1}$ is at most half the size of the subtree rooted at $P_{\mathsf{num}}$.
When the simulation algorithm is run on input $x$, it reaches a leaf of $T_P$, and at least $dk$ parities are such that they mark some block in the process. This is because the simulation queries a variable only after its corresponding block has been marked $k$ times. Hence the size of the subtree rooted at the reached leaf is at most a $2^{-dk}$ fraction of $s$. Thus, $s \geq 2^{dk}$. The theorem now follows from the correctness of Algorithm~\ref{alg:pdt to dt} described in the previous section.
\end{proof}
Towards the proof of \Cref{thm: sdt depth lifting}, we work with a modified query model instead of considering subspace decision trees. This query model is described below.
For each affine subspace choose an arbitrary ordering of the constraints.
We define a `parity constraint' query to be a query of the form $\ip{v}{x}\stackrel{?}{=} a$ where $v \in \mathbb{F}_2^{mn}, a \in \mathbb{F}_2$.
Define a `parity constraint' query protocol as a protocol that makes parity constraint queries. The answer to a query $\ip{v}{x}\stackrel{?}{=} a$ is either `Right' if $\ip{v}{x}=a$ or `Wrong' if $\ip{v}{x} \neq a$. The cost of the protocol is defined to be the worst-case number of queries that were answered `Wrong' during a run of the protocol.
Now given a subspace decision tree $T$, we construct a parity constraint query protocol as follows:
\begin{itemize}
\item When an affine subspace query is made in $T$, instead query the parity constraints making up the affine subspace query in a canonical order. Stop when any of the parity constraints is answered `Wrong'.
\item If a constraint has been answered `Wrong', traverse $T$ as if the affine subspace query had failed. If no constraint has been answered `Wrong', traverse $T$ as if the affine subspace query had succeeded.
\end{itemize}
Clearly the number of wrong answers in any execution of this protocol is upper bounded by the worst case number of affine subspace queries made by $T$, and the parity constraint protocol computes the same relation as the original subspace decision tree.
\begin{proof}[Proof of \Cref{thm: sdt depth lifting}]
From a subspace decision tree computing $f \circ g$, construct a parity constraint query protocol $T$ computing $f \circ g$ without increasing the cost, as described above.
Note that a parity constraint query protocol tree is just a parity decision tree except that for every internal node its outgoing edges have an extra label of `Right' and `Wrong'.
We modify Lines~\ref{line: b'choice} and~\ref{line: gotosmallerchild} of Algorithm~\ref{alg:pdt to dt} as follows. We look at the current query node in the PDT to see what answer $b' \in \mathbb{F}_2$ corresponds to a `Wrong' edge. We set $A[\mathsf{num}]$ to $b' + b$ so that in Line~\ref{line: setchild} the simulation does take the `Wrong' edge.
Hence for every $i \in \bigcup_{j \in [n]} \mathsf{MARK}[j]$, the parity query $M[i]$ corresponds to a `Wrong' answer. Thus note that cost$(T) \geq \@ifstar{\oldabs}{\oldabs*}{\bigcup_{j \in [n]} \mathsf{MARK}[j]}$. On the other hand, the query $x_j$ is made by the simulation only when $\mathsf{MARK}[j]$ gets $k$ elements in it. So the number of queries made is at most $\@ifstar{\oldabs}{\oldabs*}{\bigcup_{j \in [n]} \mathsf{MARK}[j]}/k \leq \text{cost}(T)/k$. The correctness of this modified algorithm follows from the correctness of Algorithm~\ref{alg:pdt to dt} described in the previous section, along with Observation~\ref{obs: markedanswersirrelevant}.
\end{proof}
\Cref{cor: indexing lifting} and \Cref{cor: ip lifting} follow from \Cref{thm: pdt depth lifting}, \Cref{thm: sdt depth lifting}, \Cref{thm: pdt size lifting}, the fact that $\mathsf{IND}_m$ is $m$-stifled (Claim~\ref{claim: ind property p}) and the fact that $\mathsf{IP}_m$ is $1$-stifled (\Cref{claim: ip stifled}).
\subsection{Non-adaptive and round-respecting simulations}
When run on a non-adaptive parity decision tree for $f \circ g$ of cost $d$, our simulation algorithm actually results in a non-adaptive decision tree for $f$ of cost $d/k$. This observation relies on the fact that in the course of every iteration (of Line~\ref{line: simulationloop} of Algorithm~\ref{alg:pdt to dt}), the updates done to $M, \mathsf{MARK}, Q$ and $\mathsf{FREE}$ depend solely on the sequence of parities $P$ that are processed. More formally,
\begin{itemize}
\item The outputs $P'$ and $j$ from the $\textsf{ROW-REDUCE}$ routine are functions of $P,M,\mathsf{MARK},k$ and $\mathsf{FREE}$. They \emph{do not} depend on the input $A$. $M$ and $\mathsf{MARK}$ are then updated depending solely on these outputs.
\item The decision to query a variable $x_j$ (and hence to append $j$ to $Q$, in Lines~\ref{line: query} and~\ref{line: updateq} of Algorithm~\ref{alg:pdt to dt}) depends only on $\mathsf{MARK}$, and the resulting update to $\mathsf{FREE}[j]$ (Line~\ref{line: update free} and the two preceding lines of Algorithm~\ref{alg:pdt to dt}) only depends on $M$ and $\mathsf{MARK}$.
\end{itemize}
Now consider a run of the simulation algorithm on a non-adaptive PDT. By Observation~\ref{obs: cost} this results in a DT that computes $f$ with cost at most $d/k$. By the observations above and since the parity decision tree is non-adaptive, the simulation algorithm processes the same sequence of parity queries regardless of what path it takes down the non-adaptive PDT. Hence the set $Q$ (and hence the queries made) does not depend on what path the simulation algorithm takes, and they can be made non-adaptively. Thus, we obtain the following theorem where $\mathsf{NADT}(\cdot)$ denotes non-adaptive decision tree complexity and $\mathsf{NAPDT}(\cdot)$ denotes non-adaptive parity decision tree complexity.
\begin{theorem}\label{thm: nonadaptive}
Let $g:\{0,1\}^m \to \{0,1\}$ be a $k$-stifled function, and let $f \subseteq \{0, 1\}^n \times \mathcal{R}$ be a relation. Then,
\[
\mathsf{NAPDT}(f \circ g) \geq \mathsf{NADT}(f) \cdot k.
\]
\end{theorem}
This argument can easily be adapted to say that when run on a `$t$-round' PDT (that is, parity queries are done simultaneously in each round), the simulation algorithm results in a $t$-round DT with the guarantee that if the parity decision tree has made at most $d_i$ queries during its first $i$ rounds, the decision tree makes at most $d_i/k$ queries during its first $i$ rounds.
| {'timestamp': '2022-12-01T02:20:42', 'yymm': '2211', 'arxiv_id': '2211.17214', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17214'} | arxiv |
\section{Discussion}
POD showed a response close to the original ESN for both the NARMA and the two wells/one riser case studies, and a very minor loss in MC during the reduction. However, this was not shown to be the case when DEIM was applied.
There seems to be more loss of dynamic information when DEIM is performed than when POD is, as POD retains the number of activation functions being computed even though the number of states is diminished.
\eric{Thus, we conjecture that the capacity of a reservoir to represent accurately a nonlinear system is more influenced by the combination of the nonlinear functions in a high-dimensional space (in the context of MOR, given by the projection of the reduced states back to the original space, just before applying the $\tanh$ nonlinearity) than maintaining a high-dimensionality of the reservoir states themselves.}
In terms of memory, however, there is some reduction resulting from the application of POD.
First, the state-to-output linear combination matrix $\mathbf{W_r^oT}$ diminishes in size and maps the reduced space directly to the output.
Also, the computation of the activation function becomes slightly less expensive memory-wise because of the term $\mathbf{W_r^rT}$, as this offline-computed product results in a matrix with less elements overall.
Of course, the resulting matrix is still larger in comparison to an ESN with the same size as the reduction, which makes the same-size ESN less complex than the POD-reduced one.
Even though POD computes the same number of activation functions as the original ESN, the computation time is significantly reduced, as shown in Table \ref{tab:narma_time}.
This table shows the mean time it took to execute a step in the full ESN against the time it took to execute a POD-ESN computation step, for the NARMA experiment.
\eric{For instance, when applying POD-ESN to reduce from 1400 states to 66 states, we get an 80\% decrease in mean execution time (from 0.767 ms to 0.147 ms), while still maintaining a very good performance, as this setup is near the horizontal line in Figure ~\ref{fig:pod_narma}.}
All experiments were performed under \eric{similar conditions, with} the same computer.
\begin{table}[h!]
\centering
\caption{Mean execution time for the NARMA experiment composed of $5,000$ time steps.}
\begin{tabular}{|c|c|c|}\hline
& Mean Execution Time (ms)& St. Dev. (ms)\\\hline
ESN\;(size=1400) & 0.767 & 0.537\\\hline
POD\;(size=3) & 0.072 & 0.0498\\\hline
POD\;(size=6) & 0.078 & 0.0251\\\hline
POD\;(size=7) & 0.141 & 0.391\\\hline
POD\;(size=8) & 0.131 & 0.340\\\hline
POD\;(size=9) & 0.160 & 0.543\\\hline
POD\;(size=10) & 0.140& 0.467\\\hline
POD\;(size=11) & 0.233 & 0.955\\\hline
POD\;(size=13) & 0.105 & 0.122\\\hline
POD\;(size=17) & 0.106 & 0.0738\\\hline
POD\;(size=30) & 0.135 & 0.0856\\\hline
POD\;(size=66) & 0.147 & 0.254\\\hline
POD\;(size=73) & 0.144 & 0.138\\\hline
POD\;(size=82) & 0.141 & 0.140\\\hline
POD\;(size=92) & 0.155 & 0.109\\\hline
POD\;(size=106) & 0.151 & 0.0744\\\hline
POD\;(size=123) & 0.149 & 0.0907\\\hline
POD\;(size=149) & 0.183 & 0.407\\\hline
POD\;(size=186) & 0.201 & 0.145\\\hline
POD\;(size=248) & 0.230 & 0.134\\\hline
POD\;(size=375) & 0.408 & 0.199\\ \hline
\end{tabular}
\label{tab:narma_time}
\end{table}
As shown in Table \ref{tab:narma_time}, even though there is no computation reduction in the nonlinear nodes, the computational time for a POD-ESN to compute a time step is actually diminished, even if by a small margin.
The loss of stability incurred in ESNs by DEIM, as previously discussed, was corroborated by their poor performance achieved in the Memory Capacity experiments.
Besides, even when the DEIM-reduced ESN dynamic system remained stable, as in the two-well experiment illustrated in Figure \ref{fig:twowells_plot}, the system experienced high overshoots which translates into modeling error.
The independent work \cite{Wang2022} that also implements POD/DEIM on ESN, which appeared in the literature during the writing of this research, proposes a method to deal with the stability issue.
However, the method is restricted to the special class of ESNs with dynamic equations without the bias term.
That method relies on expanding the nonlinear dynamics reduced by the DEIM, so that the Jacobian contribution of the terms affected by $(\mathbf{P}^T\mathbf{U})$ becomes null with respect to $\mathbf{u}=\mathbf{0}$.
In this context, generalized methods (that take into account the bias term as well) to guarantee stability retention of an ESN interpolated by DEIM are an interesting topic for future works.
\section{Conclusion} \label{sec:conclusion}
\eric{In this investigation,} the POD was shown to achieve exceptional results in terms of reducing the number of states of an ESN and maintaining performance.
The reduced ESN managed to perform almost as well as the original ESN, despite the the drastic reduction of states in a normal system identification task.
This work also showcased how the nature of the excitation signal changes the singular value profile of the SVD, concluding that more efficient reductions can be performed for lower frequency input signals.
This is to say that, ideally, the excitation signal for a system to be identified should be as slow as necessary.
In addition, the memory capacity test was performed with signals that carry information from all frequencies, and even then the reduced network showcased better performance than an ESN of the same size trained on the data.
\eric{This happens arguably because the POD-reduced ESN emulates the behavior of the larger original ESN from which it was reduced, and also for its more complex structure when compared to a same size ESN.}
\section*{Acknowledgements}
Funding: This work was supported by Coordenação de Aperfeiçoamento de Pessoal de Nível Superior (CAPES); and Fundação de Amparo à Pesquisa e Inovação do Estado de Santa Catarina (FAPESC) [grant number 2021TR2265].
\section{Applications} \label{sec:app}
This section presents results from experiments carried out with reduced-order ESNs for three case studies.
\subsection{Preliminary Study: Energy contribution distribution in Echo State Networks}
POD and DEIM both originate from applying SVD into the ESN state response \eric{matrix},
\eric{which in turn is obtained from exciting the ESN's reservoir with an input signal.
Thus, the SVD does not depend on the output layer.}
To test the influence of input signals into the singular values of the state snapshots, we initialize $20$ different single-input ESN reservoirs and apply SVD into the snapshots of the response obtained from the reservoir, given as inputs
\eric{with}
$10,000$ timesteps:
\begin{itemize}
\item A white noise following the normal distribution $\mathcal{N}(0,1)$.
\item Four different APRBS (Amplitude-modulated Pseudo-Random Binary Signal) random stair signals, defined by their minimum period, i.e., $10$ timesteps, $100$ timesteps, $500$ timesteps, and $1,000$ timesteps.
\item A concatenation in time of all the signals above.
\end{itemize}
The input signals for the experiments are shown in Figure \ref{fig:svd_input}.
Note that this discussion concerns only the state dynamics of the reservoir, therefore it is neither dependent on a system to be identified, nor on the output weights.
\begin{figure}
\centering
\includegraphics[width=0.85\textwidth]{figures/input_signals_svd.eps}
\caption{\eric{One-dimensional} input signals for the reservoir energy contribution distribution experiment.
\eric{White noise (top), APRBS signals (usually used in identification tasks): with mininum period of 10, 100, 500, and 1,000 timesteps, respectively, from second topmost plot to bottom.}
}
\label{fig:svd_input}
\end{figure}
\eric{After exciting the ESN with the aforementioned signals, one at a time, we perform SVD of the resulting ESN state response snapshots and} plot the energy contribution $\epsilon_j$ associated with each singular value, sorted from highest to lowest according to Eq. \eqref{eqn:energy_contribution}.
All the reservoirs employed for this experiment are fully leaked ($\gamma = 1$), have $500$ neurons, a spectral radius $\rho = 0.99$, and a value $0.1$ for both input scaling and bias scaling.
\begin{figure}
\centering
\includegraphics[width=0.85\textwidth]{figures/svd_plot.eps}
\caption{Mean and Standard deviation of the first ordered $10$ singular values (with $0$ corresponding to the highest, and $9$ to lowest) obtained from the snapshots of $20$ different ESN reservoirs. Each color corresponds to a different input signal fed to the ESN reservoir, shown in Fig. \ref{fig:svd_input}.}
\label{fig:ec_profile}
\end{figure}
Figure \ref{fig:ec_profile} showcases the mean and standard \eric{deviation of the} energy contribution of the $10$ highest singular values
\eric{for each state snapshot}
\eric{considering $20$ randomly} initialized reservoirs.
We infer from this result that the singular values are more evenly distributed the higher the frequencies of the input signal are.
As the white noise is a signal with heavy high frequency information, the ESN state response is expected to have a more even energy contribution distribution among the singular values.
Meanwhile, the lower frequency signals have the energy contribution concentrated about the highest magnitude singular value.
In fact, real-life dynamic systems work as low pass filters \cite{Chen} and, therefore, they are expected to have lower frequency information.
The slower the dynamics of a system are, the larger the minimum period of an APRBS signal needs to be, which directly affects the singular value profile of the model order reduction.
The implication of this experiment is that, since the distribution of the energy contribution depends entirely on the input signal frequency, the number of states that can be pruned for MOR is higher for cases with low frequency dynamics.
As an easy example, the highest energy contribution singular value for APRBS signal with minimum period of $1,000$ timesteps contributes more to the total energy of the snapshots than the \eric{sum of the $10$ highest} singular values for the white noise shown in the plot.
\subsection{Memory Capacity Evaluation}
Short-term Memory Capacity (MC) is a well known metric for Echo State Networks \cite{memory_jaeger} \eric{that} measures how well an ESN can remember past inputs and general dynamic storage capacity.
MC serves as a performance measurement for a given ESN reservoir, which is obtained from the following procedure:
\begin{itemize}
\item For an arbitrary $n$, train a single-input, single-output Echo State Network so that the input is a given white noise $\mathbf{\eta}[k]$, and the output is the same white noise delayed $n$ timesteps $\mathbf{\eta}[k-n]$.
%
In layman's terms, the ESN is supposed to ``memorize'' the input \eric{from} $n$ timesteps ago.
\item Obtain the correlation coefficient $R_n$ for the training with an arbitrary $n$,
\begin{equation}
R_n = \frac{{\tt cov}(y_{esn},\mathbf{\eta}[k-n])}{{\tt var}(\mathbf{y_{esn}}){\tt var}(\eta[k-n])}
\end{equation}
where ${\tt cov}(\cdot)$ is the covariance operator, $y_{esn}$ is the single ESN output, ${\tt var}(\cdot)$ is the variance operator, and, therefore, $R_n$ is merely the determination coefficient for a given delay $n$.
\item The memory capacity is calculated, in theory, as:
\begin{equation}
MC = \sum_{n=1}^{\infty}R_n
\end{equation}
\end{itemize}
The MC of an ESN was mathematically proven to have an upper bound in its number of neurons $N$ \cite{memory_jaeger}, which means that it is directly related to the number of network neurons.
For this work, we propose an experiment to compare the memory capacity of the reduced order model of the ESN, and the original ESN, as the number of neurons is directly tied to the upper bound.
Since it is impossible to make infinite training experiments, we define the memory capacity for this experiment as follows:
\begin{equation}
MC = \sum_{n=1}^{N_{MC}}R_n
\end{equation}
where $N_{MC}=100$ is a large enough number to measure the memory capacity of the network. As preliminary tests show, after a given $n$, the determination coefficient converges to a low value. Therefore, the information regarding memory capacity is more concentrated in the lower $n$ spectrum, endorsing the limited number of experiments ($N_{MC} = 100$) for comparison purposes.
\subsubsection{POD reduction}
We ran the memory capacity experiment for different numbers of neurons ($N = \{400,600,800, 1000, 1200, 1400, 1600, 1800, 2000, 2200 \}$) with an Energy Cutoff (EC) of $1\%$, $5\%,$ and $10\%$.
Since the reservoir of an ESN is initialized at random, we perform model order reduction for $12$ different reservoirs in each configuration.
We then measure the mean and standard deviation for the memory capacity of these $12$ runs, while also obtaining the range of the reduced dimension for a given energy cutoff.
This allows us to measure not only the memory capacity drop for the model order reduction, but also how reservoir-dependent the reduction procedure is.
All reservoirs analyzed are fully leaked ($\gamma = 1.0$), and have input and bias scaling at $0.1$.
Also, the reservoir spectral radius is $\rho = 0.99$.
\begin{figure}
\centering
\includegraphics[width=0.78\textwidth]{figures/mc_experiment_x.eps}
\caption{Plot of the memory capacity as a function of the number of neurons of the original network (upper plot), and as a function of the number of states (lower plot).
Each point is colored according to the energy cutoff of the POD-ESN that obtained the MC shown (points in blue are the MC obtained from full ESNs). EC means the energy cutoff of the applied POD.}
\label{fig:mc_experiment_podvsfull}
\end{figure}
Figure \ref{fig:mc_experiment_podvsfull} showcases the results of the Memory Capacity experiments
\eric{when}
performing MOR at the tested ESNs given different energy cutoffs, depicting both mean and standard deviation of the $12$ runs.
The first plot is depicted in terms of the number of ESN neurons before applying POD to a given network.
It shows the \eric{expected} drop in MC as MOR is performed with more energy cutoff.
Meanwhile, the second plot portrays the MC as a function of the exact number of states of a given network after performing MOR through POD.
As MC progresses monotonically given the number of states, either in an ESN or in a given MOR of that ESN, it becomes easy to map a point of the second plot into the first one: for example, the last red point
\eric{(from left to right)}
of both plots (marked within a blue circle)
have the same memory capacity since they
correspond to the same network/EC configuration.
Thus, the MOR of an ESN with $2200$ neurons (first plot) has roughly $750$ states (second plot) at 1\% energy cutoff.
As per the previous section, since a white noise signal is traditionally employed for this experiment, the drop in the number of reduced states is not very significant, however the drop in MC is still small given that a large number of states were still cut off (even in the case of $10\%$ energy cutoff for the $2200$ neurons case, the number of states was reduced to almost a third).
In fact, the second plot shows that a POD-reduced network ends up being more powerful in terms of MC than a full \eric{(non-reduced)} ESN with the same number of states.
Of course, the better performance is justifiable in that a POD-reduced ESN is still more structurally complex than a smaller ESN with the same number of neurons.
\subsubsection{DEIM reduction}
We also performed DEIM for each POD-ESN obtained, to further reduce the number of $\tanh$ in the computations and evaluate the drop in MC in comparison to the POD-reduced ESN.
We tested four different energy cutoff configurations for the DEIM: $\{1\%,5\%,10\%,20\%\}$.
\begin{table*}[]
\centering
\caption{
Memory capacity evaluated for different energy cutoffs used in POD and DEIM. Each table considers an original ESN of different size $N$, to be reduced.
}
\begin{tabular}{|c|c|c|c|c|c|}\hline
$N=800$ & \multicolumn{5}{c|}{Energy Cutoff (EC) for DEIM} \\\hline
EC (POD) & $0\%$ &$1\% (678)$ & $5\% (430)$ & $10\% (279)$ & $20\% (128)$ \\\hline
$0\% (800)$ & $19.88 \pm 0.01$ &$-$ & $-$ & $-$ & $-$ \\\hline
$1\% (686)$ & $19.87 \pm 0.01 $ & $0.44 \pm 0.20$ & $0.099 \pm 0.01$ & $0.08 \pm 0.04$ & $0.54 \pm 0.18$ \\\hline
$5\% (445)$ & $19.86 \pm 0.01 $ &$ 16.48 \pm 2.21$ & $0.059 \pm 0.026$ & $0.096 \pm 0.02$ & $0.55 \pm 0.17$ \\\hline
$10\% (291)$ & $19.84 \pm 0.008 $ &$19.68 \pm 0.03$ & $0.99 \pm 0.25$ & $0.097 \pm 0.02$ & $0.54 \pm 0.18$ \\\hline
\multicolumn{6}{c}{}
\end{tabular}\\
\begin{tabular}{|c|c|c|c|c|c|}\hline
$N=1,400$ & \multicolumn{5}{c|}{Energy Cutoff (EC) for DEIM} \\\hline
EC (POD) & $0\%$ &$1\% (1,186)$ & $5\% (748)$ & $10\% (484)$ & $20\% (226)$ \\\hline
$0\% (1,400)$ & $19.93 \pm 0.003$ &$-$ & $-$ & $-$ & $-$ \\\hline
$1\% (1,119)$ & $19.93 \pm 0.003$ &$0.11 \pm 0.03$ & $0.03 \pm 0.03$ & $0.04 \pm 0.02$ & $0.17 \pm 0.05$ \\\hline
$5\% (772)$ & $19.91 \pm 0.003$ &$3.189 \pm 1.09$ & $0.03 \pm 0.02$ & $0.04 \pm 0.02$ & $0.17 \pm 0.04$ \\\hline
$10\% (505)$ & $19.90 \pm 0.003$ &$19.18 \pm 0.50$ & $0.19 \pm 0.02$ & $0.025 \pm 0.02$ & $0.17 \pm 0.05$ \\\hline
\multicolumn{6}{c}{}
\end{tabular}\\
\begin{tabular}{|c|c|c|c|c|c|}\hline
$N=2,000$ & \multicolumn{5}{c|}{Energy Cutoff (EC) for DEIM} \\\hline
EC (POD) & $0\%$ &$1\% (1,835)$ & $5\% (1,122)$ & $10\% (713)$ & $20\% (333)$ \\\hline
$0\% (2,000)$ & $19.96 \pm 0.002$ &$-$ & $-$ & $-$ & $-$ \\\hline
$1\% (1,682)$ & $19.95\pm 0.002$ &$0.06 \pm 0.01$ & $0.02 \pm 0.02$ & $0.03 \pm 0.01$ & $0.03 \pm 0.03$ \\\hline
$5\% (1,045)$ & $19.94\pm 0.002$ &$1.2 \pm 0.4$ & $0.01 \pm 0.02$ & $0.02 \pm 0.02$ & $0.08 \pm 0.03$ \\\hline
$10\% (671)$ & $19.92\pm 0.002$ &$18.37 \pm 0.90$ & $0.09 \pm 0.03$ & $0.04 \pm 0.01$ & $0.07 \pm 0.03$ \\\hline
\end{tabular}\\
\label{tab:deim_results}
\end{table*}
Table \ref{tab:deim_results} shows the results of applying these DEIM configurations into each POD for \eric{three original reservoir sizes} $N = \{800,1400,2000\}$ \eric{(from topmost table to the bottom-most one, respectively)}.
It presents the results for the DEIM reduction, where the memory capacity is evaluated for each configuration in energy cutoff for both POD and DEIM. The number in parenthesis is the actual dimension \eric{resulting from} the reduction. Each column corresponds to a different energy cutoff configuration for DEIM, evaluated in the first row, while each row represents a different energy cutoff configuration for POD, evaluated in the first column.
\eric{For instance, the MC of an ESN with a $1\%$ energy cutoff POD (yielding $1,119$ states when $N=1,400$) and a $5\%$ energy cutoff DEIM (yielding $748$ $\tanh$ function evaluations when $N=1,400$) is 0.099, 0.03 and 0.02 for $N=800, 1400, 2000$ respectively.}
\eric{Notice that there was no POD reduction for the first row of each table, as well as no DEIM reduction for the first column of each table. The empty cells refer to the fact that DEIM can not be employed without first applying the POD reduction.
}
The only time DEIM managed to actually represent relatively well the MOR was when there was an $1\%$ energy cutoff for DEIM considering $10\%$ energy cutoff for POD.
That is, DEIM is actually being performed for smaller reduced order models.
In general, performance is mildly better whenever DEIM has a higher number of states ratio in comparison to the POD states.
For this experiment, DEIM was not expected to perform well, as the white noise signal does not allow for a great reduction of states, as it is a highly heavy information signal.
\subsection{NARMA System}
As an initial case study for the POD reduction of the ESN, we try to identify the behavior of a so-called NARMA (Nonlinear Autoregressive Moving Average) difference equation system \cite{Sakemi2020}, equated as follows:
\begin{multline} \label{eqn:narma}
y[k] = 0.3y[k-1] +0.05y[k-1]\sum_{i=1}^m y[k-i] \\+ 1.5u[k-m+1]u[k] + 0.1
\end{multline}
where $m=10$ is the order of the system.
As in \cite{Sakemi2020}, the excitation signal applied in \eqref{eqn:narma} is drawn from the random uniform distribution with value range of
$0 \leq u[k] \leq 0.05$.
A simulation of $5,000$ time steps is performed where
\eric{the first 2,000 samples} are labeled as training data and the rest is labeled as test data.
In this work, the $R^2$ metric is employed to measure network performance.
With the aforementioned dataset, we train an ESN with \eric{the following configuration:}
$1,400$ neurons
\eric{in the reservoir layer,
high enough so that we show the MOR potential at work;
}
a leak rate of $\gamma = 0.7$;
\eric{scaling of $0.1$ for both bias and input connections}; and spectral radius of $\rho = 0.99$.
In terms of $R^2$, the network had a performance of $0.95949337$ for the NARMA model output.
We will now carry out experiments of POD for this network to evaluate how the MOR performs in terms of $R^2$ in relation to the original $1,400$ units network.
\begin{figure}
\centering
\includegraphics[width=0.85\textwidth]{figures/narma_pod_r2.eps}
\caption{Experiment
\eric{comparing a POD-reduced ESN (blue dots) with a ESN of equivalent size (to the reduced ESN) (orange triangles) for the 10th order NARMA task. The POD reduction is applied on a ESN with $1,400$ units in the reservoir.}
%
\eric{The horizontal axis is the number of states (units) of the reduced (full) network, while the vertical axis is the $R^2$ metric on test set.}
The $R^2$ of the $1,400$ units ESN is also plotted as a \eric{blue horizontal} line for comparison.
%
}
\label{fig:pod_narma}
\end{figure}
Figure \ref{fig:pod_narma} showcases the experiment with POD reduction being performed so that the ESN is reduced to the number of states in the $x$ axis (blue dots).
For comparison, we also plotted the $R^2$ for the exact same NARMA experiment with $10$ runs of full
\eric{(non-reduced) ESNs which have the same reservoir size as the networks that underwent POD reduction}(orange triangles).
The POD-ESN reduction generally achieved superior performance over the full ESN at the same \eric{reservoir} size, which is understandable, as the POD-ESN is not only supposed to be an emulation of a larger ESN behavior, but is also more complex in structure.
\eric{The NARMA experiment also show that the $R^2$ metric for ESNs reduced to at least $50$ states is very similar to the metric achieved by the original 1,400 units ESN, i.e., the blue dots are very close to the horizontal blue line in the plot of Figure \ref{fig:pod_narma} when the number of states is higher than 50.}
\subsection{Two Wells and One Riser Platform}
We now test the MOR over the ESN for a physical problem: an oil production platform consisting of two gas-lifted oil wells and one riser, as illustrated in Figure \ref{fig:schematic}.
To gather data, we utilize a composite model between two well models, a riser model, and a manifold that serves as a connector to the three units.
All models assume a 2-phase fluid containing gas and liquid.
The well model assumes two control volumes in the gas injection annulus and the production tubing, with boundary conditions for: gas-lift pressure, reservoir pressure, and outlet pressure.
The riser model considers a horizontal pipeline and the vertical portion of the riser as two separate control volumes, and assumes the inlet flow, and outlet pressure as boundary conditions.
The manifold assumes no load loss due to friction, therefore it equates each well output flow to the riser input flow, and the riser inlet pressure.
Overall, the whole system has 120 algebraic variables, 10 state variables,
5 input variables, and exactly 5 boundary conditions.
\begin{figure}[!b]
\centering
\includegraphics[width=0.8\textwidth]{figures/schematic.eps}
\caption{Representation of an oil platform containing two wells and one riser.
From \cite{jordanou_eaai}.
}
\label{fig:schematic}
\end{figure}
The well is modeled as described with more details in \cite{esmaeil}, while the riser model is described in \cite{jahanshahi2011}.
The model configuration is exactly the same as the one described in \cite{jordanou_ieee}.
The reader can refer to these works for more details on the mathematical modeling of the platform.
The experiment with the two-well production platform is used to depict how to achieve MOR \eric{with ESNs} from a system identification standpoint.
First, we must train an ESN model for the two-well and one-riser platform.
We \eric{generate $50,000$ timesteps of data from numerical simulation of the platform model, yielding a dataset where the 2-dimensional input to the ESN is composed of both well production chokes $u_{ch,1}$ and $u_{ch,2}$, while the desired 2-dimensional output of the network corresponds to each well bottom-hole pressure: $P_{bh,1}$, $P_{bh,2}$.
The training dataset consist of the first $10,000$ timesteps, while the segment from $k = 20,000$ to $k = 30,000$ is used as a validation set, and the rest ($k > 30,000$) as a test set.}
With the described dataset, we train an ESN with $1,400$ reservoir units (chosen this high for the sake of demonstrating the MOR potential at work), a leak rate of $\gamma = 0.7$, scalings for both bias and input \eric{equal to} $0.1$, and spectral radius $\rho = 0.99$.
In terms of $R^2$ \eric{metric}, the network had a \eric{test} performance of $(0.99881673,0.99900379)$ for each \eric{individual} well bottom-hole pressure.
Now, we will run POD experiments with the \eric{previously trained} network to assess how MOR performs in terms of $R^2$ in relation to the original $1,400$ units network.
\begin{figure}
\centering
\includegraphics[width=0.85\textwidth]{figures/pod_test_twowells.eps}
\caption
\eric{POD-ESN for a system identification task.
The full ESN} network has $1,400$ neurons, which was trained to model the platform with two wells and one riser.
%
The $x$ axis is the number of states of the reduced network, whereas the $y$ axis is the $R^2$ \eric{metric on}
the test set
\eric{for each individual} output variable (\eric{bottomhole pressures}). The bottom-hole pressure of the first well is represented in blue color, while the orange color denotes the bottom-hole pressure of the second well.
The $R^2$ of the original network is also plotted as horizontal lines of corresponding colors for comparison.}
\label{fig:pod_twowells}
\end{figure}
Figure \ref{fig:pod_twowells} depicts an experiment where MOR of different state sizes were tested in terms of $R^2$ over the test data.
One can infer that after a given number of states $(150)$ the performance remains consistently close to the original network in terms of $R^2$, despite having only $10\%$ of the original number of states.
PODs that resulted in $92$ states also showcased good performance in comparison to the original \eric{network of} $1,400$ neurons.
However, with only POD, the computational problem of computing $\mathbf{T}^T\mathbf{f}$ still remains.
We select the case where the reduced network has $92$ states (which represents an energy cutoff of $1\%$), and try performing DEIM on it.
\begin{figure}
\centering
\includegraphics[width=0.85\textwidth]{figures/twowells_plot.eps}
\caption{Single simulation run involving a POD with $92$ states ($0.01$ energy cutoff) and a DEIM interpolation with $m=1,073$, put side by side with the original data for the bottom hole pressure $p_{bh}$ of both wells (normalized), and the original ESN.}
\label{fig:twowells_plot}
\end{figure}
Figure \ref{fig:twowells_plot} depicts a simulation for the ESN, POD-ESN, and POD-DEIM ESN
\eric{for}
the test data of the two-wells and one riser platform.
Even though there was a reduction from $1,400$ to only $92$ states, the behavior of the ESN and the POD-ESN managed to be close in terms of dynamics.
With the application of DEIM, the computation nodes were reduced from $1,400$ to $1,073$, however some overshooting emerged which was not present in the ESN and POD-ESN.
\eric{With respect to the
simulation run in Figure \ref{fig:twowells_plot},
the $R^2$ for each well normalized bottom-hole pressure was:
$(0.9988,0.9990)$ for the ESN,
$(0.9979,0.9981)$ for the POD-ESN,
and $(0.9873,0.9671)$ for the DEIM-POD-ESN. }
There is little drop in response quality from reducing the number of states from $1,400$ to $92$ through POD, but performing interpolation from a standard POD to a POD-DEIM framework seems to affect the response more significantly.
\section{Introduction}
Recurrent Neural Networks (RNN) are very relevant in applications related to modeling real world phenomena when time-dependent data are available \cite{nl_sys_ident}, \cite{Bishop},
and are considered universal approximators of dynamic systems.
As RNNs are nonlinear, their training suffers from issues such as local minima, slow training, and the so-called ``fading gradient'' problem \cite{deep_goodfellow}, which is a numerical problem inherent in Backpropagation Through Time (BPTT) \cite{Mozer}, the algorithm used to calculate an RNN gradient.
While some solutions focus on solving the fading gradient problem by changing the RNN structure, such as the Long Short-Term Memory (LSTM) network \cite{lstm}, or the gated recurrent unit \cite{deep_goodfellow}, another flavor of RNN is worthy of attention: Reservoir Computing (RC).
RC simplifies the learning by dividing the RNN into two parts: a high-dimensional recurrent nonlinear layer, called reservoir, with fixed, randomly generated weights, and an adaptive readout output layer, which computes an instantaneous linear combination of the dynamic reservoir states \cite{Jaeger2007335}.
The weights of the output layer are trained through linear least squares, overcoming the problems related to nonlinear training and BPTT.
The term \textit{Reservoir Computing} was actually established
as an unifying framework for Liquid State Machines \cite{Maass2011}, and Echo State Networks (ESN) \cite{Jaeger2007335}, both of which are methods for RNN training independently developed.
ESNs follow the general reasoning of Reservoir Computing: they adopt an architecture with a dynamic reservoir with fixed weights that projects the input to a high-dimensional space, and a trainable static readout output layer.
The dynamic reservoir needs to have a large number of neurons \cite{Jaeger2007335}, and the so-called Echo State property, which refers to stability properties of the network.
There are many successful applications of ESNs, such as: learning complex goal-directed robot behaviors \cite{Antonelo2014}, fuel cell lifetime prediction \cite{Mezzi2021}, wind speed prediction \cite{Bai2021}, and medium voltage insulators classification \cite{Stefenon2022}.
Actually, the large number of dynamic states in the reservoir is a very important characteristic, as the output, being a linear combination of them, can represent a larger repertoire of dynamics.
However, using ESNs as dynamic models for problems such as optimization and MPC (Model Predictive Control) \cite{camacho} may be an issue since
the higher the number of states in the ESN is, the larger is the optimization problem overall.
This is because the number of states in the ESN heavily dominates the number of inputs and outputs in the optimization problem,
making it inherently larger and harder to solve.
As ESNs are high-dimensional, model order reduction methods may be used to find equivalent ESN models that have a considerably smaller number of states, but which still keeps the properties and performance of the original high-dimensional ESN.
For that end, we count on Proper Orthogonal Decomposition (POD) \cite{Chatu2010}, which applies Singular Value Decomposition (SVD) to find an optimal linear transformation that represents the state space of a large dynamical system in a more compact form.
POD is already widely used to reduce the number of states of large dynamical models, specially phenomenological models such as a gas reservoir simulator \cite{Wang2018} with tens of thousands of variables.
Actually, POD has one disadvantage concerning nonlinear systems: although the method can in fact reduce the number of states, it does not reduce the computation number of nonlinear functions.
There are developments of interpolation methods, such as the Discrete Empirical Interpolation Method (DEIM) \cite{Chatu2010}, to mitigate the issue, by pivoting and approximating the nonlinear portion of the given model computation.
Both POD and DEIM can be used to find lower-dimensional networks that are equivalent to the original ESN and, thus,
have the potential to alleviate the computational burden of simulations that depend on the size of the trained ESN.
The main objective of this work is to experiment on the use of POD and DEIM for obtaining a reduced order equivalent for an already trained ESN.
For such end, we apply the reduction given by POD in three different contexts:
a Memory Capacity (MC) \cite{memory_jaeger} evaluation experiment;
a NARMA10 difference equation \cite{Sakemi2020};
and a simulated oil platform containing two gas-lifted oil wells and one riser \cite{jordanou_eaai}.
Additionally, we have shown results using DEIM-based reduction for the ESN on the first and last aforementioned experiments.
We compare the performance of the reduced ESN to the original (non-reduced) ESN in the three experiments above, and also to another ESN of size equivalent to the reduced ESN's size in the MC and NARMA experiments.
In this context, our main contribution is the proposal and evaluation of Model Order Reduction (MOR) to reduce the number of states in an Echo State Network through several experiments. Furthermore, this work contributes by showing experimentally:
\begin{itemize}
\item
that the memory capacity of a ESN reduced by POD is in general higher than the memory capacity of a non-reduced ESN of equivalent size. This difference in memory capacity is greater as the desired ESN gets smaller in size.
\item
that, given two equally sized echo state networks, with the same number of reservoir's states, the one obtained from POD reduction has a higher probability of generating a good enough reservoir for the considered task. This result is more evident and relevant as the size of the desired reservoir gets smaller.
\item that, by employing a MOR method on ESNs, this work makes small ESNs more robust and performant, improving their suitability for real-time or embedded applications with memory limitations.
\item that DEIM reduction alone for ESNs does not achieve satisfactory results in comparison to pure POD reductions.
\end{itemize}
This paper is organized as follows: Section \ref{sec:rel_work} contains related works, Section \ref{sec:esn} presents the Echo State Networks, Section \ref{sec:mor} describes POD and DEIM, Section \ref{sec:app} reports on the case studies and experimental testing for the reduced ESN, and Section \ref{sec:conclusion} concludes the work.
\section{}
\bibliographystyle{elsarticle-num-names}
\section{Echo State Networks (ESN)} \label{sec:esn}
An ESN is a type of recurrent neural network with useful characteristics for system identification \cite{Jaeger2007335},
as it represents nonlinear dynamics well and the training consists in solving a linear least-squares problem of relatively low computational cost when compared to nonlinear optimization.
\subsection{Model}
Proposed in \cite{Jaeger2004,Jaeger2001a}, the ESN is governed by the following discrete-time dynamic equations:
\begin{align}
\mathbf{x}[k+1] &= (1-\gamma)\mathbf{x}[k] \nonumber \\ &~ + \gamma \mathbf{f}(\mathbf{W_r^r}\mathbf{x}[k] + \mathbf{W_i^r}\mathbf{u}[k] + \mathbf{W_b^r} + \mathbf{W_o^r}\mathbf{y}[k]) \label{eq:esn}\\
\mathbf{y}[k+1] &= \mathbf{W_r^o}\mathbf{x}[k+1] \label{eq:output_esn},
\end{align}
where: the state of the reservoir neurons at time $k$ is given by $\mathbf{x}[k]$;
the current values of the input and output neurons are represented by $\mathbf{u}[k]$ and $\mathbf{y}[k]$, respectively;
$\gamma$ is called leak rate \cite{Jaeger2007335}, which governs the percentage of the current state $\mathbf{x}[k]$ that is transferred into the next state $\mathbf{x}[k+1]$.
The weights are represented in the notation $\mathbf{W_{from}^{to}}$, with ``$\mathbf{b}$'', ``$\mathbf{o}$'', ``$\mathbf{r}$'', and ``$\mathbf{i}$'' meaning the bias, output, reservoir, and input neurons, respectively;
and $f = \tanh(\cdot)$ is an activation function widely used in the literature, also called a base function in system identification theory \cite{nl_sys_ident}.
Fig. \ref{fig:echostate} depicts a standard architecture of an echo state network.
\begin{figure}[!t]
\centering
\includegraphics[width=0.50\textwidth]{figures/reservoir_architecture0.eps}
\caption{Representation of an Echo State Network, one of the possible models in Reservoir Computing.
Dashed connections (from Reservoir to Output Layer) are trainable, while solid connections are fixed and randomly initialized.
}
\label{fig:echostate}
\end{figure}
The network has $N$ neurons in the reservoir, which is the dimension of $\mathbf{x}[k]$ and is typically orders of magnitude higher than the number of network inputs.
As long as regularization is used in network training, $N$ can be as large as needed, but at the expense of increased computation time to update the reservoir states as defined in \eqref{eq:esn}.
According to \cite{memory_jaeger}, the ESN with no output feedback connections (the output has no effect on the state), which is given by $\mathbf{W_o^r}$, has a memory capacity ($MC$) bounded by the number of neurons in the reservoir ($MC \leq N$), assuming that linear output units are used.
The recurrent reservoir should possess the so-called Echo State Property (ESP) \cite{Jaeger2001a}, i.e., a fading memory of its previous inputs, meaning that influences from past inputs on the reservoir states vanish with time.
The ESP is guaranteed for reservoirs with $\tanh(\cdot)$ as the activation function, provided that the singular values of $\mathbf{W_r^r} < 1$.
However, this condition limits the richness of the reservoir dynamical qualities, which discourages its use in practice.
Note that all connections going to the reservoir are randomly initialized, usually according to the following steps:
\begin{enumerate}
\item Every weight of the network is initialized from a normal distribution $\mathcal{N}(0,1)$.
\item $\mathbf{W_{r}^{r}}$ is scaled so that its spectral radius $\rho$ (Eigenvalue with the largest module) characterizes a regime able to create reservoirs with rich dynamical capabilities.
%
It has been often observed that setting $\rho < 1$ in practice generates reservoirs with the ESP \cite{Jaeger2007335}.
%
However, reservoirs with $\rho > 1$ can still have the ESP since the effective spectral radius may still be lower than 1 \cite{Ozturk,Verstraeten2009}.
\item $\mathbf{W_i^r}$ and $\mathbf{W_b^r}$ are multiplied by scaling factors $f_i^r$ and $f_b^r$, respectively, affecting the magnitude of the input.
\end{enumerate}
These scaling parameters, $\rho$, $f_i^r$, and $f_b^r$ are crucial in the learning performance of the network, having an impact on the nonlinear representation and memory capacity of the reservoir
\cite{memorynl}.
Also, low leak rates allow for higher memory capacity in reservoirs, while high leak rates should be favored for quickly varying inputs and/or outputs.
The settings of these parameters should be such that the generalization performance of the network (loss on a validation set) is enhanced.
\subsection{Training}
While in standard RNNs all weights are trained iteratively using gradient descent \cite{Mozer}, ESNs restrict the training to the output layer $\mathbf{W_r^o}$.
Because the echo state property is not insured with output feedback $\mathbf{W_o^r}\mathbf{y}[k]$, this work favors reservoirs without feedback from the output (i.e., $\mathbf{W_o^r}=0$).
Also, the inputs do not interfere directly in the output, as systems with direct transmission are less smooth and more sensitive to noise.
To train an ESN, the input data $\mathbf{u}[k]$ is arranged in a matrix $\mathbf{U}$ and the desired output $\mathbf{d}[k]$ in vector $\mathbf{D}$ over a simulation time period, where each row $\mathbf{u}^T$ of $\mathbf{U}$ corresponds to a sample time $k$ and its columns are related to the input units.
%
For the sake of simplicity, we assume that there are multiple inputs and only one output.
The rows of $\mathbf{U}$ are input into the network reservoir according to each sample time, thereby creating a state matrix $\mathbf{X}$ that contains the resulting sequence of states.
Then, we apply the Ridge Regression algorithm \cite{Bishop} by using $\mathbf{X}$ as the input data matrix and $\mathbf{D}$ as the output data matrix, or in this case a vector as we assumed single output.
Ridge Regression results in solving the following linear system:
\begin{equation}
(\mathbf{X}^T\mathbf{X} - \lambda \mathbf{I})\mathbf{W_r^o} = \mathbf{X}^T\mathbf{D}
\label{eq:training},
\end{equation}
where $\lambda$ is the Tikhonov regularization parameter, which serves to penalize the weight magnitude, and avoid overfitting.
There are also methods to apply least squares training in an online way \cite{nl_sys_ident}, but these algorithms are not used in this work.
\section{Model Order Reduction} \label{sec:mor}
In this section, \eric{we propose Model Order Reduction (MOR) methods for reducing the reservoir dimensionality in ESNs. Specifically, the Proper Orthogonal Decomposition (POD) and the Discrete Empirical Interpolation Method (DEIM) are presented.}
We also propose a strategy for correcting the steady-state error introduced in ESNs by MOR methods.
\subsection{Proper Orthogonal Decomposition}
The Proper Orthogonal Decomposition is a method to find a linear transformation \cite{Chen} $\mathbf{T}$ for a given system that maps a high-dimensional state space into a reduced one, namely:
\begin{equation}
\mathbf{x} = \mathbf{T}\mathbf{z}
\end{equation}
where $\mathbf{x}$ is a vector of dimension $n$ and $\mathbf{z}$ is a vector of dimension $m \ll n$, so that $\mathbf{T}\in\mathbb{R}^{n\times m}$.
The transformation itself is akin to a similarity transformation, with the main difference being that $\mathbf{T}$ lacks an inverse for not being a square matrix.
However, the $\mathbf{T}$ resulting from POD is orthonormal ($\mathbf{T}^T\mathbf{T} = \mathbf{I}$), so the transpose is used in place of an inverse.
To find $\mathbf{T}$, we gather snapshots of the states in a given dynamical system response, akin to gathering data in a machine learning problem.
The columns of the snapshot matrix $\mathbf{X}\in\mathbb{R}^{n\times N}$ are the states $\mathbf{x}[k]\in \mathbb{R}^{n}$, where $N$ is the number of snapshots such that $N\geq n$.
Then, we wish to minimize the error induced by projecting the original state onto the reduced space and back, which leads to the following error function:
\begin{equation}
E(\mathbf{T}) = \sum_{k = 1}^{N}\bigl(\mathbf{x}[k] - \mathbf{T}\underbrace{\mathbf{T}^T\mathbf{x}[k]}_{\mathbf{z}[k]}\bigr)^2
\end{equation}
The second term is $\mathbf{x}$ \textit{projected} onto the reduced space of $\mathbf{z}$, and then \textit{lifted} back.
The optimal $\mathbf{T}$ is obtained through singular value decomposition (SVD) \cite{Sun2017}, decomposing $\mathbf{X}$ in the following form:
%
\begin{equation}
\mathbf{U_{svd}}\mathbf{\Sigma}\mathbf{V}^T = \mathbf{X}
\end{equation}
where $\mathbf{U_{svd}}$ contains the left singular vectors and has dimension $n \times n$, $\mathbf{\Sigma}$ contains the singular values and has dimension $n \times N$, with only $n$ non-zero columns.
We consider that $\mathbf{\Sigma}$ is sorted from the largest to the smallest singular value.
The right singular vector matrix $\mathbf{V}$ is not used for POD.
The transformation $\mathbf{T}$ that minimizes $E(\mathbf{T})$ is found by concatenating the columns with the $m$ largest corresponding singular values from $\mathbf{U_{svd}}$.
We seek a truncation so that the reduced system energy is close to the original, measured by:
\begin{align} \label{eqn:energy_contribution}
\epsilon &= \sum\limits_{j=1}^{m}\epsilon_j
& \epsilon_j &=
\sigma_j/{\sum\limits_{i=1}^n\sigma_i}
\end{align}
where $\epsilon$ is the total energy contribution of the singular values maintained in the reduced-order model, $\sigma_j$ is the $j^{th}$ highest singular value, $\epsilon_j$ is the energy contribution of that given singular value, and $m$ is the reduced state dimension.
For this work, we measure the energy contribution of each singular value of the original signal, and truncate $\mathbf{U_{svd}}$ to obtain $\mathbf{T}$ so that $\epsilon$ reaches a desired energy contribution value (\textit{e.g.}, $\epsilon = 0.95$ so that the reduced system has $95\%$ of the original system's energy).
After obtaining $\mathbf{T}$ for the dimension reduction through the process above, the reduced ESN dynamics can be expressed as follows:
\begin{subequations}
\label{eq:reduced_esn_pod}
\begin{align}
\mathbf{z}[k+1] &= (1-\gamma)\mathbf{z}[k] \nonumber \\ &~~ + \gamma \mathbf{T}^{T}\mathbf{f}(\mathbf{W_r^r}\mathbf{T}\mathbf{z}[k] + \mathbf{W_i^r}\mathbf{u}[k] + \mathbf{W_b^r}) \label{eq:reduced_esn_state}\\
\mathbf{y}[k+1] &= \mathbf{W_r^o}\mathbf{T}\mathbf{z}[k+1] \label{eq:output_reduced_esn},
\end{align}
\end{subequations}
\eric{It can be observed from the operation $\mathbf{T}^T\mathbf{f}(\cdot)$ that} the reduced-order ESN does not actually reduce the number of computations by only performing POD on it.
In fact, to compute the element-wise $\tanh$, $\mathbf{T}$ brings the
\eric{dimension}
back to the original state space size, \eric{which is to be reduced again with $\mathbf{T}^{T}$, increasing the number of computations in the end.}
This computational increase is inherent in POD for nonlinear systems and will \eric{be} dealt with by the method described in the next section.
\subsection{Discrete Empirical Interpolation}
The Discrete Empirical Interpolation Method (DEIM) is an approximation method to circumvent the POD computation issue \cite{Chatu2010}, which consists of state projection and lifting operations to compute state transitions in the reduced-order model.
The core idea of DEIM is to approximate the nonlinear term of a dynamic system as a polynomial interpolation that resembles the strategy employed in POD.
Given the following discrete-time nonlinear system:
\begin{equation}
\mathbf{x}[k+1] = \mathbf{A}\mathbf{x} + \mathbf{f}(\mathbf{x}[k]),
\end{equation}
where the nonlinear function is elementwise, meaning that $\mathbf{f} = \bigl (f(\mathbf{x}), f(\mathbf{x}), \dots, f(\mathbf{x})\bigr)$ for a given function $f$ such as ${\tt tanh}$. Notice that the system is divided into a linear and nonlinear portion.
Applying the POD ($\textbf{x} = \textbf{T}\textbf{z}$) into such a system yields:
\begin{equation} \label{eqn:deim_sys}
\mathbf{z}[k+1] = \mathbf{T}^T\mathbf{A}\mathbf{T}\mathbf{z}[k] + \mathbf{T}^T\mathbf{f}(\mathbf{T}\mathbf{z}[k])
\end{equation}
The nonlinear mapping $\mathbf{f}$ of the dynamic system can be approximated as follows:
\begin{equation} \label{eq:DEIM:eq01}
\mathbf{P}^T\mathbf{f}(\mathbf{T}\mathbf{z}[k]) \approx \mathbf{P}^T\mathbf{U}\mathbf{c}[k]
\end{equation}
where $\mathbf{U} \in \mathbb{R}^{n\times m}$, which is obtained from the same POD as $\mathbf{T}$, however with a different number $m$ of singular vectors, with $n$ being the number of states, and $\mathbf{P}$ is a pivoting matrix of the same dimension as $\mathbf{U}$.
DEIM interprets that the elementwise function $\mathbf{f}$ can be approximated as a linear combination with basis $\mathbf{U}$ and the elements $\mathbf{c}[k]$ as function coefficients.
After obtaining $\mathbf{U}$ from $\mathbf{U_{svd}}$, we then obtain $\mathbf{P}$ with the following procedure \cite{Chatu2010}:
\begin{enumerate}
\item The index and value of the largest element of the first left-singular vector is stored in a list. $\mathbf{P}$ starts as a column matrix with the only non-zero element being the value $1$ at the row corresponding to this index.
\item For each column $l \geq 2$ of the POD left-singular vectors (where $\mathbf{\widetilde{U}}_{l}$ is a matrix with the first $l-1$ columns of $\mathbf{U}$):
\begin{enumerate}
\item find $\mathbf{c}$ where $(\mathbf{P}^T\mathbf{\widetilde{U}}_{l})\mathbf{c} = \mathbf{P}^T\mathbf{u}_l$, where $\mathbf{u}_l$ is the left-singular vector corresponding to the $l^{th}$ column of $\mathbf{U}$.
\item Calculate $\mathbf{r} = \mathbf{u}_l - \mathbf{\widetilde{U}}_{l}\mathbf{c}$ and store the maximum absolute value and index of $\mathbf{r}$ in a list. Add a new column to $\mathbf{P}$ according to the obtained index.
\end{enumerate}
\item Output: Pivoting matrix $\mathbf{\mathbf{P}}$ according to the order dictated by the index list obtained.
\end{enumerate}
This procedure guarantees that $\mathbf{P}^T\mathbf{\widetilde{U}}_{l}$ is always nonsingular, thus $\mathbf{c}$ is the unique solution to the linear system in step 2 \cite{Chatu2010}. Letting $\mathbf{U}$ be the matrix of left singular values obtained from the procedure, it follows from \eqref{eq:DEIM:eq01} that:
\begin{equation}
\mathbf{c}[k] = (\mathbf{P}^T\mathbf{U})^{-1}\mathbf{P}^T\mathbf{f}(\mathbf{T}\mathbf{z}[k])
\end{equation}
This leads to a reduced-order model with DEIM:
\begin{equation} \label{eqn:deim_approx}
\hat{\mathbf{f}}(\mathbf{T}\mathbf{z}[k]) \approx \mathbf{U}(\mathbf{P}^T\mathbf{U})^{-1}\mathbf{P}^T\mathbf{f}(\mathbf{T}\mathbf{z}[k])
\end{equation}
This approximation has an ${\ell}_2$ error bound of the following form \cite{Chatu2010}:
\begin{equation}
e_{{\ell}_2}(\mathbf{f}) \leq \|(\mathbf{P}^T\mathbf{U})\|_2\|(\mathbf{I} - \mathbf{U}\mathbf{U}^T)\mathbf{f}(\mathbf{T}\mathbf{z}[k])\|
\end{equation}
where, in turn:
\begin{equation}
\|(\mathbf{P}^T\mathbf{U})\|_2 \leq (1 + \sqrt{2n})^{m-1}\|\mathbf{u}_1\|_\infty^{-1}
\end{equation}
with $\mathbf{u}_1$ being the first column of $\mathbf{U}$ and
$n$ being the number of original states.
The main advantage of DEIM is that, as $\mathbf{f}$ is an element-wise nonlinear function, the following equality holds:
\begin{equation}\label{eqn:deim_approximation}
\underbrace{\mathbf{U}(\mathbf{P}^T\mathbf{U})^{-1}\mathbf{P}^T}_{\mathbf{T}_1\in \mathbb{R}^{n\times n}}\underbrace{\mathbf{f}(\mathbf{T}\mathbf{z}[k])}_{\mathbf{f}:\mathbb{R}^n\rightarrow \mathbb{R}^n} =
\underbrace{\mathbf{U}(\mathbf{P}^T\mathbf{U})^{-1}}_{\mathbf{T}_2\in \mathbb{R}^{n\times m}}\underbrace{\mathbf{f}(\mathbf{P}^T\mathbf{T}\mathbf{z}[k])}_{\mathbf{f}:\mathbb{R}^m\rightarrow \mathbb{R}^m}
\end{equation}
The difference between the right-hand side and left-hand side of this equation is better seen in a compact form,
\begin{equation*}
\mathbf{T}_1\mathbf{f}(\mathbf{T}\mathbf{z}[k]) = \mathbf{T}_2\mathbf{f}(\mathbf{P}^T\mathbf{T}\mathbf{z}[k])
\end{equation*}
where $\mathbf{T_1}$ has $n$ columns, which yields the same computation problem as the original Galerkin projection, whereas $\mathbf{T_2}$ has $m$ columns, which is the reduced state space.
This simple difference grants huge computational savings, since the online calculations would be performed in terms of the reduced dimension $m$, $m\ll n$, which mitigates the computation issues regarding the POD method.
The DEIM-approximated reduced order ESN has the form, obtained by applying DEIM from Eq. \eqref{eqn:deim_approximation} into the already reduced ESN at \eqref{eq:reduced_esn_pod}:
\begin{subequations}
\begin{multline}
\mathbf{z}[k+1] = (1-\gamma)\mathbf{z}[k] \\
+ \gamma \mathbf{T}^T\mathbf{T_2}\mathbf{f}\left (\mathbf{P}^T\mathbf{W_r^r}\mathbf{T}\mathbf{z}[k] + \mathbf{P}^T\mathbf{W_i^r}\mathbf{u}[k] + \mathbf{P}^T\mathbf{W_b^r}\right ) \label{eq:reduced_esn}
\end{multline}
\begin{equation}
\mathbf{y}[k+1] = \mathbf{W_r^o}\mathbf{T}\mathbf{z}[k+1] \label{eq:output_reduced_esn_deim},
\end{equation}
\end{subequations}
The property $\mathbf{P}^T\mathbf{f}(\cdot) = \mathbf{f}(\mathbf{P}^T)$ holds for elementwise operations, which justify the matrix placement in the DEIM reduced-order ESN.
\subsection{Stability Loss in DEIM} \label{sec:DEIM-stability}
According to \cite{Selga2012}, a contractive linear system is guaranteed to retain stability when applying POD for model order reduction, therefore, if the ESN is contractive, the POD-ESN is guaranteed to retain stability.
However, DEIM has no such a property.
%
Assume an equilibrium point $\mathbf{x_{eq}}$ of the ESN, and a fixed input $\mathbf{u}$,
\begin{equation}
\mathbf{x_{eq}} = \mathbf{f}(\mathbf{W_r^r}\mathbf{x_{eq}} + \mathbf{W_i^r}\mathbf{u}+ \mathbf{W_b^r})
\end{equation}
and its reduced mapping $\mathbf{z_{eq}}=\mathbf{T}^T\mathbf{x_{eq}}$. The Jacobian of the full and reduced order model are:
\begin{align}
J(\mathbf{x_{eq}}) &= (1-\gamma)\mathbf{I} + \gamma \mathbf{f}'(\mathbf{g}(\mathbf{x_{eq}}))\mathbf{W_r^r}\\
J(\mathbf{z_{eq}}) &= (1-\gamma)\mathbf{I} + \gamma \mathbf{T}^T\mathbf{f}'(\mathbf{g}(\mathbf{T}\mathbf{z_{eq}}))\mathbf{W_r^r}\mathbf{T}
\end{align}
where:
\begin{equation}
\mathbf{g}(\mathbf{x}) = \mathbf{W_r^r}\mathbf{x} + \mathbf{W_i^r}\mathbf{u} + \mathbf{W_b^r}
\end{equation}
Since $\mathbf{f'}$ is a diagonal matrix where each element belongs to the interval $(0,1]$ for being the elementwise derivative of the $\tanh$ function, the stability of the ESN in both cases is governed by $\mathbf{W_r^r}$ at any equilibrium point.
Also, as per \cite{Selga2012}, the stability of the ESN is preserved in the POD reduction. Summing up, the original and reduced-order ESNs are stable provided that the spectral radius of $\mathbf{W_r^r}$ is smaller than $1$.
With DEIM, however, the stability is not retained.
This can be shown by calculating the Jacobian of an ESN reduced by both POD and DEIM:
\begin{multline}
\mathbf{J_{DEIM}}(\mathbf{z}) = (1-\gamma)\mathbf{I} + \gamma \mathbf{T}^T\mathbf{U}(\mathbf{P}^TU)^{-1}\mathbf{f}'(\mathbf{P}^T\mathbf{g}(\mathbf{T}\mathbf{z}))\mathbf{P}^T\mathbf{W_r^r}\mathbf{T}
\end{multline}
Notice that the term $(\mathbf{P}^T\mathbf{U})^{-1}$ can actually amplify the Jacobian to the point that the ESN dynamic system has an unstable eigenvalue, despite POD-ESN being stable.
This term represents the pivoting of the truncated singular vectors associated with DEIM.
\section{Related Work} \label{sec:rel_work}
There are works in the literature that address the issue of reducing the model size in reservoir computing.
One of them is \cite{Sakemi2020}, where they propose reducing the number of states by considering the output as a linear combination of the states at different instants in time, comparing to an original ESN through the Information Processing Capacity (IPC) metric, and also applying the proposal to a NARMA system and the generalized Hénon-map.
The solution raises the effective number of states as a multiple of the delay or ``drift-state'' number utilized.
The architecture is very hardware-friendly, easing the computation in relation to a standard ESN.
Another example is the work \cite{Whiteaker2022}, where they propose to employ the controllability matrix of the ESN as a means to find a so-called minimal ESN, which would be the ESN with the smallest reservoir that could reproduce the task at hand.
They train the ESN for a given task, obtain the controllability matrix at given points, and define its rank as a new candidate reservoir size.
An extensive search procedure is then performed to find the optimal ESN at that given size, however there is no direct connection between the larger and the smaller ESN.
In summary, the method in \cite{Whiteaker2022} proposes an interesting way of finding a minimal reservoir for a task.
In comparison, our work follows a different direction: reducing the \eric{size of the network} through the Singular Value Decomposition (SVD).
Another work \cite{Liu2022} proposes a different approach on reducing reservoir size, %
by calculating the correlation between each neuron, and eliminating the reservoir neurons with highest correlation.
The necessary large number of reservoir state in an ESN implies a complex computational model, therefore works such as \cite{Yang2022}, employ methods of so-called ``network size reduction,'' by performing multi-objective optimization on the output weights, minimizing not only the least-square error, but also the number of non-zero elements in the output weights.
Enforcing sparseness is ideal to make the ESN easier to compute.
Another work that follows this line of reasoning is \cite{deterministic_esn}, where they enforce a minimum complexity ESN by forcing the ESN reservoir to follow a deterministic form (i.e., a circular reservoir).
In \cite{Lkse2017}, they propose to add the reservoir dimensionality reduction into the architecture via Principal Component Analysis (PCA), and calculate the output layer based on the PCA output instead of the reservoir states.
They affirm that this enhances the dynamic properties of the resulting ESN in relation to the system identified, and improves the network generalization capabilities.
Also, that applying dimensionality reduction in the states renders the ESN a tool for dynamic system analysis.
In this sense, our POD-ESN method is similar to PCA with respect to obtaining the new state space, but goes beyond \cite{Lkse2017} by embedding the reduction achieved in the reservoir's state update equation. This is to say that the reservoir recurrent simulation is accomplished in the reduced state space with POD-ESN, which does not happen in \cite{Lkse2017}.
Another interesting approach of reduction in reservoir computing, not involving POD, is proposed in \cite{Halus2020}.
Their idea involves procedurally removing neurons according to the output weight value, which they curiously discovered that the network performance improves (given the Lorentz system as application) when neurons associated with large output weights are removed.
They thoroughly analyze the effect of removing different types of nodes in the ESN.
The aforementioned method can reduce an ESN size up to $60\%$ without compromising
performance.
| {'timestamp': '2022-12-05T02:14:12', 'yymm': '2211', 'arxiv_id': '2211.17179', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17179'} | arxiv |
\section{Introduction}
Pretrained transformer models have achieved excellent performance across various \ac{NLP} tasks such as \ac{TC}, \ac{NER}, \ac{QA} and summarization \cite{devlin_bert_2019, yang_xlnet_2020, he_debertav3_2021, zhang_pegasus_2020}.
Transfer learning is to a large extent responsible for this success \cite{howard_universal_2018}. Usually, transformer models are pretrained in a self-supervised way on large unlabeled corpora \cite{devlin_bert_2019, radford_improving_2018}. Pretraining is very resource intensive (especially for large models), thus making it costly and only available for large organizations \cite{sharir_cost_2020}. The \ac{MLM} task has been very successful, with many models adopting the task in their pretraining \cite{devlin_bert_2019, liu_roberta_2019, beltagy_longformer_2020, zaheer_big_2021}. Since typically only 15\% of the tokens are masked, the loss can be computed for those tokens only.
\citet{clark_electra_2020} introduced the \ac{RTD} task, which enables the loss to be computed on all tokens, making training more efficient. On the GLUE benchmark \cite{wang_glue_2018}, their ELECTRA model matches RoBERTa \cite{liu_roberta_2019} and XLNet \cite{yang_xlnet_2020} using 1/4 their compute.
Although ELECTRA's training strategy seems very promising, to the best of our knowledge, only few works have adopted the \ac{RTD} task so far \cite{he_debertav3_2021, kanakarajan_bioelectrapretrained_2021}.
\begin{figure}[t]
\centering
\resizebox{\columnwidth}{!}{
\includegraphics{plots/billsum.png}
}
\vspace{-7mm}
\caption{Results on the BillSum dataset. Note that the x-axis is in log-scale.}
\label{fig:billsum}
\vspace{-5mm}
\end{figure}
On another note, domain-specific pretraining has been shown to improve downstream performance in many domains such as
law \cite{chalkidis_legal-bert_2020, xiao_lawformer_2021},
biology \cite{lee_biobert_2019},
scientific articles \cite{beltagy_scibert_2019},
clinical documents \cite{li_clinical-longformer_2022}, or even
code \cite{chen_evaluating_2021}. Domain-specific pretraining coupled with the \ac{RTD} task, however, has not been studied in the legal domain so far.
Depending on the domain, documents might be extremely long. Texts from the legal domain, for example, tend to span multiple pages, ranging from 10s to 100s of pages, which translates to tens of thousands tokens. The quadratic time and memory requirement of the attention typically used in the transformer architecture \cite{vaswani_attention_2017} prohibits efficient processing of sequences longer than 512 tokens on current hardware. A rich body of research investigates how transformers can be adapted to efficiently process longer input \cite{tay_efficient_2020, child_generating_2019, beltagy_longformer_2020, zaheer_big_2021, roy_efficient_2021, kitaev_reformer_2020, tay_synthesizer_2021, lee-thorp_fnet_2021}.
Longformer \cite{beltagy_longformer_2020} is one of these efficient transformer architectures for long sequences, leveraging windowed and global attention. So far, to the best of our knowledge, there does not yet exist a public Longformer model pretrained on English legal data\footnote{On the web there is a model based on Longformer in a legal domain but no link how it was obtained and on its actual performance (https://huggingface.co/saibo/legal-longformer-base-4096).}, although \citet{xiao_lawformer_2021} have proven the effectiveness of the Longformer in dealing with long legal text in many Chinese-related tasks. This work aims to fill this gap.
To test the ability to grasp long-distance dependencies in the text, we mainly evaluated our \acp{LM} on the task of automatic (abstractive) summarization. It consists of capturing the most important concepts/ideas from the (long) document and then rewriting it in a shorter passage in a grammatical and logically coherent way \cite{chen_multi-task_2019}.
In particular, we used the BillSum benchmark, as a domain-specific summarization task, obtaining a new \ac{SOTA} (see Figure \ref{fig:billsum}); and the PubMed benchmark, to evaluate the model's ability outside the legal context (i.e., in the biomedical context), obtaining comparable metrics even though the \ac{LM} has only been pretrained on legal data and the tokenizer is also optimized for legal data (see Figure \ref{fig:pubmed}).
We emphasize that this performance was achieved with a minimal pretraining phase due to the combination of the RTD task and the Longformer infrastructure,
making our \ac{LM} very attractive from the point of view of building costs. For instance, our model saw only 3.2M examples during pretraining, whereas RoBERTa \cite{liu_roberta_2019} or PEGASUS-large \cite{zhang_pegasus_2020} saw 4.1B examples. RoBERTa was trained for 1024 GPU days, whereas our small and base models only used 12 and 24 GPU days respectively (16GB NVIDIA V100 GPUs for both models).
Since many tasks in legal \ac{NLP} are formulated as \ac{TC} problems, a hierarchical architecture has been used frequently to process long documents \cite{chalkidis_neural_2019, niklaus_swiss-judgment-prediction_2021}. This simple hierarchical architecture, indeed, cannot be easily adapted to solve the more complex sequence-to-sequence tasks like token classification or summarization, because it do not take efficiently long input correlations. For this reason, in this work, we pretrain a more versatile Longformer model.
Finally, for completeness, we evaluated our \acp{LM} using the LexGLUE benchmark, which is mainly based on multi-class and multi-label legal \ac{TC} problems for short texts.
\subsection*{Contributions}
The contributions of this paper are five-fold:
\vspace{-4mm}
\begin{itemize}[leftmargin=8pt, itemsep=0em]
\item We train and release
a new model pretrained on recently published curated English legal text \cite{henderson_pile_2022}, capable of handling input spans longer than 512 tokens out of the box.
\item We apply the promising, but seldom used \ac{RTD} task \cite{clark_electra_2020} on a Longformer model \cite{beltagy_longformer_2020}, for the first time, calling it BudgetLongformer.
\item On the BillSum benchmark \cite{kornilova_billsum_2019}, our models are a new \ac{SOTA} compared to models of the same size. Especially, our small model outperforms all baseline approaches, and a transformer base model \cite{vaswani_attention_2017} containing almost 4 times more encoder parameters (110M vs. 29M). It even outperforms the PEGASUS base model \cite{zhang_pegasus_2020} whose encoder is also almost 4 times larger and has been pretrained specifically for the abstractive summarization task in mind.
\item We verified that pretraining with the RTD task is suitable for down-stream summarization tasks by evaluating our model on an out-of-domain benchmark (PubMed), obtaining comparable results with summarization-specific architectures.
\item On the LexGLUE benchmark \cite{chalkidis_lexglue_2021}, despite the obvious emphasis on covering classification tasks even for short documents, our models achieve metrics equivalent to those of architectures that are better suited to this length of document, and with substantially fewer numbers of parameters and pretraining steps.
\end{itemize}
\subsection*{Main Research Questions}
In this work, we pose and examine five main research questions:
\noindent \textbf{RQ1}: \emph{Is it possible to generate an ad-hoc \ac{LM} with domain (e.g. legal) expertise from scratch, reducing costs and CO$_2$ emissions?}
\noindent \textbf{RQ2}: \emph{Is it possible to pretrain a Longformer model with the \ac{RTD} task (aka BudgetLongformer)?}
\noindent \textbf{RQ3}: \emph{How does our BudgetLongformer compare with other models on the challenging summarization task? Particularly in the case of a legal domain-specific benchmark such as BillSum?}
\noindent \textbf{RQ4}: \emph{ How well does our BudgetLongformer generalize to other domains, for example in the biomedical domain, as evaluated by the PubMed summarization benchmark?}
\noindent \textbf{RQ5}: \emph{How do our \acp{LM} compare with other models on the \acf{TC} benchmark LexGLUE?}
\input{sections/related_work}
\section{Datasets}
\label{sec:datasets}
In this section, we briefly introduce the datasets used in our experiments.
\subsection{Pile of Law}
\citet{henderson_pile_2022} recently released a large-scale English corpus suitable for pretraining \acp{LM}. It contains 256 GB of diverse legal text in English from various jurisdictions and judicial bodies including for example bills, court decisions and contracts from the US, Canada, and Europe even though the focus clearly lies on US data.
While there are 28 US datasets available (253.25 GB or 99\%), there is only 1 Canadian dataset\footnote{Canadian Court Opinions (ON, BC)} (243 MB or 0.09\%), 3 European datasets\footnote{European Court of Human Rights Opinions, EUR-LEX and European Parliament Proceedings Parallel Corpus} (2.3 GB or 0.9\%), and 2 international datasets\footnote{World Constitutions and U.N. General Debate Corpus} (212 MB or 0.08\%).
The non-US datasets only cover the categories ``Legal Case Opinions and Filings'', ``Laws'' and ``Conversations'', but do not cover categories ``Legal Analyses'', ``Contracts / Business Documents'' and ``Study Materials'', whereas the US data is much more diverse and covers all categories.
\subsection{BillSum}
\citet{kornilova_billsum_2019} introduced a legislative summarization dataset from 21K US bills from 1993 to 2018. It is challenging due to the technical nature and complex structure of the bills. Additionally, the bills are rather long, ranging from 5K to 20K characters ($\sim$ 1K to 4K tokens\footnote{Our experiments show that using our tokenizer one token corresponds to 5.33 characters on average.}) with their summaries being up to 5K characters ($\sim$ 1K tokens) long (see Appendix \ref{sec:data_details} for more details).
\subsection{PubMed}
\citet{cohan_discourse-aware_2018} introduced another challenging summarization dataset in a specialized domain (scientific articles from the biomedical domain). It includes 133K scientific papers together with their abstracts in English. The papers are 3K words long on average and the summaries (abstracts) 200 words. Thus, similar to the BillSum dataset, this dataset is well suited as a test bed for methods capable of long document summarization. Note, that in this dataset the domain is vastly different from the legal domain (see Appendix \ref{sec:data_details} for more details).
\subsection{LexGLUE}
\citet{chalkidis_lexglue_2021} recently introduced a benchmark for the English legal domain called LexGLUE. LexGLUE contains six \ac{TC} tasks and one \ac{QA} task comprising diverse legal data such as US court decisions and contracts, terms of service documents, EU legislation and cases from the \ac{ECtHR}. There exists a public leaderboard of diverse models on GitHub\footnote{\url{https://github.com/coastalcph/lex-glue}}, with Legal-BERT \cite{chalkidis_legal-bert_2020} performing best.
The LexGLUE benchmark focuses on evaluating \acp{LM} in legal \ac{TC} and \ac{QA} tasks.
In LexGLUE, 4 out of 7 tasks involve documents with input lengths lower than 512 tokens on average. From the remaining 3 tasks, the ECtHR A and B tasks and the SCOTUS tasks involve documents with long span, and the median of the first two is also less than 1000 tokens. Usually, legal documents are much longer than 512 tokens and thus this distribution might not be representative of real-world tasks. Shorter input length tasks may be better handled by short-input models (e.g., BERT, RoBERTa, Legal-BERT, etc.).
\section{BudgetLongformer}
In the legal domain, it is especially important that models can handle long input. So far, there does not exist an English legal model capable of handling more than 512 tokens. To make pretraining more affordable, we combined the well-proven Longformer model \cite{beltagy_longformer_2020} with the \ac{RTD} task proposed by \citet{clark_electra_2020}.
\section{Experimental Setup}
\label{sec:experimental_setup}
In this section, we describe how we set up the experiments.
In all our experiments, we made use of AMP mixed precision training and evaluation to reduce costs and GPU memory. For all our experiments, we used the huggingface transformers library \cite{wolf_transformers_2020} available under an Apache 2.0 license.
\subsection{Tokenizer}
We trained a byte-level BPE tokenizer \cite{wang_neural_2019} similar to \citet{beltagy_longformer_2020}. To encode the complicated legal language well, we chose a relatively large vocabulary of 64K tokens (additionally, we did not apply any preprocessing/cleaning of the input texts). We trained the tokenizer using the huggingface tokenizers library\footnote{\url{https://github.com/huggingface/tokenizers}} on the entire PileOfLaw training split ($\sim$ 192GB, $\sim$ 22.5B tokens, $\sim$ 7.5M documents), covering a wide array of English legal texts, mostly from the US.
\subsection{Pretraining}
\begin{table}[t]
\centering
\resizebox{\columnwidth}{!}{
\begin{tabular}{lrrr}
\toprule
PileOfLaw Subset & Dataset Size & \# Words & \# Documents \\
\midrule
caselaw \\
\midrule
\bf CL Opinions & \bf 59.29GB &\bf 7.65B & \bf 3.39M\\
\midrule
diverse \\
\midrule
\bf Total & \bf 73.04GB &\bf 8.91B & \bf 2.1M\\
CL Opinions & 8.74GB & 1.13B & 500K\\
CL Docket Entries and Court Filings & 17.49GB & 1.80B & 500K\\
U.S. State Codes & 6.77GB & 829.62M & 157\\
U.S. Code & 0.27GB & 30.54M & 43\\
EUR-Lex & 1.31GB & 191.65M & 106K\\
Edgar Contracts & 7.26GB & 0.97B & 500K\\
Atticus Contracts & 31.2GB & 3.96B & 488K\\
\bottomrule
\end{tabular}
}
\caption{The datasets used for pretraining our models. CL is short for Court Listener}
\label{tab:pretraining_data}
\end{table}
We trained the \emph{caselaw} models on the training subset ``Court Listener Opinions'' from the PileOfLaw (59.3 GB, 7.65B words, 3.39M documents).
The \emph{diverse} models were trained on caselaw (``Court Listener Opinions'' \& ``Court Listener Docket Entry Documents''), legislation (``US Code'', ``State Codes'' \& ``EURLEX'') and contracts (``Atticus Contracts'' \& ``EDGAR Contracts'').
To balance the training data, we limited the number of documents to 500K (this affects Court Listener Opinions, Court Listener Docket Entry Documents and EDGAR Contracts. Please see Table \ref{tab:pretraining_data} for more details.
Our validation set consisted of 1000 randomly selected examples from the respective training set.\footnote{We used such a relatively small validation set to save compute.}
To maximally use the available data, we concatenated all the examples and then cut them off in slices of the model's maximum sequence length (4096). We did this in batches of 1000 examples with multiprocessing to speed up data preparation. The last slice in each batch will not contain 4096 tokens, so we dropped it.
We trained both a small (29M parameters) and a base (159M parameters) model for each configuration. To reach 100K steps it took a bit less than 3 days for the small model and a bit less than 6 days for the base model on 4 16GB NVIDIA V100 GPUs. The achieved training and evaluation losses are shown in Table \ref{tab:losses} in Appendix \ref{sec:pretraining_details}. Interestingly, we find that the diverse models achieve lower training and evaluation losses. Please find more details in Appendix \ref{sec:hyperparameters}.
\citet{henderson_pile_2022} have experienced difficulties when the language model was trained on the entire Pile-of-Law. We believe that the highly imbalanced dataset concerning text types (contracts, court decisions, legislation, etc.) is the main reason for the training instability. This is one of the reasons why we adopted the procedure described above. As shown later in the results (see Section \ref{sec:results}), our pretraining was stable. On the contrary, the diverse model -- includes more lexical and layout diversity of documents -- turns out to perform better and train more robustly on the summarization tasks.
\subsection{Downstream Benchmarks}
\subsubsection*{BillSum}
When finetuning on the BillSum dataset \cite{kornilova_billsum_2019} we trained using early stopping with patience of 3 epochs. We paired our pretrained encoder model with a randomly initialized bart-base decoder model \cite{lewis_bart_2020}.\footnote{Interestingly, the randomly initialized decoder yielded better results than when we used the weights from the pretrained huggingface checkpoint at \url{https://huggingface.co/facebook/bart-base}.} We used a batch size of 32 and learning rate of 7e-5 after tuning in \{5e-4, 9e-5, 7e-5, 5e-5, 3e-5, 1e-5\}. We used the bart-base default config for num\_beams (4) and no\_repeat\_ngram\_size (3).
We set the maximum input length to 1024 and the maximum target length to 256 to save compute. However, many summaries get cut off at 256 tokens. This is why we took our best model and trained it with maximum input length 4096 and maximum target length 1024 (see results in Table \ref{tab:billsum_results} and examples in Table \ref{tab:examples_billsum-4096-1024_base_diverse}).
Due to high training costs, we only trained it with one random seed (42).
Our models contain 29M (small) and 159M (base) parameters in the encoder and 96M parameters in the decoder resulting in a total of 125M (small) and 255M (base) parameters.
\subsubsection*{PubMed}
Additionally, we evaluated on the PubMed summarization task \cite{cohan_discourse-aware_2018} using the same settings as for the BillSum task. We set the maximum input length to 4096 and the maximum generation length to 512.
\subsubsection*{LexGLUE}
Finally, we evaluated on LexGLUE \cite{chalkidis_lexglue_2021} using the publicly available scripts without modification to ensure consistent and comparable results. Because of compute limitations, we ran each experiment with only one random seed (1) and with the default set of hyperparameters. We speculate that hyperparameter tuning could further improve the performance of the proposed model.
\section{Results}
\label{sec:results}
In the following three sections, we present the results on the BillSum dataset, the PubMed dataset and the LexGLUE benchmark.
Tables \ref{tab:summarization_models} and \ref{tab:lexglue_models} in Appendix \ref{sec:models_overview} compare the models evaluated on the summarization and LexGLUE benchmarks, respectively.
\subsection{BillSum}
Our results on the BillSum dataset are presented in Figure \ref{fig:billsum} and Table \ref{tab:billsum_results} in Appendix \ref{sec:detailed_results}.
We observe that even our small diverse model
clearly exceeds the baseline of the original article (DOC + SUM), even though their model is based on BERT-large which contains almost 12 times more encoder parameters and has been pretrained for 10 times more steps.
Even more surprisingly, our small diverse model is on par with the PEGASUS-base model \cite{zhang_pegasus_2020} (37.58 vs. 37.78 Rouge-L), pretrained using the Gap-Sentences task specifically designed for abstractive summarization. Furthermore, their model contains almost 4 times more encoder parameters and has seen 40 times more training examples during pretraining (128M vs. 3.2M; see Table \ref{tab:summarization_models} in Appendix \ref{sec:models_overview}).
By scaling up our model to the base size, we even approach the performance of PEGASUS-large (40.5 vs. 45.8 Rouge-L). PEGASUS-large has seen three orders of magnitude more training examples during its pretraining in comparison to our model (4.1B vs. 3.2M) and contains more than twice as many encoder parameters (340M vs. 159M).
We conclude that pretraining with the \ac{RTD} task is highly effective, with minimal compute for long-input summarization in-domain.
\subsection{PubMed}
\begin{figure}[t]
\centering
\resizebox{\columnwidth}{!}{
\includegraphics{plots/pubmed.png}
}
\vspace{-7mm}
\caption{Results on the PubMed dataset. Note that the x-axis is in log-scale.}
\label{fig:pubmed}
\vspace{-5mm}
\end{figure}
Our results on the PubMed dataset are presented in Figure \ref{fig:pubmed} and Table \ref{tab:pubmed_results} in Appendix \ref{sec:detailed_results}.
Similar to the results on BillSum, our small model clearly outperforms the Transformer-base model (23.24 vs. 19.02 Rouge-L) and approaches the PEGASUS-base model (23.24 vs. 25.2 Rouge-L) even though we did not specifically pretrain our model for summarization and our model has seen 40 times fewer examples during pretraining (3.2M vs. 128M).
Similar again, we almost reach the performance of PEGASUS-large (26.53 vs. 27.69 Rouge-L) while having seen 1280 times fewer examples during pretraining (3.2M vs. 4.1B).
Note, that we pretrain on a much narrower domain than PEGASUS (legal text vs. C4). Our tokenizer and model has never seen medical data during its pretraining phase.
Finally, our tokenizer has $1/3$ fewer tokens than the PEGASUS tokenizer (64K vs. 96K).
In conclusion, pretraining with the \ac{RTD} task is even effective on an out-of-domain downstream summarization task.
\subsection{LexGLUE}
\begin{figure}[t]
\centering
\resizebox{\columnwidth}{!}{
\includegraphics{plots/lexglue_small.png}
}
\vspace{-7mm}
\caption{Results on the LexGLUE benchmark (small models). Note that the x-axis is in log-scale.}
\label{fig:lexglue_small}
\vspace{-5mm}
\end{figure}
\begin{figure}[t]
\centering
\resizebox{\columnwidth}{!}{
\includegraphics{plots/lexglue_base.png}
}
\vspace{-7mm}
\caption{Results on the LexGLUE benchmark (base models). Note that the x-axis is in log-scale.}
\label{fig:lexglue_base}
\vspace{-5mm}
\end{figure}
Table \ref{tab:lexglue_models} in Appendix \ref{sec:models_overview} compares the models evaluated on the LexGLUE benchmark.
Note, that these models differ strongly on many dimensions such as the number and types of training steps, the architecture, and the number of parameters.
Our results on the LexGLUE benchmark are presented in Table \ref{tab:lexglue_results} in Appendix \ref{sec:detailed_results} and in Figures \ref{fig:lexglue_small} and \ref{fig:lexglue_base} for the small and base models respectively. Figure \ref{fig:lexglue} in Appendix \ref{sec:detailed_results} shows all the models evaluated on LexGLUE combined.
From the results shown in Table \ref{tab:lexglue_results}, we can observe that our models do not improve on the \ac{SOTA} for short input length tasks. This suggests that for such tasks a more accurate description of the first 512 tokens, obtained through a pretraining dataset with a comparable distribution of token inputs, is more appropriate.
This could be an explanation for why our base model is not able to beat the trained models in the short input length.\footnote{
Note that Longformer and BigBird have been warm started from the RoBERTa checkpoint. Thus, they have been trained on short documents extensively during the first pretraining phase. Only in the second stage, these two models were fed long documents.
}
Despite the previous statement, we can also note that there is quite a clear correlation between the Micro-F1 and the number of parameters of the model in the case of small-size models. LegalBERT-small is an exception, outperforming DistilBERT but having fewer parameters. But LegalBERT-small has been pretrained on the same data as is contained in 6 out of 7 LexGLUE tasks. It is also likely, that the test sets have been contained in the pretraining data.
Our small model is still in this trend of performance to model size, despite having seen much fewer examples during pretraining (almost 200 times fewer than BERT-Tiny).
While in the case of the base model, this trend is still true for the same samples seen, if we leave out Legal-BERT and CaseLaw-BERT for the reasons already expressed.
This suggests that potentially extending the pretraining dataset with also short documents might improve the performance of our model in this regime as well. In our case, we avoided focusing too much on this point since the purpose of the paper is to solve the legal long documents as input.
Finally, we did not tune the hyperparameters at all.
It is well known that proper hyperparameter tuning and already selecting the right random seeds can significantly influence the downstream performance \cite{liu_empirical_2021, dodge_fine-tuning_2020}.
Note that especially our small models, like BERT-Tiny and miniLM, lag behind in the UnfairToS task (Macro-F1 score below 15). This could be due to an unlucky random seed (\citet{mosbach_stability_2021} and \citet{dodge_fine-tuning_2020} reported training performance strongly dependent on the random seed).
\section{Conclusions and Future Work}
\label{sec:conclusions_future_work}
\subsection{Answers to Main Research Questions}
\noindent \textbf{RQ1}: \emph{Is it possible to generate an ad-hoc \ac{LM} with domain (e.g., legal) expertise from scratch, reducing costs and CO$_2$ emissions?}
Yes, we showcase in this work that it is possible to pretrain a domain-expertise \ac{LM} from scratch with minimal compute, achieving comparable performance with methods that have seen more than three orders of magnitude more pretraining examples. Especially when there is no well-performing large teacher model available, our method is advisable.
\noindent \textbf{RQ2}: \emph{Is it possible to pretrain a Longformer model with the \ac{RTD} task (aka BudgetLongformer)?}
Yes, in this work, we show that it is possible to pretrain a Longformer model with the \ac{RTD} task.
\noindent \textbf{RQ3}: \emph{How does our BudgetLongformer compare with other models on the challenging summarization task? Particularly in the case of a legal domain-specific benchmark such as BillSum?}
Our \acp{LM} compare favorably to baselines on the challenging domain-specific summarization benchmark BillSum, requiring the models to process long inputs. Our small model outperforms the larger PEGASUS-base model, and our base model almost reaches the performance of the larger PEGASUS-large model. Both baselines have been pretrained with much more compute and data, and additionally with a pretraining task crafted specifically for summarization.
\noindent \textbf{RQ4}: \emph{ How well does our BudgetLongformer generalize to other domains, for example in the biomedical domain, as evaluated by the PubMed summarization benchmark?}
Yes, our results on the out-of-domain PubMed summarization benchmark show that our models compare favorably to baselines. Again, our small model outperforms PEGASUS-base and our base model approaches the performance of PEGASUS large.
\noindent \textbf{RQ5}: \emph{How do our \acp{LM} compare with other models on the understanding classification benchmark LexGLUE?}
Our small models compare favorably to baselines in their respective parameter range. Our base models approach the performance of the baselines even though (a) we trained using significantly less compute, (b) we did not pretrain on short documents, and (c) we did not tune the hyperparameters at all.
\subsection{Limitations}
\input{sections/limitations}
\subsection{Conclusion}
In this work, we show that we can successfully pretrain Longformer models with the \ac{RTD} task.
Using very little pretraining we can achieve \ac{SOTA} performance on the challenging legal summarization task BillSum, outperforming PEGASUS, that has been pretrained specifically for summarization.
Our model even outperforms PEGASUS on the out-of-domain PubMed dataset involving biomedical research articles.
To sum up, we present a simple and extremely cheap way of pretraining a long-context \ac{LM} in cases without the availability of a large teacher model.
\subsection{Future Work}
Future work could test these models on further legal downstream tasks such as CUAD \cite{hendrycks_cuad_2021} or the recently released MultiLexSum \cite{shen_multi-lexsum_2022}. Additionally, one can test whether the out-of-domain results hold on other out-of-domain summarization datasets, such as BigPatent \cite{sharma_bigpatent_2019} or ArXiv \cite{cohan_discourse-aware_2018}.
Future work could further scale up the models in terms of batch size, number of pretraining steps, number of parameters and amount of data to test what further gains can be achieved.
Due to compute constraints, we were unable to train the models long enough to reach \ac{SOTA} performance on LexGLUE. Future work could take our approach further and investigate the performance to be gained by investing more compute.
Additionally, to save even more compute and to produce better models, one could investigate how to warm-start an ELECTRA pretraining from existing checkpoints. The difficulty, of course, lies in getting a suitable generator and discriminator trained with the same tokenizer. One possible setup might be Longformer-base as the generator and Longformer-large as the discriminator.
Finally, one can investigate the use of other efficient transformers with the \ac{RTD} task.
\section*{Ethics Statement}
Pretraining language models is a very compute-heavy process and thus leaves a large carbon footprint \cite{strubell_energy_2019, patterson_carbon_2021}. Our method makes significantly reduces the compute requirements and thus the carbon footprint.
As with any large \ac{LM} there is the risk of it producing biased or unfair output. Researchers using the model should put into place respective safeguards to identify biased and/or toxic language.
\section{Pretraining Details}
\label{sec:pretraining_details}
\begin{table}[t]
\centering
\resizebox{\columnwidth}{!}{
\begin{tabular}{llrrr}
\toprule
Model & Data & \# Steps & Train Loss & Eval Loss \\
\midrule
small & caselaw & 50K & 14.61 & 15.78 \\
small & caselaw & 100K & 13.93 & 15.07 \\
\midrule
small & diverse & 50K & 13.75 & 12.70 \\
small & diverse & 100K & 12.78 & 11.66 \\
\midrule
base & caselaw & 50K & 12.40 & 13.76 \\
base & caselaw & 100K & 11.67 & 12.99 \\
\midrule
base & diverse & 50K & 10.70 & 10.01 \\
base & diverse & 100K & 9.86 & 9.22 \\
\bottomrule
\end{tabular}
}
\caption{Training and Evaluation losses for the different trained models. Note that these losses are the addition of the loss of the generator and the loss of the discriminator. Since the loss of the discriminator is much smaller, it is scaled by a factor of 50 to stabilize training.}
\label{tab:losses}
\end{table}
In this section, we show additional details regarding the pretraining process (Table \ref{tab:losses}).
\section{Hyperparameters and Training Details}
\label{sec:hyperparameters}
In this section, we present additional details regarding the chosen hyperparameters.
\subsection{Pretraining}
We pretrained our models with batch size 32 and learning rate 5e-4 and 3e-4 for the small and base models respectively.
We used a Longformer attention window of 256.
As described in by \citet{clark_electra_2020}, we used 10000 warm up steps and a 4 and 3 times smaller generator than the discriminator in the small and base version respectively. In contrast to \citet{clark_electra_2020} we reduced the generator's depth (number of hidden layers) instead of its width (embedding size, hidden size and intermediate size).
We used a \ac{MLM} probability of 25\% for the generators.
For running the pretraining, we used an AWS p3.8xlarge instance with 4 16GB NVIDIA V100 GPUs. Training the four models to 100K steps each, took approx. 18 days or 72 GPU days in total. Previous debug runs additionally consumed approx. 3 days or 12 GPU days.
\subsection{Downstream Benchmarks}
Overall, we found the diverse models to be more robust in finetuning with less failed runs and typically higher performance.
For running the finetuning experiments, we used an AWS p3.16xlarge instance with 8 16GB NVIDIA V100 GPUs. Running the BillSum, PubMed, and LexGLUE experiments including hyperparameter tuning took approximately 25, 7, and 11 GPU days in total respectively.
\section{Examples}
Example summaries are displayed in Tables \ref{tab:examples_billsum-1024-256_small_diverse}, \ref{tab:examples_billsum-1024-256_base_diverse}, \ref{tab:examples_billsum-4096-1024_base_diverse}, \ref{tab:examples_pubmed-4096-512_small_diverse}, and \ref{tab:examples_pubmed-4096-512_base_diverse}. Since the documents are very long sometimes, we truncated them to the first 2500 characters. We sorted the examples by RougeL scores and show the bottom 5\%, bottom 25\%, top 75\% and top 95\% percentile.
\renewcommand{\arraystretch}{0.2}
\include{summaries/billsum-1024-256_small_diverse}
\include{summaries/billsum-1024-256_base_diverse}
\include{summaries/billsum-4096-1024_base_diverse}
\include{summaries/pubmed-4096-512_small_diverse}
\include{summaries/pubmed-4096-512_base_diverse}
\section{Library Versions}
We used the following versions to the libraries in a pip requirements.txt format:\\
datasets==2.4.0\\
huggingface-hub==0.9.0\\
nltk==3.7\\
pandas==1.3.5\\
rouge-score==0.1.2\\
scikit-learn==1.0.2\\
scipy==1.7.3\\
tokenizers==0.12.1\\
torch==1.12.1\\
tqdm==4.64.0\\
transformers==4.21.1\\
\section{Detailed Results}
\label{sec:detailed_results}
\begin{table*}[t]
\centering
\resizebox{\textwidth}{!}{
\begin{tabular}{lrrrr}
\toprule
Model (max-in-len->max-gen-len) & \# Enc. Params $\downarrow$ & Rouge-1 $\uparrow$ & Rouge-2 $\uparrow$ & Rouge-L $\uparrow$ \\
\midrule
DOC + SUM (BERT large) & 340M & 40.80 & 23.83 & 33.73 \\
Transformer base & 110M & 44.05 & 21.30 & 30.98 \\
PEGASUS base & 110M & 51.42 & 29.68 & 37.78 \\
PEGASUS large (C4) & 468M & 57.20 & 39.56 & 45.80 \\
PEGASUS large (HugeNews) & 468M & 57.31 & 40.19 & 45.82 \\
BudgetLongformer small diverse (1024->128) & 29M & 53.61 & 33.54 & 42.50 \\
BudgetLongformer small diverse (1024->256) & 29M & 49.85 & 29.63 & 37.58 \\
BudgetLongformer base diverse (1024->256) & 159M & 52.70 & 32.97 & 40.50 \\
BudgetLongformer base diverse (1024->128) & 159M & 54.87 & 35.63 & 44.21 \\
BudgetLongformer base diverse (4096->1024) & 159M & 55.45 & 36.68 & 43.23 \\
\bottomrule
\end{tabular}
}
\caption{Results on the BillSum dataset. Enc. Params is short for Encoder Parameters. }
\label{tab:billsum_results}
\end{table*}
\begin{table*}[t]
\centering
\resizebox{\textwidth}{!}{
\begin{tabular}{lrrrr}
\toprule
Model (max-in-len->max-gen-len) & \# Enc. Params $\downarrow$ & Rouge-1 $\uparrow$ & Rouge-2 $\uparrow$ & Rouge-L $\uparrow$ \\
\midrule
Transformer base & 110M & 33.94 & 7.43 & 19.02 \\
PEGASUS base & 110M & 39.98 & 15.15 & 25.23 \\
PEGASUS large (C4) & 468M & 45.49 & 19.90 & 27.69 \\
PEGASUS large (HugeNews) & 468M & 45.09 & 19.56 & 27.42 \\
BudgetLongformer small diverse (4096->512) & 29M & 34.98 & 13.56 & 23.24 \\
BudgetLongformer base diverse (4096->512) & 159M & 41.16 & 18.15 & 26.53 \\
\bottomrule
\end{tabular}
}
\caption{Results on the PubMed dataset. Enc. Params is short for Encoder Parameters.
}
\label{tab:pubmed_results}
\end{table*}
\begin{table*}[t]
\centering
\resizebox{\textwidth}{!}{
\begin{tabular}{lrrrrrrrrrrrr}
\toprule
model & ECtHR A & ECtHR B & SCOTUS & EUR-LEX & LEDGAR & UNFAIR-ToS & CaseHOLD & Average \\
\midrule
small models\\
\midrule
BERT-Tiny & 63.7 / 44.0 & 63.9 / 50.4 & 61.1 / 35.7 & 57.9 / 25.0 & 83.8 / 73.3 & 93.9 / 11.1 & 66.2 & 70.1 / 43.7\\
miniLM & 67.9 / 55.1 & 66.6 / 61.0 & 60.8 / 45.5 & 62.2 / 35.6 & 86.7 / 79.6 & 93.9 / 13.2 & 71.3 & 72.8 / 51.6\\
DistilBERT & 69.9 / 61.1 & 70.5 / 69.1 & 67.0 / 55.9 & 66.0 / 51.5 & 87.5 / 81.5 & 97.1 / 79.4 & 68.6 & 75.2 / 66.7\\
LegalBERT-small & 70.4 / 62.6* & 71.3 / 69.4* & 71.3 / 59.7* & 66.1 / 48.2* & 87.8 / 82.0* & 97.4 / 81.7 & 72.9* & 76.7 / 68.1\\
BudgetLongformer small caselaw & 65.0 / 46.4 & 75.3 / 58.2 & 70.6 / 50.8*& 58.1 / 24.2 & 85.5 / 76.7 & 89.5 / 10.5 & 71.9* & 73.7 / 48.4\\
BudgetLongformer small diverse & 64.3 / 47.1 & 74.4 / 49.4 & 68.3 / 45.6* & 61.5 / 30.8* & 85.5 / 76.7* & 88.9 / 10.5 & 70.8* & 73.4 / 47.3\\
\midrule
base models\\
\midrule
BERT & 71.2 / 63.6 & 79.7 / 73.4 & 68.3 / 58.3 & 71.4 / 57.2 & 87.6 / 81.8 & 95.6 / 81.3 & 70.8 & 77.8 / 69.5\\
RoBERTa & 69.2 / 59.0 & 77.3 / 68.9 & 71.6 / 62.0 & 71.9 / 57.9 & 87.9 / 82.3 & 95.2 / 79.2 & 71.4 & 77.8 / 68.7\\
DeBERTa & 70.0 / 60.8 & 78.8 / 71.0 & 71.1 / 62.7 & 72.1 / 57.4 & 88.2 / 83.1 & 95.5 / 80.3 & 72.6 & 78.3 / 69.7\\
BigBird & 70.0 / 62.9 & 78.8 / 70.9 & 72.8 / 62.0 & 71.5 / 56.8 & 87.8 / 82.6 & 95.7 / 81.3 & 70.8 & 78.2 / 69.6\\
Longformer & 69.9 / 64.7 & 79.4 / 71.7 & 72.9 / 64.0 & 71.6 / 57.7 & 88.2 / 83.0 & 95.5 / 80.9 & 71.9 & 78.5 / 70.5\\
CaseLawBERT & 69.8 / 62.9 & 78.8 / 70.3 & 76.6 / 65.9* & 70.7 / 56.6 & 88.3 / 83.0 & 96.0 / 82.3 & 75.4* & 79.4 / 70.9\\
LegalBERT-base & 70.0 / 64.0* & 80.4 / 74.7* & 76.4 / 66.5* & 72.1 / 57.4* & 88.2 / 83.0* & 96.0 / 83.0 & 75.3* & 79.8 / 72.0\\
BudgetLongformer base caselaw & 67.2 / 55.9 & 76.6 / 61.1 & 74.9 / 62.3* & 64.7 / 42.9 & 86.9 / 80.4 & 89.5 / 10.5 & 72.1* & 76.0 / 55.0\\
BudgetLongformer base diverse & 66.3 / 52.6 & 77.9 / 72.3 & 75.4 / 62.9* & 65.6 / 44.4* & 87.0 / 81.0* & 95.1 / 76.7 & 71.3* & 76.9 / 65.9\\
\bottomrule
\end{tabular}
}
\caption{Results on LexGLUE. Because of limited compute, we only ran 1 random seed for our models. The other results are reported on GitHub\footnote{\url{https://github.com/coastalcph/lex-glue/discussions/categories/new-results}}. The asterix denotes datasets which are (partly) covered in the pretraining dataset. For each column we report the results in the format micro-averaged F1 score / macro-average F1 score. For the CaseHOLD task, both scores are the same.
}
\label{tab:lexglue_results}
\end{table*}
\begin{figure}[ht]
\centering
\resizebox{\columnwidth}{!}{
\includegraphics{plots/lexglue.png}
}
\vspace{-7mm}
\caption{Results on the LexGLUE benchmark (all models). Note that the x-axis is in log-scale.}
\label{fig:lexglue}
\vspace{-5mm}
\end{figure}
In this section, we show detailed and comprehensive results of the compared models (Tables \ref{tab:billsum_results}, \ref{tab:pubmed_results} and \ref{tab:lexglue_results} and Figure \ref{fig:lexglue}).
\section{Related Work}
\label{sec:related_work}
\subsection*{Domain-Specific Language Models}
Previous work showed that domain-specific pretraining shows promising results on datasets of specialized domains such as
law \cite{chalkidis_legal-bert_2020, xiao_lawformer_2021},
biology \cite{lee_biobert_2019},
scientific articles \cite{beltagy_scibert_2019},
clinical documents \cite{li_clinical-longformer_2022}, or even
code \cite{chen_evaluating_2021}.
\citet{gururangan_dont_2020} show that continued pretraining on a RoBERTa checkpoint on biomedical data, scientific articles in computer science, and reviews, clearly improves downstream performance in the respective domain-specific datasets. The effect was less pronounced on datasets from the news domain, presumably because RoBERTa has seen many news articles in its pretraining already.
\subsection*{Long Document Processing}
In the past few years, a vast amount of research has been devoted to addressing the problem of quadratic time and memory complexity associated with the dense attention mechanism \cite{vaswani_attention_2017}, practically limiting the maximum sequence length severely (often to 512 tokens) \cite{tay_efficient_2020, child_generating_2019, beltagy_longformer_2020, zaheer_big_2021, roy_efficient_2021, kitaev_reformer_2020, tay_synthesizer_2021, lee-thorp_fnet_2021}. These research works have given rise to a new class of transformers, referred to as sparse transformers or efficient transformers \cite{tay_efficient_2020}. Reducing the cost associated with the computation of the dense attention matrix while maintaining the same performance is the core idea behind efficient transformers. This is often achieved by introducing sparsity in the attention matrix in a variety of ways that may be fixed pattern such as local (windowed) attention \cite{child_generating_2019, beltagy_longformer_2020}, global attention \cite{zaheer_big_2021} or learnable patterns such as routing attention \cite{roy_efficient_2021} and LSH attention \cite{kitaev_reformer_2020} or a random pattern \cite{zaheer_big_2021, tay_synthesizer_2021}. Recently, \citet{lee-thorp_fnet_2021} proposed to use Fourier transforms instead of the attention layer. A comprehensive list of efficient transformers and the detailed description of their attention mechanism can be found in the survey by \citet{tay_efficient_2020}.
\cite{tay_long_2020} proposed a series of tasks designed for testing the capabilities of these different models suitable for longer inputs. However, this so-called ``Long Range Arena'' considers mostly artificial tasks, with the goal of evaluating the models independently of any pretraining.
\subsection*{Efficient Pretraining}
ELECTRA-style pretraining \cite{clark_electra_2020} has been shown to reduce training cost substantially, while matching the performance of \ac{SOTA} \acp{LM}. ELECTRA leverages a smaller generator model (discarded after pretraining), that changes some tokens. The larger discriminator model (used for down-stream tasks) must predict for each token if it was changed by the generator or not, similar to how \acp{GAN} are trained \cite{goodfellow_generative_2014}. This enables the loss to be relevant for every token, leading to much faster and thus more efficient training.
\section{Data Details}
\label{sec:data_details}
We used our own tokenizer to calculate the number of tokens. In Tables \ref{fig:billsum_train}, and \ref{fig:billsum_test} we show the data length distributions for the BillSum train and test splits. In Tables \ref{fig:pubmed_train}, \ref{fig:pubmed_validation}, and \ref{fig:pubmed_test} we show the data length distributions for the PubMed train, validation and test splits.
\begin{figure*}[ht]
\resizebox{\textwidth}{!}{
\subfloat[
\textbf{Input Text}\\
Mean: 1289, Median: 1166\\
75-Quant: 1644, 95-Quant: 2290, Max: 3055\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/billsum_train_input.png}
}}
\qquad
\subfloat[
\textbf{Summary}\\
Mean: 179, Median: 157\\
75-Quant: 240, 95-Quant: 398, Max: 808\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/billsum_train_summary.png}
}}
}
\caption{Histograms for the BillSum training set (18949 samples). }
\label{fig:billsum_train}
\vspace{-5mm}
\end{figure*}
\begin{figure*}[ht]
\resizebox{\textwidth}{!}{
\subfloat[
\textbf{Input Text}\\
Mean: 1284, Median: 1164\\
75-Quant: 1629, 95-Quant: 2288, Max: 2957\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/billsum_test_input.png}
}}
\qquad
\subfloat[
\textbf{Summary}\\
Mean: 179, Median: 156\\
75-Quant: 239, 95-Quant: 394, Max: 787\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/billsum_test_summary.png}
}}
}
\caption{Histograms for the BillSum test set (3269 samples). }
\label{fig:billsum_test}
\vspace{-5mm}
\end{figure*}
\clearpage
\begin{figure*}[ht]
\resizebox{\textwidth}{!}{
\subfloat[
\textbf{Input Text}\\
Mean: 3044, Median: 2572\\
75-Quant: 3996, 95-Quant: 7057, Max: 109759\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/pubmed_train_input.png}
}}
\qquad
\subfloat[
\textbf{Summary}\\
Mean: 202, Median: 208\\
75-Quant: 262, 95-Quant: 326, Max: 391\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/pubmed_train_summary.png}
}}
}
\caption{Histograms for the PubMed train set (119924 samples). }
\label{fig:pubmed_train}
\vspace{-5mm}
\end{figure*}
\begin{figure*}[ht]
\resizebox{\textwidth}{!}{
\subfloat[
\textbf{Input Text}\\
Mean: 3112, Median: 2609\\
75-Quant: 4011, 95-Quant: 6968, Max: 119269\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/pubmed_validation_input.png}
}}
\qquad
\subfloat[
\textbf{Summary}\\
Mean: 203, Median: 209\\
75-Quant: 263, 95-Quant: 330, Max: 518\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/pubmed_validation_summary.png}
}}
}
\caption{Histograms for the PubMed validation set (6633 samples). }
\label{fig:pubmed_validation}
\vspace{-5mm}
\end{figure*}
\begin{figure*}[ht]
\resizebox{\textwidth}{!}{
\subfloat[
\textbf{Input Text}\\
Mean: 3093, Median: 2596\\
75-Quant: 3964, 95-Quant: 6985, Max: 48750\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/pubmed_test_input.png}
}}
\qquad
\subfloat[
\textbf{Summary}\\
Mean: 205, Median: 213\\
75-Quant: 265, 95-Quant: 329, Max: 506\\
]
{{
\includegraphics[width=\textwidth/2]{data_info/pubmed_test_summary.png}
}}
}
\caption{Histograms for the PubMed test set (6658 samples). }
\label{fig:pubmed_test}
\vspace{-5mm}
\end{figure*}
\section{Overview of Compared Models}
\label{sec:models_overview}
\begin{table*}[t]
\centering
\resizebox{\textwidth}{!}{
\begin{tabular}{llrrrrrrrr}
\toprule
Model Name & Source & P. Steps (K) & P. BS & \# P. Examples (M) & \# Enc. Params (M) & Max Seq Len & Vocab Size (K) & PubMed Rouge-L & BillSum Rouge-L \\
\midrule
DOC + SUM & \cite{kornilova_billsum_2019} & 1000 & 256 & 256 & 340 & 512 & 30 & ~ & 33.73 \\
Transformer-base & \cite{zhang_pegasus_2020} & ~ & ~ & ~ & 110 & 1024 & 96 & 19.02 & 30.98 \\
PEGASUS-base & \cite{zhang_pegasus_2020} & 500 & 256 & 128 & 110 & 1024 & 96 & 25.23 & 37.78 \\
PEGASUS-large-C4 & \cite{zhang_pegasus_2020} & 500 & 8192 & 4096 & 340 & 1024 & 96 & 27.69 & 45.8 \\
BudgetLongformer small diverse & ours & 100 & 32 & 3.2 & 29 & 4096 & 64 & 23.24 & 37.58 \\
BudgetLongformer base diverse & ours & 100 & 32 & 3.2 & 159 & 4096 & 64 & 26.53 & 40.50 \\
\end{tabular}
}
\caption{Abbreviations: P.: Pretraining, BS: Batch Size, Enc.: Encoder, Params: Parameters.
Comparison of the models evaluated on the summarization tasks BillSum and PubMed.
}
\label{tab:summarization_models}
\end{table*}
\begin{table*}[t]
\centering
\resizebox{\textwidth}{!}{
\begin{tabular}{llrrrrrrrrrrr}
\toprule
Model Name & Source & P. Steps (K) & P. BS & D. Steps (K) & D. BS & WS Steps (K) & WS BS & \# P. Examples (M) $\downarrow$ & \# Params (M) $\downarrow$ & Max Seq Len $\uparrow$ & Vocab Size (K) & LexGLUE Micro-F1 $\uparrow$ \\
\midrule
small models \\
\midrule
BERT-Tiny & \cite{turc_well-read_2019} & 1000 & 256 & 1400 & 256 & ~ & ~ & 614.4 & 4.4 & 512 & 31 & 70.1 \\
miniLM & \cite{wang-etal-2021-minilmv2} & 1000 & 256 & 400 & 256 & ~ & ~ & 358.4 & 21 & 512 & 30 & 72.8 \\
DistilBERT & \cite{sanh_distilbert_2020} & 1000 & 256 & 500 & 256 & ~ & ~ & 384 & 66 & 512 & 30 & 75.2 \\
LegalBERT-small & \cite{chalkidis_legal-bert_2020} & 1000 & 256 & ~ & ~ & ~ & ~ & 256 & 35 & 512 & 31 & 76.7 \\
BudgetLongformer small caselaw & ours & 100 & 32 & ~ & ~ & ~ & ~ & 3.2 & 29 & 4096 & 64 & 73.9 \\
BudgetLongformer small diverse & ours & 100 & 32 & ~ & ~ & ~ & ~ & 3.2 & 29 & 4096 & 64 & 73.4 \\
\midrule
base models \\
\midrule
BERT & \cite{devlin_bert_2019} & 1000 & 256 & ~ & ~ & ~ & ~ & 256 & 110 & 512 & 30 & 77.8 \\
RoBERTa & \cite{liu_roberta_2019} & 500 & 8192 & ~ & ~ & ~ & ~ & 4096 & 125 & 512 & 31 & 77.8 \\
DeBERTa & \cite{he_debertav3_2021} & 1000 & 256 & ~ & ~ & ~ & ~ & 256 & 139 & 512 & 128 & 78.3 \\
BigBird & \cite{zaheer_big_2021} & 500 & 8192 & ~ & ~ & 500 & 256 & 4224 & 127 & 4096 & 50 & 78.2 \\
Longformer & \cite{beltagy_longformer_2020} & 500 & 8192 & ~ & ~ & 65 & 64 & 4100.16 & 149 & 4096 & 31 & 78.5 \\
Legal-BERT-base & \cite{chalkidis_legal-bert_2020} & 1000 & 256 & ~ & ~ & ~ & ~ & 256 & 110 & 512 & 31 & 79.8 \\
CaseLaw-BERT & \cite{zheng_when_2021} & 2000 & 256 & ~ & ~ & ~ & ~ & 512 & 110 & 512 & 30 & 79.4 \\
BudgetLongformer base caselaw & ours & 100 & 32 & ~ & ~ & ~ & ~ & 3.2 & 159 & 4096 & 64 & 76.0 \\
BudgetLongformer base diverse & ours & 100 & 32 & ~ & ~ & ~ & ~ & 3.2 & 159 & 4096 & 64 & 76.9 \\
\bottomrule
\end{tabular}
}
\caption{Abbreviations: P.: Pretraining, D.: Distillation, WS: Warm Start, BS: Batch Size, Params: Parameters.
Comparison of the models evaluated on LexGLUE. In cases where we were not able to find the batch size in the papers, we assumed it to be 256, since this is the most widely used batch size in pretraining and the default for BERT. For DistilBERT we were not able to find the number of distillation steps, so we assumed 500K steps.
}
\label{tab:lexglue_models}
\end{table*}
In this section, we show detailed overviews of the model specifics (Tables \ref{tab:summarization_models} and \ref{tab:lexglue_models}).
| {'timestamp': '2022-12-01T02:18:40', 'yymm': '2211', 'arxiv_id': '2211.17135', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17135'} | arxiv |
\section{Introduction}
\label{sec:introduction}
Large autoregressive models, notably large Transformers, are much more capable than smaller models, as is evidenced countless times in recent years e.g., in the text or image domains, like GPT-3 \citep{gpt3}, LaMDA \citep{lamda}, Parti \citep{parti}, and PaLM \citep{palm}. Unfortunately, a single decode step from these larger models is significantly slower than a step from their smaller counterparts, and making things worse, these steps are done serially - decoding $K$ tokens takes $K$ serial runs of the model.
Since large autoregressive models and specifically large Transformers are so important, several approaches were developed to make inference from them faster.
Some approaches aim to reduce the inference cost for \emph{all} inputs equally
\citep[e.g.][]{Distilling_the_Knowledge_in_a_Neural_Network, Sparse_is_Enough_in_Scaling_Transformers, Quantized_Neural_Networks, Primer, multi-query-attn}.
Other approaches stem from the observation that not all inference steps are born alike - some require a very large model, while others can be approximated well by more efficient models. These \emph{adaptive computation} methods
\citep[e.g.][]{Dynamic_Neural_Networks_Survey, Adaptive_Attention_Span_in_Transformers, Confident_Adaptive_Transformers, early_exits, Controlling_Computation_versus_Quality_Sequence_Models, depth_adaptive_transformer, Matching_Model_and_Instance_Complexities}
aim to use less compute resources for the easier inference steps.
While many of these solutions have proven extremely effective in practice, they usually require changing the model architecture, changing the training-procedure and re-training the models, and don't maintain identical outputs.
The key observation above, that some inference steps are ``harder'' and some are ``easier'', is also a key motivator for our work.
We additionally observe that inference from large models is often not bottlenecked on arithmetic operations, but rather on memory bandwidth and communication, so additional computation resources might be available.
Therefore we suggest increasing concurrency as a complementary approach to using an adaptive amount of computation. Specifically, we are able to accelerate inference without changing the model architectures, without changing the training-procedures or needing to re-train the models, and without changing the model output distribution. This is accomplished via \emph{speculative execution}.
Speculative execution \cite{speculative_computation, HennessyPatterson12} is an optimization technique, common in processors, where a task is performed in parallel to verifying if it's actually needed - the payoff being increased concurrency. A well-known example of speculative execution is branch prediction.
For speculative execution to be effective, we need an efficient mechanism to suggest tasks to execute that are likely to be needed.
In this work, we generalize speculative execution to the stochastic setting - where a task \emph{might be} needed with some probability.
Applying this to decoding from autoregressive models like Transformers, we sample generations from \emph{small approximation models} as speculative prefixes for the large models.
With a novel sampling method, \emph{speculative sampling}, we maximize the probability of these speculative tasks to be accepted, while guaranteeing that the outputs from our system have the same distribution as those from the large model alone.
For example, the sentence in figure \ref{fig:autocomplete}, consisting of 38 tokens, was generated by our method with only 9 serial runs of a larger model (97M parameters) thanks to approximations by a smaller model (6M parameters),
while the probability of generating it is unchanged.
We analyze our method in a variety of tasks and model sizes: unconditional generation from a 97M parameter GPT-like model trained on lm1b, English to German translation and news article summarization with an 11B parameters T5-XXL model, and a dialog task with a 137B parameter LaMDA model. We implement our method and compare actual walltimes for T5-XXL to those of the robust T5X implementation \cite{t5x}, showing an out-of-the-box latency improvement of \textbf{2X-3X}, without any change to the outputs (\cref{sec:experiments}).
Our method is easy to employ in actual production settings, doesn't require training new models, and doesn't change the outputs.
Therefore, in common situations where memory bandwidth is the bottleneck, and compute resources are available, it may be a good default to accelerate sampling from autoregressive models like Transformers.
To summarize, our main contributions are: (1) A generalization of speculative execution to the stochastic setting, with a novel sampling method we call \emph{speculative sampling}, and (2) A decoding mechanism we call \emph{speculative decoding} that can accelerate decoding from autoregressive models, without any change to the model architectures, training regimes and output distributions.
\section{Speculative Decoding}
\subsection{Overview}
Let $M_p$ be the large model, inference from which we're trying to accelerate, and $p(x_t|x_{<t})$ the distribution we get from the model for a prefix $x_{<t}$. Let $M_q$ be a smaller and more efficient approximation model for the same task, and denote by $q(x_t|x_{<t})$ the distribution we get from the model for a prefix $x_{<t}$\footnote{
We'll use $p(x)$ to denote $p(x_t|x_{<t})$ whenever the prefix $x_{<t}$ is clear from the context, and similarly for $q(x)$.}. The core idea is to (1) use the more efficient model $M_q$ to generate $\gamma \in \mathbb{Z}^+$ completions (see \cref{sec:optimal_gamma} for how to optimally choose this parameter), then (2) use the larger model $M_p$ to evaluate all of the guesses and their respective probabilities from $M_q$ in parallel, accepting all those that \emph{can} lead to an identical distribution, and (3) sampling an additional token from an adjusted distribution to fix the first one that was rejected, or to add an additional one if they are all accepted. That way, each parallel run of the large model $M_p$ will produce at least one new token (so the number of serial runs of the large model can never, even in the worst case, be larger than the simple autoregressive method), but it can potentially generate many new tokens, up to $\gamma + 1$, depending on how well $M_q$ approximates $M_p$.
\subsection{Standardized Sampling}
\label{sec:sample_with_approx}
First, note that while there are many methods and parameters of sampling, like argmax, top-k, nucleus, and setting a temperature, and popular implementations usually treat them differently at the logits level, they can all easily be cast into standard sampling from an adjusted probability distribution. For example, argmax sampling is equivalent to zeroing out non-max elements of the distribution and normalizing. We can therefore only deal with standard sampling from a probability distribution, and cast all of the other types of sampling into that framework. Going forward we'll assume that $p(x)$ and $q(x)$ are the distributions from $M_p$ and $M_q$ respectively, adjusted for the sampling method.
\subsection{Speculative Sampling}
\label{sec:speculative_sampling}
To sample $x \sim p(x)$, we instead sample $x \sim q(x)$, keeping it if $q(x) \le p(x)$, and in case $q(x) > p(x)$ we reject the sample with probability $1 - \frac{p(x)}{q(x)}$ and sample $x$ again from an adjusted distribution $p'(x) = norm(max(0, p(x) - q(x)))$ instead. It’s easy to show (see \cref{appendix:correctness}) that for any distributions $p(x)$ and $q(x)$, and $x$ sampled in this way, indeed $x \sim p(x)$.
Given the distribution $q(x)$ obtained from running $M_q$ on a conditioning $prefix$, we can sample a token $x_1 \sim q(x)$. We then calculate the distribution $p(x)$ by running $M_p$ on $prefix$ while in parallel speculatively calculating the distribution of the next token $x_2$ by running $M_p$ on $prefix + [x_1]$. Once both computations complete, we proceed as per above: If $x_1$ is rejected, we discard the computation of $x_2$ and re-sample $x_1$ from an adjusted distribution, and if $x_1$ is accepted, we keep both tokens. \cref{alg:sample_with_approx} generalizes this idea to sample between 1 and $\gamma + 1$ tokens at once.
\newcommand{\COMMENTLLAMA}[1]{{\color{darkgreen} $\triangleright$ {#1}}}
\begin{algorithm}
\caption{SpeculativeDecodingStep}
\label{alg:sample_with_approx}
\begin{algorithmic}
\STATE {\bfseries Inputs:} $M_p, M_q, prefix$.
\STATE \COMMENTLLAMA{Sample $\gamma$ guesses $x_{1,\ldots,\gamma}$ from $M_q$ autoregressively.}
\FOR{$i=1$ {\bfseries to} $\gamma$}
\STATE $q_i(x) \gets M_q(prefix + [x_1, \ldots, x_{i-1}])$
\STATE $x_i \sim q_i(x)$
\ENDFOR
\STATE \COMMENTLLAMA{Run $M_p$ in parallel.}
\STATE $p_1(x), \ldots, p_{\gamma + 1}(x) \gets$
\STATE \quad \quad $M_p(prefix), \ldots, M_p(prefix + [x_1, \ldots, x_{\gamma}])$
\STATE \COMMENTLLAMA{Determine the number of accepted guesses $n$.}
\STATE $r_1 \sim U(0, 1), \dots, r_\gamma \sim U(0, 1)$
\STATE $n \gets \min(\{ i - 1 \mid 1 \le i \le \gamma, r_i > \frac{p_i(x)}{q_i(x)} \} \cup \{ \gamma \})$
\STATE \COMMENTLLAMA{Adjust the distribution from $M_p$ if needed.}
\STATE $p'(x) \gets p_{n+1}(x)$
\IF{$n < \gamma$}
\STATE $p'(x) \gets norm(max(0, p_{n+1}(x) - q_{n+1}(x)))$
\ENDIF
\STATE \COMMENTLLAMA{Return one token from $M_p$, and $n$ tokens from $M_q$.}
\STATE $t \sim p'(x)$
\STATE {\bfseries return} $prefix + [x_1, \ldots, x_{n}, t]$
\end{algorithmic}
\end{algorithm}
\section{Analysis}
\subsection{Number of Generated Tokens}
Let's analyze the reduction factor in the number of serial calls to the large model, or equivalently, the expected number of tokens produced by a single run of \cref{alg:sample_with_approx}.
\begin{definition}
\label{def:beta_prefix}
The \emph{acceptance rate $\beta_{x_{<t}}$}, given a prefix $x_{<t}$, is the probability of accepting $x_t \sim q(x_t|x_{<t})$ by speculative sampling, as per \cref{sec:speculative_sampling}\footnote{We'll omit the $x_{<t}$ subscript whenever the prefix is clear from the context.}.
\end{definition}
$E(\beta)$ is a natural measure of how well $M_q$ approximates $M_p$. If we make the simplifying assumption that the $\beta$s are i.i.d., and denote $\alpha = E(\beta)$, then the number of tokens produced by a single run of \cref{alg:sample_with_approx} is a capped geometric variable, with $p = 1 - \alpha$ and $cap = \gamma + 1$, and the expected number of tokens generated by \cref{alg:sample_with_approx} satisfies \cref{eq:expected_num_tokens}. See \cref{fig:alpha_v_tokens}.
\begin{equation}
\label{eq:expected_num_tokens}
E(\#\ generated\ tokens) = \frac{1 - \alpha^{\gamma + 1}}{1 - \alpha}
\end{equation}
\begin{figure}[ht]
\begin{center}
\centerline{\includegraphics[width=\columnwidth]{alpha_v_tokens.pdf}}
\caption{The expected number of tokens generated by \cref{alg:sample_with_approx} as a function of $\alpha$ for various values of $\gamma$.}
\label{fig:alpha_v_tokens}
\end{center}
\vskip -0.2in
\end{figure}
\subsection{Calculating $\alpha$}
We'll now derive a simple formula for calculating $\alpha$ given a prefix and the two models $M_p$ and $M_q$. We start by defining a natural divergence $D_{LK}$:
\begin{definition}
\label{def:dlk}
$D_{LK}(p, q) = \sum_{x}|p(x) - M(x)| = \sum_{x}|q(x) - M(x)|$ where $M(x) = \frac{p(x) + q(x)}{2}$.
\end{definition}
\begin{lemma}
\label{lemma:dlk}
$D_{LK}(p, q) = 1 - \sum_x\min(p(x), q(x))$
\end{lemma}
\begin{proof}
$D_{LK}(p, q) = \sum_{x}|p(x) - M(x)| = \sum_x\frac{|p-q|}{2}= 1 - \sum_x\frac{p + q - |p - q|}{2} = 1 - \sum_x\min(p(x), q(x))$
\end{proof}
From \cref{lemma:dlk} we immediately get the following results:
\begin{corollary}
\label{cor:dlk_properties}
$D_{LK}(p, q)\ \text{is a symmetric divergence in}\ [0, 1].\\
D_{LK}(p, q) = 0 \iff p = q. \\
D_{LK}(p, q) = 1 \iff \text{p and q have disjoint support}.$
\end{corollary}
\begin{theorem}
\label{thm:dlk_beta}
$\beta = 1 - D_{LK}(p, q)$
\end{theorem}
\begin{proof}
$\beta = E_{x \sim q(x)}\left\lbrace
\begin{tabular}{@{}p{0.5cm}p{1.8cm}}
$1$ & $q(x) \le p(x)$ \\
$\frac{p(x)}{q(x)}$ & $q(x) > p(x)$ \\
\end{tabular}\right. =
E_{x \sim q(x)}\min(1, \frac{p(x)}{q(x)}) =
\sum_x\min(p(x), q(x))$
\end{proof}
Finally we get:
\begin{corollary}
\label{thm:dlk_alpha}
$\alpha = 1 - E(D_{LK}(p, q))$
\end{corollary}
In experiments with various tasks, sampling methods, and off-the-shelf models where $M_q$ is around 2 orders of magnitude smaller than $M_p$, we observe empirical $\alpha$ values in the range 0.5-0.9. See \cref{tbl:empirical alphas}.
\subsection{Walltime Improvement}
\label{sec:latency_imp}
We've shown that with the i.i.d. assumption our algorithm reduces the number of calls to the large model by a factor of $\frac{1 - \alpha^{\gamma + 1}}{1 - \alpha}$.
Note that speculative execution in general, and our algorithm in particular, assume that we have enough compute resources to support the increased concurrency (\cref{sec:arithmetic_ops}). For the walltime anaylsis, we'll assume that we can run $\gamma + 1$ concurrent evaluations of $M_p$ in parallel without increasing the walltime.
To get the total walltime improvement, we now consider the cost of running the small model $M_q$.
\begin{definition}
\label{def:c}
Let $c$, the \emph{cost coefficient}, be the ratio between the time for a single run of $M_q$ and the time for a single run of $M_p$.
\end{definition}
Note that unlike $\alpha$ which is an intrinsic property of the models and the task, the value of $c$ depends on the hardware configuration and software implementation details. In our experiments where $M_q$ is typically a couple of orders of magnitude smaller than $M_p$, $c$ was always less than $0.05$ and often negligibly close to 0.
\begin{theorem}
\label{thm:total_walltime}
The expected improvement factor in total walltime by \cref{alg:sample_with_approx} is $\frac{1 - \alpha^{\gamma + 1}}{(1-\alpha)({\gamma}c + 1)}$.
\end{theorem}
\begin{proof}
Denote the cost of running a single step of $M_p$ by $T$. Now, each run of \cref{alg:sample_with_approx} costs $Tc\gamma + T$ (for running the approximation model $M_q$ $\gamma$ times and running $M_p$ once) and according to \cref{eq:expected_num_tokens} produces $\frac{1 - \alpha^{\gamma + 1}}{1 - \alpha}$ tokens on average.
So the overall expected cost for producing a token with \cref{alg:sample_with_approx} is $\frac{(c\gamma + 1)(1-\alpha)}{1 - \alpha^{\gamma + 1}}T$.
Since the cost of producing a single token with the standard decoding algorithm is $T$, we get the desired result.
\end{proof}
Note that \cref{thm:total_walltime} assumes long enough generations (for example, since we run $M_p$ at least once, the improvement factor is capped by the number of generated tokens).
\begin{corollary}
\label{lemma:condition_for_improvement}
If $\alpha > c$, there exists $\gamma$ for which we'll get an improvement, and the improvement factor will be at least $\frac{1 + \alpha}{1 + c}$.
\end{corollary}
\begin{proof}
If we get an improvement for $\gamma$, we’d also get an improvement for any $0 < \gamma^* < \gamma$, so for our method to yield an improvement, we can evaluate \cref{thm:total_walltime} for $\gamma=1$, yielding $\frac{1 - \alpha^2}{(1-\alpha)(c + 1)} = \frac{1 + \alpha}{1 + c}$.
\end{proof}
\subsection{Number of Arithmetic Operations}
\label{sec:arithmetic_ops}
\cref{alg:sample_with_approx} does $\gamma + 1$ runs of $M_p$ in parallel, so the number of \emph{concurrent} arithmetic operations grows by a factor of $\gamma + 1$.
Now, since \cref{alg:sample_with_approx} produces at most $\gamma + 1$ tokens per run, the \emph{total} number of arithmetic operations might be higher than that of the standard decoding algorithm.
When we accept the sample from $M_q$ the increased concurrency is ``free'' and the total number of operations isn't increased\footnote{Neglecting the cost of $M_q$.}. When we reject a guess though, computation is wasted.
Let's now analyze the effect of our method on the total number of arithmetic operations.
\begin{definition}
Let $\hat{c}$ be the ratio of arithmetic operations per token of the approximation model $M_q$ to that of the large model $M_p$.
\end{definition}
\begin{theorem}
\label{thm:num_ops}
The expected factor of increase in the number of total operations of \cref{alg:sample_with_approx} is $\frac{(1-\alpha)({\gamma}\hat{c} + \gamma + 1)}{1 - \alpha^{\gamma + 1}}$.
\end{theorem}
\begin{proof}
Denote by $\hat{T}$ the number of arithmetic operations done by a standard decoding baseline per token, i.e. the number of operations of a single run of $M_p$. Then a single iteration of \cref{alg:sample_with_approx} costs $\hat{T}\hat{c}\gamma + \hat{T}(\gamma + 1)$ operations (for $\gamma$ runs of $M_q$ and $\gamma + 1$ parallel runs of $M_p$). Dividing by the expected number of tokens produced by \cref{alg:sample_with_approx}, i.e. \cref{eq:expected_num_tokens}, we get the desired result.
\end{proof}
If $\alpha$ is low, the increase in the number of arithmetic operations is high, and vice-versa.
Note that for Transformer decoders, the total number of arithmetic operations by \cref{alg:sample_with_approx} (not counting runs of $M_q$) can be bounded from above by a single run of the same-size Transformer encoder.
Unlike the total number of arithmetic operations, the total number of memory accesses can go down with our method. Specifically, the large model's weights and caches can be read once per execution of \cref{alg:sample_with_approx}, so the number of memory accesses for reading them shrinks by a factor of $\frac{1 - \alpha^{\gamma + 1}}{1 - \alpha}$, according to \cref{eq:expected_num_tokens}.
\begin{figure}[ht]
\vskip 0.2in
\begin{center}
\centerline{\includegraphics[width=\columnwidth]{alpha_v_optimal_gamma.pdf}}
\caption{The optimal $\gamma$ as a function of $\alpha$ for various values of $c$.}
\label{fig:alpha_v_optimal_gamma}
\end{center}
\vskip -0.2in
\end{figure}
\subsection{Choosing \texorpdfstring{$\gamma$}{gamma}}
\label{sec:optimal_gamma}
Given $c$ and $\alpha$ and assuming enough compute resources (see \cref{sec:arithmetic_ops}), the optimal $\gamma$ is the one maximizing the walltime improvement equation (\cref{thm:total_walltime}): $\frac{1 - \alpha^{\gamma + 1}}{(1-\alpha)({\gamma}c + 1)}$. Since $\gamma$ is an integer, it can be easily found numerically, see \cref{fig:alpha_v_optimal_gamma}. Depending on the amount of compute resources at our disposition, we might want to choose $\gamma$ values that are lower than the optimal value for unbounded computational power.
\cref{table:non optimal gamma} and \cref{fig:arithm_ops} illustrate the trade-off between inference speed and total number of arithmetic operations for various values of $\alpha$ and $\gamma$, assuming $c = \hat{c} = 0$.
\cref{fig:xprof} shows a simplified trace diagram.
\begin{table}[ht]
\caption{The total number of arithmetic operations and the inference speed vs the baseline, for various values of $\gamma$ and $\alpha$, assuming $c = \hat{c} = 0$.}
\label{table:non optimal gamma}
\vskip 0.15in
\begin{center}
\begin{small}
\begin{sc}
\begin{tabular}{lcccr}
\toprule
$\alpha$ & $\gamma$ & Operations & Speed \\
\midrule
0.6 & 2 & 1.53X & 1.96X \\
0.7 & 3 & 1.58X & 2.53X \\
0.8 & 2 & 1.23X & 2.44X \\
0.8 & 5 & 1.63X & 3.69X \\
0.9 & 2 & 1.11X & 2.71X \\
0.9 & 10 & 1.60X & 6.86X \\
\bottomrule
\end{tabular}
\end{sc}
\end{small}
\end{center}
\vskip -0.1in
\end{table}
\begin{figure}[ht]
\vskip 0.2in
\begin{center}
\centerline{\includegraphics[width=\columnwidth]{arith_ops.pdf}}
\caption{The speed improvement and increase in number of operations as a function of $\alpha$ for various values of $\gamma$.}
\label{fig:arithm_ops}
\end{center}
\vskip -0.2in
\end{figure}
\begin{figure*}
\includegraphics[width=1\linewidth]{trace_diagram.pdf}
\caption[xprof]{A simplified trace diagram for a full encoder-decoder Transformer stack. In this case we have enough computational power so that the calls to $M_p$ all take about the same time. The top row shows decoding with our method with $\gamma=7$ so each of the calls to $M_p$ (the purple blocks) is preceded by 7 calls to $M_q$ (the blue blocks). The yellow block on the left is the call to the encoder for $M_p$ and the orange block is the call to the encoder for $M_q$. Likewise the middle row shows our method with $gamma=3$, and the bottom row shows standard decoding.}
\centering
\label{fig:xprof}
\end{figure*}
Instead of picking a single value for $\gamma$ based on $\alpha$, since the $\beta$s aren’t constant,
we could get a further improvement by predicting the value of $\beta$ and accordingly varying the value of $\gamma$ for each run of \cref{alg:sample_with_approx}. To get an upper bound on the additional improvement factor, assume we had an oracle for $\gamma$. We would then have $E(\#\ generated\ tokens) = \frac{1}{1-\alpha}$.
For typical values of $c$ and $\alpha$, and assuming unbounded compute resources, the enhanced walltime improvement factor can be up to $\sim$60\% higher than the improvement factor with a fixed $\gamma$. We leave exploring this for future work\footnote{The above bound assumes that we still run $M_p$ to verify the oracle's predictions. If we skip those verifications the bound doesn't hold and we would get a substantial additional improvement.}.
\subsection{Special Approximation Models}
An interesting type of approximation models are those for which $c \approx 0$, i.e. approximation models with a negligible cost relative to the larger model. Some examples include n-gram models. In this case, we get an expected walltime improvement of $\frac{1 - \alpha^{\gamma + 1}}{1 - \alpha}$, which is bounded from above by $\frac{1}{1 - \alpha}$ (we approach equality if $\gamma$ is large).
Interestingly, in empirical tests (\cref{sec:empirical_alphas}) we get non-0 $\alpha$s in these cases. For example, for the English-German translation task, with $M_p$ being T5-XXL 11B and $M_q$ being a trivial bigram model, we get $\alpha \approx 0.2$ which leads to an inference speed improvement factor of $1.25$X with $\gamma=3$.
Our algorithm can also trivially be extended to cases where the approximation model $M_q$ is non-autoregressive. Then, instead of the autogreressive loop in \cref{alg:sample_with_approx} we'd just call the non-autoregressive model once. This would usually require training a custom non-autoregressive model and we haven't experimented with this setup yet.
Another example, interesting mostly from a theoretical perspective, is an approximation model which chooses tokens at random, which guarantees some improvement (although very small) for all models $M_p$.
\section{Experiments}
\label{sec:experiments}
\subsection{Empirical Walltime Improvement}
\label{sec:empirical-t5-time}
We implement our algorithm and compare it to the implementation in the T5X codebase for accelerating T5-XXL\footnote{Note that we did not extensively optimize our implementation, so a production grade implementation of our method might produce somewhat greater improvements over the baseline.}.
\paragraph{Setup} We test a standard encoder-decoder T5 version 1.1 model \citep{t5} on two tasks from the T5 paper: (1) English to German translation fine tuned on WMT EnDe, and (2) Text summarization fine tuned on CCN/DM. For both tasks, we use T5-XXL (11B) for $M_p$. For the approximation model $M_q$ we test several existing configurations, namely T5-large (800M), T5-base (250M), and T5-small (77M) \citep{t5}. We use existing checkpoints for all models. We measure walltime improvements with a batch size of 1 on a single TPU-v4 for both argmax sampling (temp=0) and standard sampling (temp=1).
\paragraph{Results}
\cref{tbl:t5 model results} shows the empirical results from our method. We see that T5-small (60M), with a good balance of $c$ and $\alpha$, provides the highest speedup out of the tested approximation models. As expected we see that $\alpha$ increases with the size of the approximation model. Interestingly, $\alpha$ and walltime improvement are higher for argmax sampling (temp=0). We observe speedups of 2.6X (temp=1) and 3.4X (temp=0) on the translation task and slightly lower speedups of 2.3X (temp=1) and 3.1X (temp=0) for the summarization task.
\begin{table}[ht]
\caption{Empirical results for speeding up inference from a T5-XXL 11B model.}
\label{tbl:t5 model results}
\vskip 0.15in
\begin{center}
\begin{small}
\begin{sc}
\begin{tabular}{llcccrr}
\toprule
Task & $M_q$ & Temp & $\gamma$ & $\alpha$ & Speed\\
\midrule
EnDe & T5-small $\bigstar$ & 0 & 7 & 0.75 & \textbf{3.4X}\\
EnDe & T5-base & 0 & 7 & 0.8 & 2.8X \\
EnDe & T5-large & 0 & 7 & 0.82 & 1.7X\\
EnDe & T5-small $\bigstar$ & 1 & 7 & 0.62 & \textbf{2.6X}\\
EnDe & T5-base & 1 & 5 & 0.68 & 2.4X \\
EnDe & T5-large & 1 & 3 & 0.71 & 1.4X \\
\midrule
CNNDM & T5-small $\bigstar$ & 0 & 5 & 0.65 & \textbf{3.1X} \\
CNNDM & T5-base & 0 & 5 & 0.73 & 3.0X \\
CNNDM & T5-large & 0 & 3 & 0.74 & 2.2X\\
CNNDM & T5-small $\bigstar$ & 1 & 5 & 0.53 & \textbf{2.3X}\\
CNNDM & T5-base & 1 & 3 & 0.55 & 2.2X \\
CNNDM & T5-large & 1 & 3 & 0.56 & 1.7X \\
\bottomrule
\end{tabular}
\end{sc}
\end{small}
\end{center}
\vskip -0.1in
\end{table}
\subsection{Empirical $\alpha$ Values}
\label{sec:empirical_alphas}
While we only implemented our method for T5, we measured $\alpha$ values for various tasks, sampling methods, models $M_p$ and corresponding approximation models $M_q$. Specifically, we evaluated the expectation from \cref{thm:dlk_alpha} on 10K tokens generated by $M_p$, for each of the settings below.
\paragraph{GPT-like (97M params)}We test a decoder-only Transformer model on unconditional language generation, trained on lm1b \citep{lm1b}. The model here is a GPT-like Transformer decoder-only with Gelu activations \citep{gelu}. For $M_q$ we experimented with a Transformer decoder-only model with 6M parameters: dim 256, dim feed-forward 1024, 2 layers, 4 attention heads, as well as simple unigram and bigram models. $M_p$ has 97M parameters: dim 768, dim feed-forward 3072, 12 layers, 12 attention heads. We used Bert tokenization \citep{bert} with 8k tokens for all models.
\paragraph{LaMDA (137B params)} We tested a decoder only LaMDA model on a dialog task \citep{lamda}.
We used existing checkpoints from LaMDA 137B as $M_p$ and LaMDA 8B, LaMDA 2B, and LaMDA 100M for $M_q$.
See \cref{sec:empirical-t5-time} for the setup of the T5-XXL (11B params) model.
\cref{tbl:empirical alphas} summarizes the $\alpha$ values for the tested cases. We observe that in all cases approximation models that are a couple of orders of magnitude smaller than the large model tend to produce $\alpha$ values between 0.5 and 0.9. Interestingly, we also note that for all models, the sharper the adjusted distribution, the higher the $\alpha$ values. Finally, we note that even trivial unigram and bigram approximations yield non-0 $\alpha$ values. For example, for the case of English to German translation, the bigram model gets an $\alpha$ of 0.2, and since $c=0$ in this case, yields a 1.25X speed improvement, which is surprisingly high for this trivial approximation model (but is still lower than the speedup we get from using T5-small as the approximation model).
\stepcounter{footnote}
\begin{table}[ht]
\caption{Empirical $\alpha$ values for various models $M_p$, approximation models $M_q$, and sampling settings. T=0 and T=1 denote argmax and standard sampling respectively\footnotemark[\value{footnote}].}
\label{tbl:empirical alphas}
\vskip 0.15in
\begin{center}
\begin{small}
\begin{sc}
\begin{tabular}{lllccr}
\toprule
$M_p$ & $M_q$ & Smpl & $\alpha$ \\
\midrule
GPT-like (97M) & Unigram & t=0 & 0.03\\
GPT-like (97M) & Bigram & t=0 & 0.05\\
GPT-like (97M) & GPT-like (6M) & t=0 & 0.88\\
GPT-like (97M) & Unigram & t=1 & 0.03\\
GPT-like (97M) & Bigram & t=1 & 0.05\\
GPT-like (97M) & GPT-like (6M) & t=1 & 0.89\\
\midrule
\midrule
T5-XXL (EnDe) & Unigram & t=0 & 0.08 \\
T5-XXL (EnDe) & Bigram & t=0 & 0.20 \\
T5-XXL (EnDe) & T5-small & t=0 & 0.75\\
T5-XXL (EnDe) & T5-base & t=0 & 0.80\\
T5-XXL (EnDe) & T5-large & t=0 & 0.82\\
T5-XXL (EnDe) & Unigram & t=1 & 0.07 \\
T5-XXL (EnDe) & Bigram & t=1 & 0.19 \\
T5-XXL (EnDe) & T5-small & t=1 & 0.62\\
T5-XXL (EnDe) & T5-base & t=1 & 0.68\\
T5-XXL (EnDe) & T5-large & t=1 & 0.71 \\
\midrule
\midrule
T5-XXL (CNNDM) & Unigram & t=0 & 0.13 \\
T5-XXL (CNNDM) & Bigram & t=0 & 0.23 \\
T5-XXL (CNNDM) & T5-small & t=0 & 0.65\\
T5-XXL (CNNDM) & T5-base & t=0 & 0.73\\
T5-XXL (CNNDM) & T5-large & t=0 & 0.74\\
T5-XXL (CNNDM) & Unigram & t=1 & 0.08 \\
T5-XXL (CNNDM) & Bigram & t=1 & 0.16 \\
T5-XXL (CNNDM) & T5-small & t=1 & 0.53 \\
T5-XXL (CNNDM) & T5-base & t=1 & 0.55 \\
T5-XXL (CNNDM) & T5-large & t=1 & 0.56 \\
\midrule
\midrule
LaMDA (137B) & LaMDA (100M) & t=0 & 0.61\\
LaMDA (137B) & LaMDA (2B) & t=0 & 0.71\\
LaMDA (137B) & LaMDA (8B) & t=0 & 0.75\\
LaMDA (137B) & LaMDA (100M) & t=1 & 0.57\\
LaMDA (137B) & LaMDA (2B) & t=1 & 0.71\\
LaMDA (137B) & LaMDA (8B) & t=1 & 0.74\\
\bottomrule
\end{tabular}
\end{sc}
\end{small}
\end{center}
\vskip -0.1in
\end{table}
\section{Related work}
The efficiency of inference from large models was studied extensively \citep{The_Efficiency_Misnomer}. A lot of interesting work is trying to make inference from large models in general, and autoregressive models like Transformers in particular, more efficient. Many techniques try to make inference more efficient for all tokens, e.g. distillation \citep{Distilling_the_Knowledge_in_a_Neural_Network}, sparcification \citep{Sparse_is_Enough_in_Scaling_Transformers}, quantization \citep{Quantized_Neural_Networks}, and architecture modification \citep{Primer, multi-query-attn}. Closer to our approach are adaptive computation methods which adapt the amount of computation to problem difficulty \citep{Dynamic_Neural_Networks_Survey}. Examples include attending to a subset of the inputs \citep{Adaptive_Attention_Span_in_Transformers}, and early exits \citep{Confident_Adaptive_Transformers, early_exits, Controlling_Computation_versus_Quality_Sequence_Models, depth_adaptive_transformer, Matching_Model_and_Instance_Complexities}.
These methods usually learn, either within the model itself or with an auxiliary model, when a computation shortcut can be taken.
Usually, these methods save on both inference time and arithmetic operations, but require a change of architecture, a change of training procedure and training custom models or re-training of existing models.
These methods also usually change the outputs of the model.
We note that while many of these methods improve the memory to arithmetic-operations ratio, in cases where the ratio remains high, these methods and our speculative decoding method might be effective in tandem.
We recently became aware of Shallow Aggressive Decoding (SAD) \citep{sad}, which also decodes several tokens in parallel, similarly to our work. Unlike our work, it doesn't use a small approximation model but instead copies the input to the output, making it only suitable to cases where the inputs and outputs are very similar, like for grammatical error correction. In addition, SAD does not support the general stochastic sampling setting. Wisdom of Committes (WoC) \citep{Matching_Model_and_Instance_Complexities} leverages off-the-shelf smaller models, similarly to our work.
WoC is an adaptive computation approach and not a speculative execution approach like our work, and so it uses a heuristic to determine when to stop, losing the guarantee of identical outputs to those of the large models.
\footnotetext{Note that the outputs from the LaMDA model always go through a $Top_{40}$ filter. This has no effect on argmax, but does have some effect on standard sampling.}
\section{Discussion}
We presented \emph{speculative sampling} which enables efficient \emph{stochastic speculative execution} - i.e. speculative execution in the stochastic setting. We analyzed its impact on decoding from autoregressive models like Transformers via \emph{speculative decoding} and have shown that given enough compute resources, we get meaningful 2X-3X speedups in practice vs T5X, a popular optimized implementation. We achieve this by leveraging small off-the-shelf approximations models.
One limitation of speculative execution in general, and of speculative decoding in particular, is that latency is improved through increased concurrency at the cost of an increased number of arithmetic operations. Thus, our method is not helpful for configurations where additional computation resources are not available. However, in cases where additional computation resources are available (e.g. when memory bandwidth is the bottleneck) our method provides the speedup with significant benefits: the model architecture doesn't change, retraining isn't required, and most importantly, \emph{the output distribution is guaranteed to stay the same}. Our method is easy to implement, and can be used to speedup inference using out-of-the-box models without developing and evaluating custom schemes.
There are several directions for follow up research, importantly, further investigating the compatibility of speculative decoding with beam search (see \cref{sec:beam}). Also, while a great property of our method is that off-the-shelf models can be used, greater improvements might be obtained via training custom approximation models, e.g. of custom sizes, or with custom training procedures (e.g. distillation). It could also be interesting to explore using custom non-autoregressive models with speculative decoding. Relatedly, it could be interesting to explore a hierarchical version of the algorithm, where the approximation model is itself accelerated by an even faster model, which could allow for larger approximation models. In this work we fixed the approximation model and the number of guesses $\gamma$ throughout inference, but varying them during inference could yield additional improvement (see \cref{sec:optimal_gamma}). We only experimented with standardizing the distributions generated by the approximation model and the large model in the same way, but further improvements might be obtained by applying different transformations. We tested speculative decoding only in the text modality, but it might work well in other domains (e.g. images) which would be interesting to experiment with.
Finally, we note that \emph{stochastic speculative execution} and \emph{speculative sampling} can be helpful outside the scope of \emph{speculative decoding} from autoregressive models. For example, given two slow functions, $f(x)$ and $g(y)$ such that $f(x)$ generates a distribution from which $g$'s input is sampled, we could use our method to run $f$ and $g$ in parallel. This setup might arise e.g. in physics simulations, or in reinforcement learning where $f$ is a large model that produces a distribution on actions, and $g$ is the world simulation, which would be interesting to explore.
\section*{Acknowledgments}
We would like to extend a special thank you to YaGuang Li for help with everything LaMDA related and for calculating the LaMDA figures in the paper, and to Blake Hechtman for great insights and help with XLA.
We would also like to thank Asaf Aharoni, Sasha Goldshtein, Nadav Sherman, Eyal Segalis, Eyal Molad, Dani Valevski, Daniel Wasserman, Valerie Nygaard, the LaMDA and Theta Labs teams at Google, and our families.
| {'timestamp': '2022-12-01T02:20:02', 'yymm': '2211', 'arxiv_id': '2211.17192', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17192'} | arxiv |
\section{Introduction}
\vspace{-2mm}
Interpretability is a pressing issue for machine learning (ML)~\citep{doshi2017towards,fan2021interpretabilityreview,rudin2022interpretable}.
As models continue to grow in complexity, machine learning is increasingly integrated into fields where flawed decisions can have serious ramifications~\citep{caruana2015intelligible,rudin2018age,rudin2019stop}.
Interpretability is not a binary property that machine learning methods have or do not: rather, it is the degree to which a learning system can be probed and comprehended~\citep{doshi2017towards}. Importantly, interpretability can be attained along many distinct routes~\citep{lipton2018mythos}.
Various constraints on the learning system can be incorporated to bring about a degree of comprehensibility~\citep{molnar2020interpretable,molnar2022interpretableML}.
In contrast to explainable AI that happens post-hoc after a black-box model is trained, interpretable methods engineer the constraints into the model from the outset~\citep{rudin2022interpretable}.
A common route to interpretability enforces that the effects of features combine in a simple (e.g., linear) manner, greatly restricting the space of possible models in exchange for comprehensibility.
In this work, we introduce a novel route to interpretability that places no restrictions on model complexity, and instead tracks \textit{how much} and \textit{what} information is most important for prediction.
By identifying optimal information from features of the input, the method grants a measure of salience to each feature, produces a spectrum of models utilizing different amounts of optimal information about the input, and provides a learned compression scheme for each feature that highlights from where the information is coming in fine-grained detail.
The central object of interpretation is then no longer a single optimized model, but rather a family of models that reveals how predictive information is distributed across features at all levels of fidelity.
The information constraint that we incorporate is a variant of the Information Bottleneck (IB)~\citep{tishbyIB2000,asoodeh2020bottleneck}.
The IB can be used to extract relevant information in a relationship, but it lacks interpretability because the extracted information is free to be any black-box function of the input.
Here instead, we use the Distributed IB\citep{aguerri2018DIB,dib}, which siloes the information from each feature and applies a sum-rate constraint at an appropriate level in the model's processing: after every feature is processed and before any interaction effects between the features can be included.
Before and after the bottlenecks, arbitrarily complex processing can occur, thereby allowing the Distributed IB to be used in scenarios with many features and complex feature interactions.
By restricting the flow of information into a predictive model, we acquire a novel signal about the relationships in the data and the inner workings of the prediction.
In this paper, we develop a framework for extracting insight from the interpretable signals acquired by the Distributed IB. In doing so, we demonstrate the following strengths of the approach:
\begin{enumerate}
\item \textbf{Capacity to find the features \textit{and} feature values that are most important for prediction.} In using the Distributed IB, interpretability comes from the fine-grained decomposition of the most relevant information in the data, which is found over the full spectrum of approximations. The approach hence provides an analysis of the relationship between input and (predicted) output that is comprehensible and understandable.
\item \textbf{Full complexity of feature processing and interactions.} Compatible with arbitrary neural network architectures before and after the bottlenecks, the method gains interpretability without sacrificing predictive accuracy.
\item \textbf{Intuitive to implement, minimal additional overhead.} The method is a probabilistic encoder for each feature, employing the same loss penalty as $\beta$-VAE~\citep{betavae}. A single model is trained once while sweeping the magnitude of the information bottleneck.
\end{enumerate}
In addition to demonstrating these strengths of the Distributed IB, we compare the approach to other approaches in interpretable ML and feature selection on a variety of tabular datasets. Collectively, our analyses and computational experiments serve to illustrate the capacity of the Distributed IB to provide interpretability while simultaneously supporting full complexity, thereby underscoring the approach's utility in future work.
\begin{figure}
\begin{center}
\includegraphics[width=\linewidth]{fig_schematic.pdf}
\end{center}
\caption{\textbf{Restricting information flow from features grants interpretability with full complexity.}
\textbf{(a)} Feature selection methods optimize a binary mask on features to uncover the most informative ones.
\textbf{(b)} Interpretable ML methods sacrifice model complexity in exchange for comprehensible feature interactions (shown is a GAM with a neural network to transform each feature).
\textbf{(c)} Our method places an information bottleneck penalty on each feature, with no constraints on complexity before or after the bottlenecks.
The features $X_i$ are compressed to optimal representations $U_i$, which communicate the most relevant information to the rest of the model.
Compressing the features in this way allows feature inclusion/exclusion to exist on a continuum.
The learned compression scheme for each feature grants insight into feature effects on the model output.
}
\label{fig:schematic}
\end{figure}
\vspace{-3mm}
\section{Related work}
\vspace{-2mm}
We propose a method that analyzes the information content of features of an input with respect to an output. Its generality bears relevance to several broad areas of research. Here in this section we will briefly canvas prior related work to better contextualize our contributions.
\textbf{Feature selection and variable importance.}
Feature selection methods isolate the most important features in a relationship (Fig.~\ref{fig:schematic}a), both for interpretability and to reduce computational burden~\citep{chandrashekar2014featureselection,cai2018featureselectionreview}.
When higher order feature interactions are present, the combinatorially large search space presents an NP-hard optimization problem~\citep{chandrashekar2014featureselection}.
Modern feature selection methods navigate the search space with feature inclusion weights, or masks, that can be trained as part of the full stack with the machine learning model~\citep{fong2017interpretable,balin2019concrete,lassonet2021,kolek2022rate}.
Many classic methods of statistical analysis work to identify the most important features in data.
Canonical correlation analysis (CCA)~\citep{hotelling1936cca} relates sets of random variables by finding transformations that maximize linear correlation.
Modern extensions broaden the class of transformations to include kernel methods~\citep{hardoon2004kcca} and deep learning~\citep{andrew2013deepCCA,wang2016deepCCA}.
Another line of research generalizes the linear correlation to use mutual information instead~\citep{painsky2018ITCCA}.
Analysis of variance (ANOVA) finds a decomposition of variance by features~\citep{fisher1936anova,stone1994fanova}; extensions incorporate ML-based transforms~\citep{martens2020fANOVA}.
Variable importance (VI) methods quantify the effect of different features on an outcome~\citep{breiman2001randomforests,fisher2019allmodelswrong}.
\textbf{Interpretable machine learning.}
Interpretability is often broadly categorized as \textit{intrinsic}--- the route to comprehensibility was engineered into the learning model from the outset, as in this work---or \textit{post hoc}---constructed around an already-trained model~\citep{rudin2022interpretable}.
Another common distinction is \textit{local}---the comprehensibility built up piecemeal by inspecting individual examples (e.g., LIME~\citep{ribeiro2016LIME})---or \textit{global}---the comprehensibility applies to the whole space of inputs at once, as in this work.
Intrinsic interpretabilty is generally achieved through constraints incorporated to reduce the complexity of the system.
Generalized Additive Models (GAMs) require feature effects to combine linearly (Fig.~\ref{fig:schematic}b), though each effect can be an arbitrary function of a feature~\citep{chang2021interpretablegams,molnar2022interpretableML}.
By using neural networks to learn the transformations from raw feature values to effects, Neural Additive Models (NAMs) maintain the interpretability of GAMs with more expressive effects~\citep{agarwal2021NAM}.
Pairwise interactions between effects can be included for more complex models~\citep{yang2021gami,chang2021nodegam}, though complications arise involving degeneracy and the number of effect terms to inspect grows rapidly.
Regularization can be used to encourage sparsity in the ML model so that fewer components---weights in the network~\citep{ng2004regularization} or even features~\citep{lassonet2021}---conspire to produce the final prediction.
\textbf{Information Bottleneck.}
The proposed method can also be seen as a regularization to encourage sparsity of information.
It is based upon the Information Bottleneck, a broad framework that extracts the most relevant information in a relationship~\citep{tishbyIB2000} and has proven useful in representation learning~\citep{alemiVIB2016,wang2019multiviewIB,asoodeh2020bottleneck}.
However, the standard IB has one bottleneck for the entire input, preventing an understanding of where the relevant information originated and hindering interpretability.
\citet{bang2021explaining} and \citet{schulz2020restricting} employ the IB to explain a trained model's predictions as a form of post-hoc interpretability, whereas the current method is built into the training of a model and thus serves as intrinsic interpretability.
Distributing bottlenecks to multiple sources of data has been of interest in information theory as a solution to multiterminal source coding, or the ``CEO problem''~\citep{berger1996ceo,aguerri2018DIB,aguerriDVIB2021,steiner2021distributedcompression}.
Only recently has the Distributed IB been utilized for interpretability~\citep{dib}, whereby features of data serve as the distributed sources.
With this formulation, the extracted information from each feature can be used to understand the role of the features in the relationship of interest.
\vspace{-3mm}
\section{Methods}
\vspace{-2mm}
At a high level, we introduce a penalty on the amount of information used by a black-box model about each feature of the input.
Independently of all others, features are compressed and communicated through a noisy channel; the messages are then combined for input into a prediction network.
The optimized information allocation and the learned compression schemes---for every feature and every magnitude of the penalty---serve as our windows into feature importance and into feature effects.
\vspace{-2mm}
\subsection{Distributed Variational Information Bottleneck}
\vspace{-2mm}
Let $X,Y\sim p(x,y)$ be random variables representing the input and output of a relationship to be modeled from data.
The mutual information is a general measure of the statistical dependence of two random variables, and is the reduction of entropy of one variable after learning the value of the other:
\begin{equation} \label{eqn:MI}
I(X;Y) = H(Y) - H(Y|X),
\end{equation}
\noindent with $H(Z)=\mathbb{E}_{z\sim p(z)}[-\textnormal{log} \ p(z)]$ Shannon's entropy~\citep{shannon1948mathematical}.
The Information Bottleneck (IB) \citep{tishbyIB2000} is a learning objective to extract the most relevant information from $X$ about $Y$.
It optimizes a representation $U$ that conveys information about $X$, realized as a stochastic channel of communication $U \sim p(u|x)$.
The representation is found by minimizing a loss comprising competing mutual information terms balanced by a scalar parameter $\beta$,
\begin{equation} \label{eqn:IB}
\mathcal{L}_\textnormal{IB} = \beta I(U;X) - I(U;Y).
\end{equation}
\noindent The first term is the bottleneck---acting as a penalty on information passing into $U$---with $\beta$ determining the strength of the bottleneck.
Optimization with different values of $\beta$ produces different models of the relationship between $X$ and $Y$, and a sweep over $\beta$ produces a continuum of models that utilize different amounts of information about the input $X$.
In the limit where $\beta\rightarrow 0$, the bottleneck is fully open and all information from $X$ may be freely conveyed into $U$ in order for it to be maximally informative about $Y$.
As $\beta$ increases, only the most relevant information in $X$ about $Y$ becomes worth conveying into $U$, until eventually it is optimal for $U$ to be uninformative random noise.
Because mutual information is generally difficult to estimate from data \citep{saxe2019,mcallester2020infolimitations}, variants of IB replace the mutual information terms of Eqn.~\ref{eqn:IB} with bounds amenable to deep learning \citep{alemiVIB2016,achillesoatto2018,kolchinskyNonlinearIB2019}.
We follow the Variational Information Bottleneck (VIB) \citep{alemiVIB2016}, which learns representations $U$ in a framework resembling that of $\beta$-VAEs~\citep{betavae}.
\begin{figure}
\begin{center}
\includegraphics[width=0.8\linewidth]{fig_infoplane_pedagogy2.pdf}
\end{center}
\caption{\textbf{The tradeoff between information into a model and predictive power out.}
\textbf{(a)} The distributed information plane displays the sum total information from all features, encoded independently of one another, against the information about the output $Y$.
While there are many possible allocations of feature information (gray region), the Distributed IB objective allows us to find a continuum of allocations (black curve) that contain the most information about the output for the least information about the input.
Increasing the bottleneck strength $\beta$ traverses the optimal trajectory from the green point---all bottlenecks fully open, and all information is available for prediction---to the red point---where predictions are independent of the input.
\textbf{(b)} A pragmatic alternative to \textbf{(a)} displays the sum of the KL-divergences $\sum D_\textnormal{KL}$ (roughly corresponding to the information utilized by the model about the features) against the particular error metric being optimized.
Optimizing the Distributed IB objective finds a continuum of models (black curve) that utilize the least information about the features for the least error.
In the large $\sum D_\textnormal{KL}$ regime, the effect of the bottlenecks are negligible and the models are essentially unconstrained machine learning.
A Distributed IB optimization gradually increases $\beta$, the strength of the bottlenecks, shedding information.
}
\label{fig:infoplane_pedagogy}
\end{figure}
A sample $x$ is encoded as a distribution in representation space $p(u|x)=f(x,\phi,\epsilon)$ with a neural network parameterized by weights $\phi$ and a source of noise $\epsilon\sim\mathcal{N}(0,1)$ to facilitate the ``reparameterization trick''~\citep{vae}.
The bottleneck restricting the information from $X$ takes the form of the Kullback-Leibler (KL) divergence---$D_\textnormal{KL}(p(z)||q(z))=\mathbb{E}_{z\sim p(z)}[-\textnormal{log} \ (q(z)/p(z))]$---between the encoded distribution $p(u|x)$ and a prior distribution $r(u)=\mathcal{N}(0,1)$.
As the KL divergence tends to zero, all representations are indistinguishable from the prior and from each other, and therefore uninformative.
A representation $u$ is sampled from $p(u|x)$ and then decoded to a distribution over the output $Y$ with a second neural network parameterized by weights $\psi$, $q(y|u)=g(u,\psi)$.
In place of Eqn.~\ref{eqn:IB}, the following may be minimized with standard gradient descent methods:
\begin{equation}\label{eqn:vib}
\mathcal{L}_\textnormal{VIB} = \beta D_\textnormal{KL}(p(u|x)||r(u)) - \mathbb{E}[\textnormal{log} \ q(y|u)].
\end{equation}
\noindent
The Distributed IB~\citep{aguerri2018DIB} concerns the optimal scheme of compressing multiple sources of information as they relate to a single relevance variable $Y$.
Let $\{X_i\}$ be the features of $X$; the Distributed IB encodes each feature $X_i$ independently of the rest, and then integrates the information from all features to predict $Y$.
A bottleneck is installed after each feature in the form of a compressed representation $U_i$ (Fig.~\ref{fig:schematic}c), and the set of representations $U_X=\{U_i\}$ is used as input to a model to predict $Y$.
The same mutual information bounds of the Variational IB \citep{alemiVIB2016} can be applied in the Distributed IB setting \citep{aguerriDVIB2021},
\begin{equation} \label{eqn:DIB}
\mathcal{L}_\textnormal{DIB} = \beta \sum_i D_\textnormal{KL}(p(u_i|x_i)||r(u_i)) - \mathbb{E}[\textnormal{log} \ q(y|u_X)].
\end{equation}
\noindent
\textbf{Arbitrary error metrics with feature information regularization.}
Instead of quantifying predictive power with cross entropy, another error metric can be used in combination with the constraint on the information about the features.
For instance, mean squared error (MSE) may be used instead,
\begin{equation}
\mathcal{L} = ||y-\hat{y}||^2 + \beta \sum D_\textnormal{KL},
\label{eqn:mse_dib}
\end{equation}
\noindent with $y$ and $\hat{y}$ the prediction and ground truth values, respectively.
The connection to the IB is diminished, as $\beta$ is no longer a unitless ratio of information about $Y$ to the sum total information about the features of $X$, and the optimal range must be found anew for each problem.
Optimization will nevertheless yield a spectrum of approximations prioritizing the most relevant information about the input features; the heart of the proposed framework is regularization on the information about input features, inspired by the Distributed Information Bottleneck rather than a strict application of it.
\textbf{Boosting expressivity for low-dimensional features.}
Similarly with \citet{agarwal2021NAM}, we found the feature encoders struggled with expressivity due to the low dimensionality of the features.
We \textit{positionally encode} feature values~\citep{tancik2020fourier} before they pass to the neural network, taking each value $z$ to $[\textnormal{sin}(\omega_1 z), \textnormal{sin}(\omega_2 z), ...]$ where $\omega_k$ are the frequencies for the encoding.
\vspace{-2mm}
\subsection{Visualizing the optimally predictive information}
\vspace{-2mm}
\textbf{Distributed information plane.} \citet{tishbyDL2015} popularized the visualization of learning dynamics in the ``information plane'', a means to display how successfully information conveyed about the input of a relationship is converted to information about the output.
We employ the distributed information plane (Fig.~\ref{fig:infoplane_pedagogy}a) to compare the total information utilized about the features $\sum I(U_i;X_i)$ to information about the output $I(\{U_i\};Y)$.
Considering the space of possible allocations of information to the input features, the Distributed IB finds the set of allocations that minimize $\sum I(U_i;X_i)$ while maximizing $I(\{U_i\};Y)$.
All possible allocations converge on two universal endpoints: the origin (no information in, no information out; red point in Fig.~\ref{fig:infoplane_pedagogy}a) and at $(\sum H(X_i), I(X,Y))$ (all information in, mutual information between $X$ and $Y$ out; green point in Fig.~\ref{fig:infoplane_pedagogy}a).
\begin{figure}
\begin{center}
\includegraphics[width=\linewidth]{fig_clustering_pedagogy.pdf}
\end{center}
\caption{\textbf{Confusion matrices to visualize compression schemes}.
\textbf{(a)} An input value is encoded to a distribution over $u$.
The Bhattacharyya coefficient quantifies how distinguishable the distributions are for different encodings, which we express as a matrix.
The diagonal (white) values are indistinguishable and everything else (blue) is distinguishable, yielding 2 bits of information.
\textbf{(b)} 1 bit of information allows a hard clustering of the values, such that the $ab$ cluster is distinguishable from the $cd$ cluster, but no more than that.
\textbf{(c)} 1 bit also allows a soft clustering, where some pairs of values are partially distinguishable.
\textbf{(d)} When trained with a two-dimensional embedding space per feature on the Bikeshare dataset, we recover a soft clustering of the day of the week. Weekend is distinguishable from weekday, with intermediate values of distinguishability otherwise.
}
\label{fig:confusion_matrix_pedagogy}
\end{figure}
A pragmatic alternative to the distributed information plane replaces $\sum I(U_i;X_i)$ with its upper bound used during optimization, the sum of KL divergences across the features.
Additionally, we replace the vertical axis $I(\{U_i\};Y)$ with the error used for training.
Switching the vertical axis from mutual information to an error has the effect of inverting the trajectory found by the Distributed IB: the uninformed point is now the \textit{maximum} error with zero $\sum D_\textnormal{KL}$ (red point in Fig.~\ref{fig:infoplane_pedagogy}b).
The entire curve of optimal information allocations in Fig.~\ref{fig:infoplane_pedagogy}b may be found in a single training run, by increasing $\beta$ logarithmically over the course of training as Eqn.~\ref{eqn:DIB} is optimized.
Training begins with negligible information restrictions ($\beta\sim 0$) so that the relationship may be found without obstruction~\citep{wu2020learnability,lassonet2021}, and ends once all information is removed.
Each value of $\beta$ corresponds to a different approximation to the relationship between $X$ and $Y$, and we can use the KL divergence for each feature as a measure of its overall importance in the approximation.
\textbf{Confusion matrices to visualize feature compression schemes.}
Transmitting information about a feature is equivalent to conveying distinctions between the feature's possible values.
In the course of optimizing the Distributed IB, the spectrum of models learned range from all input values perfectly distinguishable ($\beta \rightarrow$ 0, unconstrained machine learning) to all inputs perfectly indistinguishable (the model utilizes zero information about the input).
Along the way, the distinctions most important for predicting $Y$ are selected, and can be inspected via the encoding of each feature value.
Each feature value $x_i$ is encoded to a probability distribution $p(u_i|x_i)$ in channel space, allowing the compression scheme to be visualized with a confusion matrix showing the similarity of feature values (Fig.~\ref{fig:confusion_matrix_pedagogy}a).
The Bhattacharyya coefficient~\citep{kailath1967Bdistance} is a symmetric measure of the similarity between probability distributions $p(z)$ and $q(z)$, and is straightforward to compute for normal distributions.
The coefficient is 0 when the distributions are perfectly disjoint (i.e., zero probability is assigned by $p(z)$ everywhere that $q(z)$ has nonzero probability, and vice versa), and 1 when the distributions are identical.
In other words, if the Bhattacharyya coefficient between encoded distributions $p(u|x=a)$ and $p(u|x=b)$ is 1, the feature values $x=a$ and $x=b$ are indistinguishable to the prediction network and the output is independent of whether the actual feature value was $a$ or $b$.
On the other extreme where the Bhattacharyya coefficient is 0, the feature values are perfectly distinguishable and the prediction network can yield distinct outputs for $x=a$ and $x=b$.
\begin{table}[t]
\caption{Performance on various tabular datasets. NAM and NODE-GAM allow no feature interactions; NODE-GA$^2$M contain pairwise feature interactions; the Neural Oblivious Decision Ensemble (NODE) LassoNet, and Distributed IB methods are full complexity models (allowing arbitrary feature interactions). \ddag Results from \citet{chang2021nodegam}.
}
\centering
\resizebox{\textwidth}{!}{
\begin{tabular}{@{}lccccc
}
& \shortstack{Bikeshare \\ (RMSE $\downarrow$)} & \shortstack{Wine \\(RMSE $\downarrow$)} & \shortstack{MIMIC-II \\(AUC \% $\uparrow$)} & \shortstack{MIMIC-III\\ (AUC \% $\uparrow$)} & \shortstack{Microsoft \\ (MSE $\downarrow$)} \\
\midrule
NAM~\citep{agarwal2021NAM} & 99.9\scriptsize{$\pm 1.3$} & 0.71\scriptsize{$\pm 0.02$} & 83.0\scriptsize{$\pm 0.8$} & 81.7\scriptsize{$\pm 0.2$} & 0.5908\scriptsize{$\pm 0.0004$} \\
NODE-GAM~\citep{chang2021nodegam} & 100.7\scriptsize{$\pm 1.6$} & 0.71\scriptsize{$\pm 0.03$} & 83.2\scriptsize{$\pm 1.1$} & 81.4\scriptsize{$\pm 0.5$} & 0.5821\scriptsize{$\pm 0.0004$} \\
NODE-GA$^2$M~\citep{chang2021nodegam} & 49.8\scriptsize{$\pm 0.8$} & 0.67\scriptsize{$\pm 0.02$} & 84.6\scriptsize{$\pm 1.1$} & 82.2\scriptsize{$\pm 0.7$} & 0.5618\scriptsize{$\pm 0.0003$} \\
LassoNet~\citep{lassonet2021} & 46.0\scriptsize{$\pm 2.0$} & 0.68\scriptsize{$\pm 0.02$} & 83.4\scriptsize{$\pm 0.8$} & 79.4\scriptsize{$\pm 0.8$} & 0.5667\scriptsize{$\pm 0.0012$} \\
NODE\ddag~\citep{popov2019neural} & \textbf{36.2\scriptsize{$\pm 1.9$}} & 0.64\scriptsize{$\pm 0.01$} & 84.3\scriptsize{$\pm 1.1$} & \textbf{82.8\scriptsize{$\pm 0.7$}} & \textbf{0.5570\scriptsize{$\pm 0.0002$}} \\
Distributed IB (Ours) & 38.0\scriptsize{$\pm 1.1$} & \textbf{0.62\scriptsize{$\pm 0.01$}} & \textbf{84.9\scriptsize{$\pm 1.2$}} & 80.2\scriptsize{$\pm 0.4$} & 0.5790\scriptsize{$\pm 0.0003$}\\
\bottomrule
\end{tabular}
}
\label{tab:results}
\end{table}
We display in Fig.~\ref{fig:confusion_matrix_pedagogy}b,c possible compression schemes containing one bit of information about a hypothetical $x$ with four equally probable values.
The compression scheme can be a hard clustering of the values into two sets where $x=a$ and $x=b$ are indistinguishable, and similarly for $x=c$ and $x=d$ (Fig.~\ref{fig:confusion_matrix_pedagogy}b).
Another possibility with one bit of information is the soft clustering shown in Fig.~\ref{fig:confusion_matrix_pedagogy}c, where each feature value is partially `confused' with other feature values.
In the case of soft clustering, a learned compression cannot be represented by a decision tree; rather, the confusion matrices are the fundamental distillations of the information preserved about each feature.
An example in Fig.~\ref{fig:confusion_matrix_pedagogy}d shows the learned compression scheme of the \texttt{weekday} feature in the Bikeshare dataset (dataset details below).
The soft clustering distinguishes between the days of the week to different degrees, with the primary distinction between weekend and weekdays.
\vspace{-3mm}
\section{Experiments}
\vspace{-2mm}
We analyzed a variety of tabular datasets with the Distributed IB and compared the interpretability signal to what is obtainable through other methods.
Our emphasis was on the unique capabilities of the Distributed IB to produce insight about the relationship in the data modelled by the neural network.
Performance results are included in Tab.~\ref{tab:results} for completeness.
Note that the Distributed IB places no constraints on the machine learning models used and in the $\beta \rightarrow 0$ regime could hypothetically be as good as any finely tuned black-box model.
The benefit of freedom from complexity constraints was particularly clear in the smaller regression datasets, whereas performance was only middling on several other datasets (refer to App.~\ref{app:extendedviz} for extended results and App.~\ref{app:implementation} for implementation details).
\begin{figure}[t!]
\begin{center}
\includegraphics[width=\linewidth]{fig_infoplane.pdf}
\end{center}
\caption{\textbf{Distributed information plane trajectories with information allocation by feature.}
\textbf{(a)} For the Bikeshare dataset, the optimal RMSE error versus $\sum D_\textnormal{KL}$ (black) decays as more information is used by the model about the features.
The shifting allocation of information to the features tells of their relevance to the prediction at each level of approximation.
Only a few bits about a handful of features is enough for most of the performance.
We label and color the first features to contribute non-negligibly to the approximations.
\textbf{(b)} The LassoNet trajectory for the Bikeshare dataset yields only a discrete series of error values and an ordering of the features.
Note the LassoNet trajectory extends to the point of all features included, whereas the Distributed IB is truncated at 20 bits of $\sum D_\textnormal{KL}$.
\textbf{(c, d)} Same as \textbf{(a, b)} for the MiceProtein dataset, with expression levels of 77 proteins measured to classify mice in one of eight categories related to Down syndrome.
\textbf{(e, f)} Same as \textbf{(a, b)} for the MIMIC-II dataset, a binary classification task related to ICU mortality, with 17 input features.
}
\label{fig:infoplane_experimental}
\end{figure}
\vspace{-2mm}
\subsection{The features with the most predictive information}
\vspace{-2mm}
We used the Distributed IB to identify informative features for three datasets in Fig.~\ref{fig:infoplane_experimental}.
Bikeshare~\citep{dua_uci_repo} is a regression dataset to predict the number of bikes rented given 12 descriptors of the date, time, and weather;
MiceProtein~\citep{higuera2015mouseprotein} is a classification dataset relating the expression of 77 genes to normal and trisomic mice exposed to various experimental conditions; MIMIC-II~\citep{johnson2016mimic} is a binary classification dataset to predict hospital ICU mortality given 17 patient measurements.
We compared to LassoNet~\citep{lassonet2021}, a feature selection method that attaches an L1 regularization penalty to each feature and introduces a proximal algorithm into the training loop to enforce a constraint on weights.
By gradually increasing the regularization, LassoNet finds a series of models that utilize fewer features while maximizing predictive accuracy, providing a signal about what features are necessary for different levels of accuracy.
\begin{figure}[h]
\begin{center}
\includegraphics[width=\linewidth]{fig_feature_effects_revised.pdf}
\end{center}
\caption{\textbf{Important information within each feature via inspection of the learned compression schemes.}
\textbf{(a-d)} For the Bikeshare dataset at different levels of approximation, confusion matrices display the learned compression schemes for four of the top features found in Figure~\ref{fig:infoplane_experimental}.
Following the scheme in Fig.~\ref{fig:confusion_matrix_pedagogy}, the pairwise distinguishability of feature values visualizes the information preserved about each feature.
For the categorical features (\texttt{hour}, \texttt{workingday}, and \texttt{season}), each row and column of the confusion matrices corresponds to a unique value, and the probability distributions at the top of the figure are aligned with the columns of the matrices.
For the continuous variable \texttt{atemp} (apparent temperature), 1000 values were sampled randomly from the dataset and sorted for use as the inspected points; the rank order plot at the top shows their order in the matrices.
As the utilized information $\sum D_\textnormal{KL}$ increases, so too does the performance; with only four bits the Distributed IB can perform about as well as NAM, highlighting the value of using a full-complexity model.
\textbf{(e)} The effects of these features on the output can be directly visualized with NAM; the horizontal coordinates match those of the matrices in \textbf{(a-d)} and the black traces display effects for an ensemble of 25 NAMs.
}
\label{fig:feature_effects}
\end{figure}
Like LassoNet, the Distributed IB probes the tradeoff between information about the features and predictive performance, though with important differences.
LassoNet can only vary the information used for prediction through a discrete-valued proxy: the number of features.
Binary inclusion/exclusion of features is a common limitation for feature selection methods~\citep{bang2021explaining,kolek2022rate}.
By contrast, the Distributed IB compresses each feature along a continuum, selecting the most informative information from across all input features.
At every point along the continuum is an allocation of information to each of the features.
For example, in Fig.~\ref{fig:infoplane_experimental}a we found that only a few bits of information ($\sum D_\textnormal{KL}$), mostly coming from the \texttt{hour} feature, was necessary to achieve most of the performance of the full-information model, and to outperform the linear models (Tab.~\ref{tab:results}).
The capacity to extract partial information from features shines in comparison to the LassoNet performance (Fig.~\ref{fig:infoplane_experimental}b), which improves only after multiple whole features have been incorporated.
In contrast to Bikeshare, where decent approximations required only a handful of features, the MiceProtein (Fig.~\ref{fig:infoplane_experimental}c,d) and MIMIC-II (Fig.~\ref{fig:infoplane_experimental}e,f) datasets were found to require information from many features simultaneously.
The information allocation is dynamic, with some features saturating quickly, and others growing in information usage at different rates.
The signal obtained by the Distributed IB can help decompose datasets with a large number of features and complex interaction effects, all within a single training run.
\vspace{-2mm}
\subsection{Fine-grained inspection of feature effects}
\vspace{-2mm}
In addition to a measure of feature importance in the form of average information allocation, the Distributed IB offers a second source of interpretability: the relative importance of particular feature values, revealed through inspection of the learned compression schemes of each feature.
One of the primary strengths of a GAM is that the effects of the feature values are straightforwardly obtained, though at the expense of interactions between the features.
By contrast, the Distributed IB permits arbitrarily complex feature interactions, and still maintains a window into the role specific feature values play toward the ultimate prediction.
In Fig.~\ref{fig:feature_effects} we compared the compression schemes found by the Distributed IB to the feature effects obtained with NAM~\citep{agarwal2021NAM}.
The Distributed IB allows one to build up to the maximally predictive model by approximations that gradually incorporate information from the input features.
As an example, Fig.~\ref{fig:feature_effects} displays approximations to the relationship between weather and bike rentals in the Bikeshare dataset.
To a first approximation (Fig.~\ref{fig:feature_effects}a), with only two bits of information about all features, the scant distinguishing power was allocated to discerning certain times of day---commuting periods, the middle of the night, and everything else---in the \texttt{hour} feature.
Some information discerned hot from cold from the apparent temperature (\texttt{atemp}), and no information about the season or whether it was a working day was used for prediction.
We are unable to say how this information was used for prediction---the price of allowing the model to be more complex---but we can infer much from where the discerning power was allocated.
At four bits, and performing about as well as the linear models in Tab.~\ref{tab:results}, the Boolean \texttt{workingday} was incorporated for prediction, and the evening commuting time was distinguished from the morning commuting time.
With eight and sixteen bits of information about the inputs, nearly all of the information was used from the \texttt{hour} feature, the apparent temperature became better resolved, and in \texttt{season}, winter was distinguished from the warmer seasons.
The feature effects retrieved with NAM (Fig.~\ref{fig:feature_effects}e) corroborated some of the distinguishability found by the Distributed IB, particularly in the \texttt{hour} feature (e.g., the commuting times, the middle of the night, and everything else form three characteristic divisions of the day in terms of effect).
However, we found the interpretability of the NAM-effects to vary significantly across datasets (see App.~\ref{app:extendedviz} for more examples).
For example, the apparent temperature (\texttt{atemp}) and temperature (\texttt{temp}) features were found to have contradictory effects (Fig.~\ref{fig:feature_effects_BIKESHARE}) that were difficult to comprehend, presumably arising from feature interactions that NAM could not model.
Thus while the Distributed IB sacrifices a direct window to feature effects, tracking the information on the input side of a black-box model may serve as one of the only sources of interpretability in cases with complex feature interactions.
\vspace{-3mm}
\section{Discussion}
\vspace{-2mm}
Interpretability can come in many forms~\citep{lipton2018mythos}; the Distributed IB provides a novel sources of interpretability by illuminating where information resides in a relationship with regards to features of the input.
Without having to sacrifice complexity, the Distributed IB is particularly useful in scenarios where obtaining a foothold is difficult due to large numbers of features and complex interaction effects.
The capacity for successive approximation, allowing detail to be incorporated gradually so that humans' limited cognitive capacity \citep{cowan2010workingmemory,rudin2022interpretable} does not prevent comprehension of the full relationship, plays a central role in the Distributed IB's interpretability.
The signal from the Distributed IB---particularly the compression schemes of feature values (e.g. Fig.~\ref{fig:feature_effects})---is vulnerable to over-interpretation.
This is partly due to a difficulty surrounding intuition about compression schemes (i.e., it is perhaps most natural to imagine 1 bit of information as a single yes/no question, or a hard clustering (Fig.~\ref{fig:confusion_matrix_pedagogy}b), rather than as a confusion matrix (Fig.~\ref{fig:confusion_matrix_pedagogy}c)), and partly due to the inability to make claims like ``changing input $A$ to input $B$ changes output $C$ to output $D$''.
Rather than supplanting other interpretability methods, the Distributed IB should be seen as a new tool for interpretable machine learning, supplementing other methods.
A thorough analysis could incorporate methods where the effects are comprehensible, possibly using a reduced feature set found by the Distributed IB.
| {'timestamp': '2022-12-01T02:21:43', 'yymm': '2211', 'arxiv_id': '2211.17264', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17264'} | arxiv |
\section{Introduction}\label{sec:intro}
Deep semantic matching aims to discriminate the relationship between documents based on deep neural networks \cite{huang2013learning,shen2014learning,guo2016deep}. It plays a critical role in today's intelligent web services, such as recommendation systems, search engines, and online advertising systems~\cite{xu2018deep}. Conventional semantic matching models mainly analyze the intrinsic features of the documents. Thanks to the increasing capacity of deep neural networks, a series of advanced document encoders have been proposed, especially those based on pre-trained language models \cite{reimers2019sentence,khattab2020colbert,luan2020sparse}.
\setlength{\textfloatsep}{10pt}
\begin{figure}
\centering
\includegraphics[width=0.7\columnwidth]{Figures/cdsm-example.pdf}
\caption{Example of ad-hoc neighbor selection. The key document is linked to multiple neighbors (papers in its reference) of different semantics. While estimating its relationship with Q1, N1 will be selected as both documents are about \textit{semi-supervised learning}; while estimating the relationship with Q2, N2 will be selected due to the correlation with \textit{word representation}.}
\label{fig:1}
\end{figure}
\subsection{Semantic Matching on Textual Graphs}
Many textual datasets can be naturally organized with graph structures, e.g., the webpages of online products can be linked based on users' web browsing behaviors, and the academic literature can be linked based on their citation relationships. In recent years, it becomes increasingly popular to discriminate the matching relationship between two documents on such textual graphs \cite{Zhu2021TextGNN,Li2021AdsGNN,zhang2020mira,Yang2021GraphFormer}, where both the intrinsic document features and the extrinsic neighbor features are jointly leveraged. Existing works mainly emphasize the design of graph-based matching models, whereas limited effort is dedicated to the selection of appropriate neighbors. It's usually assumed that most of the neighbors are informative, and semantic matching may always benefit from the incorporation of neighbor features. As a result, existing methods~\cite{Zhu2021TextGNN,Yang2021GraphFormer} either use all the available neighbors if the computation capacity allows, or heuristically sample a subset of neighbors for efficient computation.
We argue that \textbf{the neighbors could be highly noisy and partially useful, thus appropriate neighbor selection is vital for graph-based semantic matching}. Contradicted to the common assumption, we empirically find the following properties. \emph{1) The neighbor features can be highly \textbf{noisy}: in many situations, only a small fraction of neighbors could actually contribute to the current semantic matching}. \emph{2) The neighbor feature's usefulness is \textbf{conditional}: a neighbor may contribute to the semantic matching given one particular target document, but it may become useless when dealing with another target document (as Example~\ref{eq:1}).} As such, a lack of effective neighbor selection will severely restrict the performance of graph-based semantic matching. The irrelevant neighbors will not only {take a huge amount of unnecessary computation cost}, but also {introduce strong background noise which deteriorates the matching accuracy}.
\subsection{Our Work}
In this paper, we propose the \textbf{C}ascaded \textbf{D}eep \textbf{S}emantic \textbf{M}atching (\textbf{CDSM}) framework to address the above challenges. It completes the semantic matching task in two consecutive steps. First, an ad-hoc neighbor selection step is performed to select the optimal subset of neighbors w.r.t. the given documents. By focusing on these selected neighbors which are truly informative, the subsequent semantic matching step can be accomplished with both high accuracy and high efficiency, as background noise and unnecessary computation costs from the irrelevant neighbors can be avoided.
$\bullet$ \textbf{Ad-hoc Neighbor Selection}. In CDSM, the neighbor selection is performed in an ad-hoc manner. It is empirically found that {merely a small number of neighbors may accurately contribute to the semantic matching task between two specific documents; and an informative neighbor in one matching task will probably become useless in another task}\footnote{check Section \ref{sec:problem_definition} for the empirical analysis}. Therefore, static neighbor selection will be inappropriate. Instead of assigning fixed neighbors to each document, CDSM makes \textbf{Ad-hoc} neighbor selection, i.e., neighbors are selected w.r.t the counterpart to be matched. Specifically, given a document and its matching counterpart, CDSM aims to identify the neighbors that are closely related to the counterpart. Only the neighbors relevant to the counterpart will be preserved for the subsequent semantic matching task, while the irrelevant ones will be filtered out.
We use a concrete example to illustrate the underlying intuition.
\begin{example}\label{eq:1}
As shown in Figure \ref{fig:1}, the key document ``BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding'' should be linked to all documents within its reference list. N1 is about ``semi-supervised learning'', and N2 is about the ``representation of words''; meanwhile, there are many more neighbors about other topics, like ``ImageNet dataset'', ``machine reading comprehension'', etc. To determine whether the query document Q1 has a citation link with the key document, the ad-hoc neighbor selector will choose N1 to contribute useful information, rather than N2. Both N1 and Q1 are about ``semi-supervised learning''. Based on such supporting evidence, the connection between the key document and Q1 can be positively determined with high confidence. However, given another query document Q2, the neighbor N2 becomes a plausible choice. Both Q2 and N2 are about ``word representation'', based on which the connection between the key document and Q2 can be positively determined with high confidence.
\end{example}
The neighbor selector is also designed to be \textbf{lightweight}. Given that each document may be linked to a vast number of neighbors, it will be infeasible to identify their utilities with heavy-loaded functions. In CDSM, the neighbor selector makes use of lightweight estimation networks, whose inference cost will be small. It is also experimentally validated that the highly simplified backbone networks are already sufficiently accurate to identify useful neighbors. As a result, the computation overhead of neighbor selection will be small enough, making CDSM comparably efficient as the existing methods based on heuristic neighbor sampling.
The subsequent semantic matching is performed based on the well-selected neighbors from the first stage. As discussed, both accuracy and efficiency of the semantic matching will benefit from such a selection, thanks to the elimination of background noise and unnecessary computation costs. It is worth noting that CDSM is a \textbf{Generic} framework, where the mainstream graph-based matching models (e.g., the recent works which combine GNNs and pre-trained language models \cite{zhang2020mira,Li2021AdsGNN,Zhu2021TextGNN}) can be seamlessly incorporated as the backbone of the matching network.
$\bullet$ \textbf{Training via weak-supervision}. One major challenge for CDSM is that there are no explicit measurements of the neighbors' usefulness, which hinders the training of the neighbor selector. In our work, we develop a weak-supervision strategy, where the neighbor selector is trained on top of weak annotations obtained from the semantic matching model. Intuitively, given a pair of documents Q and K, a useful neighbor of Q should provide additional evidence to support the correlation between Q and K. In other words, a useful neighbor will strengthen the correlation between Q and K. Based on such an intuition, we make a formalized definition, which serves as the criterion of whether a neighbor is useful in a specific semantic matching task.
\begin{definition}\label{def:1}
Given a pair of documents $Q$ and $K$, and the function $\mathcal{M}$($\cdot$) which measures the semantic correlation between $Q$ and $K$. A neighbor $Q.N_i$ is useful, if the semantic correlation between $Q$ and $K$ is improved when $Q$ is aggregated with $Q.N_i$: $\mathcal{M}(Q\oplus{Q.N_i},K) > \mathcal{M}(Q,K)$ (``$\oplus$'' is the aggregation operator).
\end{definition}
With the definition of neighbor usefulness, we develop a weak-supervision algorithm for CDSM. First, the graph-based semantic matching network $\mathcal{M}$ is trained with the neighbors sampled by heuristics. Second, the well-trained semantic matching network makes annotation for the usefulness of each neighbor $Q.N_i/K.N_i$. Finally, the neighbor selector is trained based on the annotation results, where it learns to discriminate the highly useful neighbors from the less useful ones.
Extensive experimental studies are conducted with three large-scale datasets: DBLP, Wiki and Bing Ads\footnote{The first two are widely used open benchmark datasets, and the third one is a massive industrial dataset collected by Bing Search.}. The CDSM's effectiveness is verified from two perspectives. Firstly, as a generic framework, it notably improves the accuracy of a variety of graph-based semantic matching models. Secondly, it achieves competitive running efficiency as high-quality neighbors can be effectively selected with a small computation cost.
To summarize, our major contributions are listed as follows:
\begin{itemize}
\item We identify the importance of neighbor selection in the graph-based semantic matching task.
\item We propose a novel generic framework CDSM. With the selection of high-quality neighbors, CDSM achieves both high accuracy and high efficiency for graph-based semantic matching.
\item We design the weak-supervision strategy to effectively train the neighbor selector on top of the semantic matching network's annotations.
\item We perform comprehensive experimental studies, whose results verify the effectiveness and efficiency of CDSM as a generic framework.
\end{itemize}
The rest of the paper is organized as follows. The related works are reviewed in Section~\ref{sec:related_work}. The graph-based semantic matching problem is formally defined and empirically analyzed in Section~\ref{sec:problem_definition}. The detailed methodology of CDSM is elaborated in Section~\ref{sec:framework}. The experimental studies are discussed in Section~\ref{sec:experimental_setting} and \ref{sec:results}. Finally, the whole work is concluded in Section~\ref{sec:conclusion}.
\section{Related Works}\label{sec:related_work}
Semantic matching between documents is a fundamental problem in information retrieval and recommendation systems. Conventional works mainly rely on the intrinsic document features, e.g., bag-of-words \cite{robertson2009probabilistic}, latent semantic analysis \cite{landauer1998introduction} and topic modeling \cite{blei2003latent}. In recent years, various neural text encoders have been extensively explored for this task. In \cite{shen2014learning,yang2016hierarchical}, convolution neural networks are utilized to capture the local contextual patterns of the input texts; and in \cite{palangi2016deep,Seo2017BiDAF}, recurrent neural networks are employed to encode the sequential relationship between tokens. The latest works are usually built upon the large-scale pre-trained language models, like BERT and RoBERTa \cite{Devlin2019BERT,Liu2019Roberta,reimers2019sentence}. The semantic matching accuracy can be significantly improved thanks to the high-quality deep contextualized text representations.
Actually, many textual datasets can be organized in the form of a graph. For example, in sponsored search, advertisements can be linked together based on users' co-click behaviors \cite{Zhu2021TextGNN,Li2021AdsGNN}. Similarly, online articles and webpages can be connected as a graph according to their mutual linkage relationships. In recent years, it becomes increasingly popular to conduct fine-grained semantic matching on such textual graphs~\cite{Zhu2021TextGNN,Li2021AdsGNN,Yang2021GraphFormer,zhang2020mira,Hu2020RecoGNN,Arora2020KGcompletionSurvey,Wang2021KGCompletionSurvey}, leveraging both the intrinsic document features and the extrinsic neighbor features. The typical approaches \cite{hamilton2017inductive,ying2018graph} will firstly encode each document node into latent representations; and then make use of graph neural networks to aggregate the graph neighbor information. The latest works usually combine graph neural networks with pre-trained language models \cite{Zhu2021TextGNN,Li2021AdsGNN}, where the underlying semantics of each individual document can be captured more effectively. To facilitate the in-depth interaction between the textual features and graph structures, Yang et al.~\cite{Yang2021GraphFormer} propose GraphFormers: the GNN components are nested into each layer of the transformer. In such a way, each document's representation can be contextualized by involving the graph information.
Despite the achieved progress so far, these works mainly focus on designing a better model to aggregate existing neighbors (all neighbors or those selected heuristically), whereas limited effort is made for the selection of truly informative neighbors. Empirically, we have found that 1) the neighbor features can be noisy and 2) the usefulness of a neighbor is conditional, different for different matching counterparts. In this paper, we are committed to solving the problem of effective neighbor selection to improve both the accuracy and efficiency of graph-based semantic matching.
\section{Problem Definition}\label{sec:problem_definition}
This section covers the following issues: 1) the definition of graph-based semantic matching, 2) the empirical analysis of how neighbor selection matters in graph-based semantic matching, and 3) the definition of neighbor selection, which plays a central role in our CDSM framework.
\subsection{Graph-based Semantic Matching}
Semantic matching is a critical issue in information retrieval and natural language processing. Given a query document $Q$ and a key document $K$, a semantic matching model predicts the relevance score between the two documents based on their textual features. Since many real-world data can be organized as graphs, the graph-based semantic matching goes beyond by leveraging the textual features from both the target nodes (i.e. $Q$ and $K$) and their linked neighbors on the graph. In this place, we define the graph-based semantic matching task in the form of a typical ranking problem.
\begin{definition}\label{def:2}
{(Graph-based Semantic Matching)} Given a pair of documents: query $Q$ and key $K$, together with their neighbor sets $Q.N$ and $K.N$, the graph-based semantic matching model $\mathcal{M}$ learns to predict the relevance score between the query and key as:
\begin{equation}
m(Q,K) = \mathcal{M}(Q\oplus{Q.N}, K\oplus{K.N}),
\end{equation}
(``$\oplus$'' is the aggregation operator), such that a positive key $K^+$ can be ranked higher than a negative key $K^-$: $m(Q,K^+) > m(Q,K^-)$.
\end{definition}
Although the neighbor features may provide complementary information to the semantic matching task, they should be utilized with caution due to the following defects. First, the neighbor features are prone to strong noise: many of the neighbors may contribute little useful information to the semantic matching task. Secondly, the usefulness of a neighbor is conditional: a neighbor can be helpful to the semantic matching task between a query and a specific key document, but turns useless when dealing with other keys. In the following discussion, an empirical analysis is presented to demonstrate the neighbors' impacts.
\setlength{\textfloatsep}{10pt}
\begin{figure}
\centering
\includegraphics[width=0.6\columnwidth]{Figures/counterpart.pdf}
\caption{TextGNN with counterpart attention. The center document $Q, K$ and their neighbors are encoded by the pre-trained language model (with stacked transformers) at first; the neighbors are then aggregated based on the attention of the matching counterpart.}
\label{fig:2}
\end{figure}
\begin{figure}
\centering
\includegraphics[width=0.6\linewidth]{Figures/preliminary.pdf}
\caption{Case analysis on DBLP. The horizontal axis shows the number of neighbors utilized in each semantic matching task, and the vertical axis shows the semantic matching accuracy (measured by precision@1).}
\label{fig:preliminary_analysis}
\end{figure}
\subsection{Neighbors' Impact: An Empirical Analysis with TextGNN}
We take one of the latest graph-based semantic matching methods, TextGNN \cite{Zhu2021TextGNN}, for our analysis. The TextGNN framework uses the pre-trained language model BERT as the text encoder, and graph neural networks (like GraphSage) as the graph aggregator. The input documents, i.e. the query/key and their neighbors, are encoded by the text encoder at first. Then, the text embeddings are aggregated by the graph aggregator to get the final representation for semantic matching. In our work, we make an analysis based on the following adaptations of TextGNN.
\textbf{First}, we introduce the ``counterpart attention'' as shown in Figure \ref{fig:2}. The ``counterpart'' means the document to be matched: the query's counterpart is the key, while the key's counterpart is the query. To identify the neighbors that truly contribute to the current matching task, the neighbors are scored and aggregated based on their attention with the counterpart document:
\begin{equation}
\text{AGG}(N) = \sum_i \alpha_i * \theta_{N_i}, ~
\alpha_i = \mathrm{CP-ATT}(\theta_{N_i}, \theta_{CP}).
\end{equation}
$\text{AGG}(\cdot)$ is the neighbor aggregation function and $\text{CP-ATT}(\cdot)$ means the counterpart attention. $\theta_{N_i}$ and $\theta_{CP}$ are the embeddings of the neighbor $N_i$ (could be $Q.N_i$ or $K.N_i$) and the counterpart document respectively. With this adaptation, TextGNN becomes more robust to noisy neighbors, as truly useful neighbors for the counterpart can be highlighted with higher attention weights.
\textbf{Second}, we select a subset of neighbors for graph-based semantic matching. A neighbor is selected if it is ranked within the ``Top-$k$'' positions w.r.t. the counterpart attention scores. By this means, the quality of neighbor features can be improved as the potentially irrelevant neighbors can be largely removed, therefore leading to higher semantic matching accuracy.
We perform experimental analysis with the DBLP dataset (refer to Section \ref{sec:experimental_setting} for details). A total of three alternatives are compared: (1) The original TextGNN with GraphSage aggregator (using mean-pooling for implementation), and uniformly sampled neighbors. (2) The adapted TextGNN with counterpart attention, and uniformly sampled neighbors. (3) The adapted TextGNN with counterpart attention, and the Top-$k$ neighbors. All neighbors are sampled from the same candidate set, and each document owns at most 50 neighbors. The analysis results are shown in Figure \ref{fig:preliminary_analysis}. The semantic matching accuracy (measured by Precision@1, with 1 positive key and 29 negative keys) is checked when different numbers of neighbors are incorporated. The following properties can be observed from the shown results.
$\bullet$ {There is indeed strong noise within the neighbor features.} The adapted TextGNN with Top-$k$ neighbors consistently outperforms the one with uniformly sampled neighbors, which indicates that the subset of Top-$k$ neighbors is more useful. Besides, the accuracy of TextGNN with the Top-$k$ neighbors reaches its apex when $k$ is merely around 20; it goes down when more neighbors are introduced. It is probably because the additional neighbors (thereafter the apex) are less relevant, which provides little useful information but noisy features to the semantic matching task.
$\bullet$ {The usefulness of neighbors is conditional, dependent on the given counterpart}. For both methods with the uniformly sampled neighbors, the adapted TextGNN with counterpart attention outperforms the original TextGNN consistently. Such an observation indicates that a neighbor is likely to contribute more to the semantic matching task if it is relevant to the matching counterpart.
Both findings are consistent with our statements about the neighbor features: noisy and conditionally useful. Without an effective neighbor selection mechanism, the graph-based semantic matching could be inaccurate and inefficient due to the introduction of useless neighbors. Notice that although the ``counterpart attention based Top-$k$ neighbor selection'' improves the accuracy, it has low feasibility in practice as the entire neighbors still need to be encoded by heavy-loaded text encoders. A practical selection mechanism will be introduced in our subsequent discussion.
\subsection{Neighbor Selection}
Given the discussed properties of the neighbor features, it is important to select the subset of neighbors which are truly helpful to the specific semantic matching task. In this paper, we aim to learn a neighbor selector to complete the selection defined as follows.
\begin{definition}
(Neighbor Selection) Given the semantic matching task between the query document $Q$ and key document $K$ (whether $K$ is positive or negative is unknown), the neighbor selector $\mathcal{S}(\cdot)$ learns to identify the subsets of neighbors:
\begin{equation}
Q.\tilde{N} \leftarrow \mathcal{S}(Q.N|Q,K), ~K.\tilde{N} \leftarrow \mathcal{S}(K.N|Q,K);
\end{equation}
such that the semantic matching accuracy can be optimized on top of the selection result: $Q\oplus{Q.\tilde{N}}$ and $K\oplus{K.\tilde{N}}$.
\end{definition}
According to the above definition, the selector $\mathcal{S}(\cdot)$ is expected to realize the following two functionalities. (1) \textbf{Ranking}: which identifies the relative importance of the neighbors; (2) \textbf{Truncation}: which determines how many top-ranked neighbors should be selected and utilized. Insufficient selection will be less informative, while excessive selection will introduce noise.
Besides, the selector is desirable for satisfying two properties. \textbf{Ad-hoc}: instead of assigning a fixed set of neighbors to each document, the selection needs to be dynamically dependent on the given counterpart: the query's neighbors are selected w.r.t. the key to be matched, and vice versa. \textbf{Lightweight}: the neighbor selector needs to be highly efficient, such that it could traverse all neighbors for the optimal subset with affordable computation overhead.
\begin{figure*}
\centering
\includegraphics[width=0.85\linewidth]{Figures/cdsm-frame.pdf}
\caption{The whole architecture of our CDSM framework with a two-stage workflow: (1) A lightweight ad-hoc neighbor selector is deployed to filter the optimal subset of neighbors for the matching documents; (2) A high-capacity matching model is employed to calculate the relevance score with these selected neighbors.}
\label{fig:architecture}
\end{figure*}
\section{Cascaded Deep Semantic Matching}\label{sec:framework}
In this work, we propose Cascaded Deep Semantic Matching (CDSM), a generic framework for accurate and efficient semantic matching on textual graphs. It consists of two modules: the lightweight ad-hoc neighbor selector, and the high-capacity graph-based semantic matching network. Besides, we design a hybrid optimization algorithm to train the above two modules. We also demonstrate a prototype implementation of CDSM, which realizes the properties required in Section~\ref{sec:problem_definition} and shows strong empirical performance.
\subsection{The CDSM Framework}\label{subsec:cdsm_framework}
The proposed CDSM framework is illustrated in Figure~\ref{fig:architecture}, which completes the graph-based semantic matching in two consecutive steps. First, a lightweight ad-hoc neighbor selector is developed to filter the optimal subset of useful neighbors that would help to discriminate the semantic relationship between the query and key. Second, a high-capacity graph-based matching network is employed to calculate the relevance score based on the given documents and their selected neighbors. The detailed formulations are introduced as follows.
\subsubsection{Ad-hoc Neighbor Selector} In the first stage, the CDSM takes the query document $Q$, key document $K$ and all their neighbors $Q.N=[Q.N_1,\ldots,Q.N_n]$, $K.N=[K.N_1,\ldots,K.N_n]$ as the input. Then, the ad-hoc neighbor selection is performed with two operations: 1) ranking, which estimates and compares the importance of all the neighbors, and 2) truncation, which determines how many top-ranked neighbors should be selected (i.e, the value of $k$ when making Top-$k$ selection).
$\bullet$ \textbf{Ranking function}. We discuss two optional forms of the ranking function. The first one is the \textit{one-step} ranking function $\mathcal{R}^{one}(\cdot)$, where the importance of a query's neighbor $Q.N_i$ and a key's neighbor $K.N_j$ is computed as follows:
\begin{equation}
\begin{aligned}
{r}(Q.N_i) &= \mathcal{R}^{one}(Q.N_i|Q,K); \\
{r}(K.N_j) &= \mathcal{R}^{one}(K.N_j|Q,K).
\end{aligned}
\end{equation}
Because the computation of the neighbor's usefulness ${r}(Q.N_i)$ and ${r}(K.N_j)$ purely relies on the $Q$ and $K$, the importance scores of all neighbors $Q.N$ and $K.N$ can be simultaneously computed in one step. The top-$k$ neighbors can be directly selected thereafter:
\begin{equation}
\begin{aligned}
Q.\tilde{N} = \text{top-}k({r}(Q.N_i)|\forall Q.N_i \in Q.N); \\
K.\tilde{N} = \text{top-}k({r}(K.N_j)|\forall K.N_j \in K.N).
\end{aligned}
\end{equation}
The other option is the \textit{multi-step} ranking function, which consecutively filters useful neighbors one by one in multiple steps. In this method, the importance score of a neighbor is estimated based on not only the matching documents $Q$ and $K$, but also the already selected neighbors $Q.\tilde{N}$ and $K.\tilde{N}$ (initialized to be empty at the beginning):
\begin{equation}
\begin{aligned}
{r}(Q.N_i) = \mathcal{R}^{mul}(Q.N_i|Q,K,Q.\tilde{N}); \\
{r}(K.N_j) = \mathcal{R}^{mul}(K.N_j|Q,K,K.\tilde{N}).
\end{aligned}
\end{equation}
The underlying intuition is that the selected neighbors are desired of providing comprehensive information about $Q$ and $K$'s relationship. As a result, their underlying semantics are desired to be diversified. In other words, it is unnecessary to choose multiple identical or highly similar neighbors, because no additional information can be introduced by them. In this place, the selection is performed for $k$ consecutive rounds w.r.t to the already selected neighbors. The neighbor with the largest information gain is selected in each step:
\begin{equation}
\begin{aligned}
Q.\tilde{N} \leftarrow Q.\tilde{N}+ Q.N_*, ~ & Q.N \leftarrow Q.N \setminus Q.N_*, ~ & \text{where}~
Q.N_* = \mathrm{argmax}(\mathrm{r}(Q.N_i));\\
K.\tilde{N} \leftarrow K.\tilde{N}+ K.N_*, ~ & K.N \leftarrow K.N \setminus K.N_*, ~ & \text{where}~
K.N_* = \mathrm{argmax}(\mathrm{r}(K.N_i)).
\end{aligned}
\end{equation}
$\bullet$ \textbf{Truncation}. The ranking function only measures the relative importance of all neighbors, whereas it is still unclear how many top-ranked neighbors should be selected. Some documents may have very few useful neighbors for the given semantic matching task, while others may have a large number of useful neighbors. In this paper, we propose the following heuristic strategies to determine how to truncate the top-ranked neighbors to get the optimal subset, including basically static methods and more flexibly dynamic methods. All these strategies can be easily applied together with the ranking functions. In practice, the truncation strategy can be chosen based on empirical performance.
\textit{Fixed Capacity}. The simplest way of truncation is to set a fixed capacity and always select the same number of neighbors for all documents when making the Top-$k$ selection. As discussed above, a fixed capacity may lack the flexibility to deal with documents with different numbers of useful neighbors. Thus, more complicated strategies are further introduced for a complement.
\textit{Absolute Value as Threshold}. Since the utility of neighbors is reflected by the predicted score $r(Q.N_i)$ or $r(K.N_j)$, we think there should be an absolute score threshold $\tau$ to distinguish whether a neighbor is necessary to be selected. In this case, a neighbor $Q.N_i$ will be selected if $r(Q.N_i)>\tau$, the same for $K.N_j$. Both approaches set a static threshold (capacity or value) for truncation, more flexibly dynamic methods are listed in the next.
\textit{Overall Ranking}. Recall that we define the semantic matching task in a typical ranking style as Definition~\ref{def:1}, we think the truly positive key documents would have more useful neighbors to support their connection with the query document than those negative ones. Thus, when measuring the utility of all keys' neighbors with the ranking function, the positive key counterpart would have more neighbors that achieve high ranking scores, and more neighbors should be selected for it. Based on this hypothesis, we propose to rank the neighbors of all candidate keys in a unified list, and select those neighbors within the Top-$p$ position. We illustrate the matching tasks between a query document $Q$ and a series of key documents $K_1,K_2,\ldots$ as an example. We copy $Q$ for many times to construct document pairs with all the keys, obtaining $[Q_1,K_1],[Q_2,K_2],\ldots$ where all $Q_i$ are the same. For all keys, we rank all their neighbors $K_i.N_j$ in a unified list based on the ranking score $r(K_i.N_j)$ and selected those neighbors within the Top-$p$ position for the corresponding key. With regard to the copied queries $Q_1,Q_2,\ldots$, we rank all their neighbors $Q_i.N_j$ in an unified list on top of their ranking scores $r(Q_i.N_j)$ and select the Top-$p$ neighbors. Although the $Q$ and $Q.N$ are copied, when dealing with different key documents, the ranking score of the query neighbors is decided by different keys to highlight different neighbors.
\textit{Relevance Score as Threshold}. Another intuition is that the introduction of neighbor features should strengthen the correlation between $Q$ and $K$, as presented in Definition~\ref{def:1}. Therefore, we expect that the selected neighbors can outscore the original relevance between $Q$ and $K$. At first, we measure the $Q$ and $K$'s similarity as $sim(Q,K)$ (sample implementation of $sim(Q,K)$ will be introduced in Subsection \ref{subsec:implement}). Then, a neighbor $Q.N_i/K.N_i$ will be selected if it satisfies $r(Q.N_i)>sim(Q,K)/r(K.N_i)>sim(Q,K)$.
To summarize, the method of fixed capacity selects the same number of neighbors for all documents, while the other three methods are adaptive to different matching tasks. The two kinds of strategies can be combined together to benefit each other.
\subsubsection{Graph-based Matching Network}
In the second stage, a graph-based semantic matching network is deployed. The matching network will take the query $Q$, key $K$, and the selected neighbors $Q.\tilde{N}$ and $K.\tilde{N}$ as the input. Then, it predicts $Q$ and $K$'s relevance score as:
\begin{equation}\label{eq:match}
m(Q,K) = \mathcal{M}(Q\oplus{Q.\tilde{N}},K\oplus{K.\tilde{N}}),
\end{equation}
where ``$\oplus$'' is the graph aggregator. Though CDSM is generic and adaptive to various matching models, we desire a high-capacity graph-based semantic matching network in order to derive fine-grained relevance prediction, e.g., TextGNN and GraphFormers. (This is different from the neighbor selector which requires lightweight computation.) Besides, knowing that the matching network only needs to deal with a small set of well-selected neighbors, $|Q.\tilde{N}| \ll |Q.N|$ and $|K.\tilde{N}| \ll |K.N|$, the relevance prediction is ensured to be made with much less computation overhead.
\begin{figure*}
\centering
\includegraphics[width=0.9\linewidth]{Figures/Optimization.pdf}
\caption{The hybrid optimization workflow of the CDSM framework: (1) Training the graph-based matching network $\mathcal{M}$ based on the document pairs with heuristically sampled neighbors; (2) Annotating the neighbors' usefulness with the well-trained matching network; (3) Training the neighbor selector with these weak annotations.}
\label{fig:optimization}
\end{figure*}
\subsection{The CDSM Optimization}
The optimization of CDSM is challenging because there are no explicit measurements of neighbors' usefulness. To deal with this challenge, we propose a hybrid optimization workflow, where the neighbor selector is trained on top of weak annotations from the semantic matching network.
$\bullet$ \textbf{Hybrid Optimization} The proposed hybrid optimization works in the following three steps, as illustrated in Figure~\ref{fig:optimization}. First, we train the graph-based matching network $\mathcal{M}$ based on the labeled document pairs and randomly sampled neighbors. Second, the well-trained semantic matching model is used to annotate the neighbor's usefulness based on Definition~\ref{def:1}. Finally, the ad-hoc neighbor selector is trained on the annotation results through contrastive learning. The details of each step are illustrated in the following.
$\bullet$ \textbf{Train Semantic Matching Network}. Given a positive pair of documents $Q, K$ and their neighbors $Q.N, K.N$ which are selected by random sampling or heuristic rules, the matching score is calculated as $m(Q,K) = \mathcal{M}(Q\oplus Q.N, K\oplus K.N)$ (Eq.~\ref{eq:match}). Then, we randomly sample a batch of negative key documents $[K_1^-,K_2^-,\ldots,K_M^-]$. The matching network is trained to distinguish the positive keys from the negative keys by minimizing the classification loss.
\begin{equation}
\mathcal{L}^{cls} = -\frac{\exp(m(Q,K^+))}{\exp(m(Q,K^+))+\sum_{i}\exp(m(Q,K_i^-))}.
\end{equation}
In our implementation, we make use of ``in-batch negative samples''~\cite{luan2020sparse,Karpukhin2020inbatch} to reduce the computation cost, where for one positive document pair, the keys of the other samples in the same mini-batch are viewed as negative keys.
$\bullet$ \textbf{Train Ad-hoc Neighbor Selector}. The neighbor selector is trained via weak supervision, with neighbors’ usefulness annotated by the semantic matching model trained in the last step. Based on whether the one-step or multi-step ranking function is utilized, the data annotation is performed in two different ways.
When the one-step ranking function $R^{one}(\cdot)$ is utilized, a neighbor's usefulness is determined purely based on the input features of $Q$ and $K$. For a positive pair of documents $Q, K$, their semantic matching score without any neighbor features can be calculated as $\mathcal{M}(Q,K)$. Then, the usefulness of each query neighbor $Q.N_i$ for this matching task is evaluated as $\mathcal{M}(Q\oplus Q.N_i,K)$, and that of each key neighbor $K.N_i$ is denoted as $\mathcal{M}(Q,K\oplus K.N_i)$. A neighbor is useful if it improves the matching network's prediction about the relationship between $Q$ and $K$, based on which the labels are generated by the formulations:
\begin{equation}
\begin{split}
l(Q.N_i) =
\begin{cases}
+: ~ \mathcal{M}(Q\oplus{Q.N_i}, K) > \mathcal{M}(Q, K),
\\
-: ~ \mathcal{M}(Q\oplus{Q.N_i}, K) \leq \mathcal{M}(Q,K),
\end{cases}
\\
l(K.N_i) =
\begin{cases}
+: ~ \mathcal{M}(Q, K\oplus{K.N_i}) > \mathcal{M}(Q, K),
\\
-: ~ \mathcal{M}(Q, K\oplus{K.N_i}) \leq \mathcal{M}(Q, K).
\end{cases}
\end{split}
\end{equation}
$l(Q.N_i)$ and $l(K.N_i)$ are the labels of the neighbors, and $\mathcal{M}(\cdot)$ denotes the matching network's predicting function.
When the multi-step ranking function $R^{mul}(\cdot)$ is utilized, the neighbor's usefulness is measured based on not only $Q$ and $K$, but also the already selected neighbors. As a result, we define a neighbor to be useful if it further improves the matching network's prediction about $Q$ and $K$'s relevance after introducing it into the currently selected neighbor subset $Q.\tilde{N}, K.\tilde{N}$.
\begin{equation}
\begin{split}
l(Q.N_i) =
\begin{cases}
+: ~ \mathcal{M}(Q\oplus\{Q.N_i,Q.\tilde{N}\}, K) > \mathcal{M}(Q\oplus{Q.\tilde{N}}, K),
\\
-: ~ \mathcal{M}(Q\oplus\{Q.N_i,Q.\tilde{N}\}, K) \leq \mathcal{M}(Q\oplus{Q.\tilde{N}}, K),
\end{cases}
\\
l(K.N_i) =
\begin{cases}
+: ~ \mathcal{M}(Q, K\oplus\{K.N_i,K.\tilde{N}\}) > \mathcal{M}(Q, K\oplus{K.\tilde{N}}),
\\
-: ~ \mathcal{M}(Q, K\oplus\{K.N_i,K.\tilde{N}\}) \leq \mathcal{M}(Q, K\oplus{K.\tilde{N}}).
\end{cases}
\end{split}
\end{equation}
With the neighbors of all positive document pairs annotated, we construct neighbor pairs comprised of a positive neighbor $N_i^+$ and a negative neighbor $N_i^-$ to train the selector by contrastive learning. Taking a given query document $Q$ as an example, the neighbor selector is learned by minimizing the following loss:
\begin{equation}
\mathcal{L}^{sel} = -\frac{1}{1+\exp(-(r(Q.N_i^+)-r(Q.N_i^-)))}.
\end{equation}
$r(Q.N_i^+)$ and $r(Q.N_j^-)$ are calculated by the corresponding $R^{one}(\cdot)$ or $R^{mul}(\cdot)$, when different ranking functions are applied.
\subsection{The CDSM Implementation}\label{subsec:implement}
In this place, we show a prototype implementation of the ad-hoc neighbor selector, which will be used in our experiments. In order to guarantee efficiency, we adopt a lightweight architecture, including a CNN-based text encoder and a ranking function. The implementation of graph-based semantic matching networks follows baseline models, whose details will be introduced in Section~\ref{sec:experimental_setting}.
As for the CNN-based text encoder, the input is an individual text, taking the query $Q=[w_1^Q,w_2^Q,\ldots]$ as an example. The first layer is a word embedding layer that converts tokens into low-dimensional vectors. By passing the query through this layer, we obtain a word embedding matrix $V^Q=[v_1^Q,v_2^Q,\ldots]$. The second layer is a 1-d CNN layer, capturing local context information within the text sequence to obtain better word representations. As for the i-th term, its context-aware representation $c_i^Q$ is calculated as:
\begin{align}
c_i^Q = \text{ReLU}(F_w\times v_{(i-k):(i+k)}^Q + b_w),
\end{align}
where $v_{(i-k):(i+k)}^Q$ means the word embeddings from the position $(i-k)$ to $(i+k)$. $2k+1$ is the size of the context window. $F_w$ and $b_w$ are the parameters of CNN filters. Through the 1-d CNN layer, the output is a matrix of contextual word representations, denoted as $C^Q=[c_1^Q,c_2^Q,\ldots]$. Considering that different words in a sentence contribute different informativeness, we set the third layer as a word-level attention network. The query in the attention mechanism is a trainable dense vector $q_w$. We compute the attention weight of each word based on the interaction between the query $q_w$ and the context-aware word representation, i.e.,
\begin{align}
\alpha _i = \frac{\exp(\alpha_i)}{\sum_{j=1}^{|Q|}\exp(\alpha_j)},\quad \alpha _i = (c_i^Q)^T \text{tanh}(W_q\times q_w + b_q).
\end{align}
Finally, the text representation $r^Q$ of $Q$ is the weighted sum of all word representations based on the attention weights, as:
\begin{align}
r^Q = \sum_{i=1}^{|Q|}\alpha_ic^Q_i.
\end{align}
Using this CNN-based text encoder, we are able to obtain the text representation for the matching documents $Q, K$ and all the presented neighbors.
With $Q, K$ and all neighbors represented as vectors, the ranking function is employed on them to evaluate the neighbors' importance. With regard to the one-step ranking function, we calculate the usefulness of a neighbor as the relevance between it and the matching counterpart:
\begin{align}
\mathcal{R}^{one}(Q.N_i|Q,K) = (r^{Q.N_i})^T r^{K},\\
\mathcal{R}^{one}(K.N_i|Q,K) = (r^{K.N_i})^T r^{Q}.
\end{align}
As for the multi-step ranking function, it calculates the usefulness for a neighbor $Q.N_i/K.N_i$ according to both the selected neighbor set $Q.\tilde{N}/K.\tilde{N}$ and the matching documents $Q, K$. To highlight the different aspects of information that the already selected neighbors cover, we perform max-pooling along the last dimension to aggregate all selected neighbors. Thus, the usefulness is calculated as:
\begin{align}
\mathcal{R}^{mul}(Q.N_i|Q,K,Q.\tilde{N}) = \varphi([r^Q,\text{max-pool}(r^{N_i}|\forall N_i \in N)])^T r^K,
\end{align}
where $N = Q.\tilde{N} + Q.N_i$. $\varphi(\cdot)$ is an MLP layer, $[\cdot,\cdot]$ indicates vector concatenation, and $\text{max-pool}(\cdot)$ is the max-pooling operation along the last dimension.
For the function $sim(\cdot)$ to measure $Q$ and $K$'s similarity, it works as:
\begin{align}
sim(Q,K) = (r^Q)^T r^K.
\end{align}
\begin{table}[]
\centering
\caption{Time complexity analysis of CDSM and other graph-based matching methods.}
\begin{tabular}{c|ccc}
\toprule
Method & All Neighbors & Heuristic Selection & CDSM \\
\hline
Time Complexity & $n * T_m$ & $n * T_h + k * T_m$ & $n * T_s + k * T_m$ \\
\bottomrule
\end{tabular}
\label{tab:time_complexity}
\end{table}
\subsection{The CDSM Efficiency Analysis}
As stated in Section~\ref{sec:intro}, filtering a set of irrelevant neighbors with a lightweight neighbor selector could improve both the efficiency and accuracy of graph-based semantic matching. Here, we deploy a mathematical time complexity analysis to prove the CDSM efficiency. We compare the computation time for the semantic matching task of directly using all neighbors, sampling neighbors heuristically and selecting neighbors with our CDSM framework. The comparison results are displayed in Table~\ref{tab:time_complexity}.
In Table~\ref{tab:time_complexity}, $T_m$ represents the time cost of a high-capacity semantic matching network to encode a document. $T_s$ indicates the time cost of the lightweight selector to process a neighbor node ($T_s << T_m$). $T_h$ means the time cost of selecting a neighbor through heuristic methods, such as random sampling. $n$ and $k$ represent the number of all available neighbors and that of the selected neighbors respectively. As such, when $k << n$, CDSM saves a lot of time for computing the fine-grained document representations compared with using all neighbors. Our designed lightweight selector obtains document representations through CNN, thus the time cost $T_s$ would be so small that CDSM can be comparably efficient as the heuristic sampling methods.
In the next sections, we conduct experiments to verify the strong performance and efficiency of the above introduced simplified selector.
\begin{table}[]
\centering
\caption{Statistics of the three datasets.}
\begin{tabular}{p{1.8cm}|p{2.0cm}|p{1.6cm}|p{1.6cm}}
\toprule
Dataset & \textbf{Wikidata5M} & \textbf{DBLP} & \textbf{Product} \\
\hline
\#Item & 4,018,299 & 3,691,796 & 2,049,487\\
Avg.\#N & 27.35 & 46.94 & 17.02\\
\#Train & 7,145,834 & 3,009,506 & 3,004,199 \\
\#Valid & 66,167 & 60,000 & 50,000\\
\#Test & 100,000 & 100,000 & 536,575\\
\bottomrule
\end{tabular}
\label{tab:data}
\end{table}
\section{Experimental Settings}\label{sec:experimental_setting}
\subsection{Datasets and Evaluations}
\subsubsection{Datasets}
We use three large-scale textual graph datasets for evaluation. 1) \textbf{Wikidata5M}\footnote{https://deepgraphlearning.github.io/project/wikidata5m}, a million-scale knowledge graph dataset introduced in~\cite{Wang2021Wikidata}. It contains entities and their connections. Each entity has an aligned passage from the corresponding Wikipedia page and we take the first sentence from the passage as its textual description. 2) \textbf{DBLP}\footnote{https://originalstatic.aminer.cn/misc/dblp.v12.7z}. This dataset contains academic papers up to 2020-04-09 collected from DBLP\footnote{https://dblp.uni-trier.de/}. The connections between different papers are built upon their citation relationships. We use each paper's title as its textual description. 3) \textbf{Product}. This is a product graph dataset constructed from the real-world Bing search engine. We track each user's web browsing events along with the targeted product web pages and divide her continuous events into sessions with 30 minutes of user inactivity as interval~\cite{yao2020peps}. Following a typical product graph construction method in e-commerce platforms~\cite{wang2018billion}, the products within a common session are linked to each other. Each product has its corresponding textual description which indicates the product name, brand, type and so on.
For these three datasets, we uniformly sample at most 50 neighbors for each center node from the set comprised of its one-order and two-order neighbors. The statistics of datasets are listed in Table~\ref{tab:data}.
\subsubsection{Evaluations}
In this paper, we define the graph-based semantic matching task in the form of a ranking problem, as Definition~\ref{def:2}. For each positive pair of query and key document, we sample 29 negative key documents, and the target is to rank the positive key higher than these negative keys. Two common ranking metrics are leveraged to evaluate the matching accuracy: \textbf{precision@1 (p@1)} and \textbf{ndcg}.
\subsection{Baselines}
Our proposed CDSM is a generic framework to improve both the accuracy and efficiency of the graph-based semantic matching task. It is highlighted for the two-stage workflow instead of a specific semantic matching model: a lightweight neighbor selector to obtain informative neighbors and then the graph-based semantic matching task is conducted, where various mainstream graph-based matching models can be adapted.
\subsubsection{Graph-based Semantic Matching Models}
To verify its generality, various mainstream graph-based semantic matching models are incorporated as the backbone of the matching network. In these models, texts are all encoded with BERT. The last layer's [CLS] token embedding is treated as the document representation.
$\bullet$ \textbf{BERT}~\cite{Devlin2019BERT}: It calculates the semantic matching score as the dot product between the query's and key's [CLS] vectors encoded by BERT respectively, without any neighbor features.
$\bullet$ \textbf{TextGNN}~\cite{Zhu2021TextGNN}: This is one of the most recent graph-based semantic matching methods, with pre-trained language model BERT as the text encoder and GNNs to aggregate the information from neighbors. We consider the following forms of GNNs. \textbf{GAT}~\cite{Velickovic2017GAT}, which combines neighbors and the center document as a weighted sum of all their text vectors. The weight of each text vector is calculated as the attention score with the center document. \textbf{GraphSage}~\cite{Hamilton2017GraphSage}, where the neighbors are first aggregated, then the aggregation result is concatenated with the center document embedding and passed through a dense layer to generate the final representation for semantic matching. There are four different aggregation variants: \textbf{MaxSage} and \textbf{MeanSage}, which aggregate neighbors by max-pooling and mean-pooling respectively. \textbf{AttnSage} aggregates the neighbors based on their attention scores with the center document. \textbf{Counterpart} aggregates the neighbors based on their attention scores with the matching counterpart, as presented in Section~\ref{sec:problem_definition}. The above variants of TextGNN are denoted as \textbf{TextGNN(GAT/Max/Mean/Attn/CP)} in our experiments.
$\bullet$ \textbf{BERT4Graph}: This is a naive extension of BERT from traditional text matching to graph-based semantic matching. For the query, it concatenates the tokens of the query and all neighbors, with a [CLS] token added to the head. Then, the joint token sequence is inputted into BERT for fine-grained interactions. The last layer's [CLS] token embedding is used for the semantic matching, the same for the key document. The semantic matching score is calculated as their cosine similarity.
$\bullet$ \textbf{GraphFormers}~\cite{Yang2021GraphFormer}: This model adopts a deeper fusion of GNNs and text encoders than TextGNN to make more effective use of neighbor features. It nests GNN components between the transformer layers to conduct iterative text encoding and neighbor aggregation.
Except that BERT uses no neighbor information, the other matching models consider neighbors. We apply them as the backbone of the matching network, and compare their performance under different neighbor selection methods.
\subsubsection{Selection Approaches}
Furthermore, to verify the effectiveness of the ad-hoc neighbor selector under our CDSM framework, we compare it with other selection approaches, including random sampling and two heuristic rule-based methods. All these baselines assign a static set of neighbors to each document, without dynamically considering the matching counterparts like our CDSM. Details are listed as follows.
$\bullet$ \textbf{Random Sampling}: For each document, a set of distinct neighbors is randomly sampled from all the presented neighbors.
$\bullet$ \textbf{Popularity}: For each document, we rank all its neighbors according to their popularity, i.e., how many nodes they have connections with. Then, the top-$k$ popular neighbors are selected.
$\bullet$ \textbf{Similarity}: For each center document, the top-$k$ neighbors that are most similar to it are selected. The similarity is computed as the dot product between their vectors encoded by BERT.
$\bullet$ \textbf{CDSM}: This indicates the ad-hoc neighbor selector under our framework.
\begin{table*}[t]
\centering
\setlength{\abovecaptionskip}{0.1cm}
\setlength{\belowcaptionskip}{0.1cm}
\caption{Overall performance of different graph-based semantic matching models with different available neighbor sets: all neighbors, randomly sampled 5 neighbors, 5 neighbors selected according to the popularity, the similarity with the center document and the usefulness measured by CDSM. ``$\dagger$'' denotes that the result is significantly better than other selection methods (except for all neighbors) in t-test with $p \textless 0.05$ level. ``$^*$'' denotes that the result is significantly better than that with all neighbors in t-test with $p \textless 0.05$ level. Results of the best neighbor selection method are shown in bold. }
\label{tab:overall_performance}
\begin{tabular}{p{0.07\textwidth}p{0.17\textwidth}p{0.04\textwidth}p{0.04\textwidth}p{0.04\textwidth}p{0.04\textwidth}p{0.04\textwidth}p{0.04\textwidth}p{0.04\textwidth}p{0.04\textwidth}p{0.045\textwidth}p{0.04\textwidth}}
\toprule
\multirow{2}*{Data} & \multirow{2}*{Methods} & \multicolumn{2}{c}{All} & \multicolumn{2}{c}{Random (5)} & \multicolumn{2}{c}{Popularity (5)} & \multicolumn{2}{c}{Similarity (5)} & \multicolumn{2}{c}{CDSM (5)} \\
\cmidrule(lr){3-4}
\cmidrule(lr){5-6}
\cmidrule(lr){7-8}
\cmidrule(lr){9-10}
\cmidrule(lr){11-12}
& & p@1 & ndcg & p@1 & ndcg & p@1 & ndcg & p@1 & ndcg & p@1 & ndcg\\
\hline
\multirow{9}*{Wiki} & BERT & .644 & .817 & - & - & - & - & - & - & - & - \\
& TextGNN(GAT) & .580 & .772 & .521 & .732 & .416 & .664 & \textbf{.587} & \textbf{.781} & .581 & .778 \\
& TextGNN(Mean) & .694 & .850 & .678 & .840 & .627 & .810 & .662 & .828 & \textbf{.694}$\dagger$ & \textbf{.850}$\dagger$ \\
& TextGNN(Max) & .687 & .844 & .676 & .839 & .653 & .827 & .666 & .831 & \textbf{.697}$\dagger$ & \textbf{.852}$\dagger$ \\
& TextGNN(Attn) & .696 & .850 & .679 & .840 & .620 & .803 & .664 & .829 & \textbf{.694}$\dagger$ & \textbf{.850} \\
& TextGNN(CP) & .705 & .856 & .681 & .841 & .679 & .843 & .674 & .836 & \textbf{.704}$\dagger$ & \textbf{.855}$\dagger$ \\
& BERT4Graph & - & - & .690 & .846 & .622 & .789 & .683 & .841 & \textbf{.705}$\dagger$ & \textbf{.858}$\dagger$ \\
& GraphFormers & .704 & .854 & .689 & .845 & .698 & .852 & .685 & .841 & \textbf{.707} & \textbf{.860} \\
\hline
\hline
\multirow{9}*{DBLP} & BERT & .821 & .914 & - & - & - & - & - & - & - & - \\
& TextGNN(GAT) & .826 & .918 & .776 & .892 & .790 & .900 & .851 & .929 & \textbf{.860}$\dagger^*$ & \textbf{.936}$^*$ \\
& TextGNN(Mean) & .845 & .908 & .817 & .894 & .816 & .894 & .815 & .891 & \textbf{.844}$\dagger$ & \textbf{.907}$\dagger$ \\
& TextGNN(Max) & .805 & .888 & .812 & .891 & .813 & .892 & .812 & .890 & \textbf{.833}$\dagger$$^*$ & \textbf{.902}$\dagger$$^*$ \\
& TextGNN(Attn) & .843 & .906 & .815 & .892 & .813 & .892 & .813 & .875 & \textbf{.842}$\dagger$ & \textbf{.906}$\dagger$ \\
& TextGNN(CP) & .852 & .917 & .819 & .901 & .818 & .901 & .816 & .899 & \textbf{.850}$\dagger$ & \textbf{.916}$\dagger$ \\
& BERT4Graph & - & - & .864 & .936 & .873 & .941 & .878 & .942 & \textbf{.901}$\dagger$ & \textbf{.955}$\dagger$ \\
& GraphFormers & .903 & .955 & .877 & .944 & .882 & .946 & .880 & .942 & \textbf{.909}$\dagger$ & \textbf{.959}$\dagger$ \\
\hline
\hline
\multirow{9}*{Product} & BERT & .481 & .707 & - & - & - & - & - & - & - & - \\
& TextGNN(GAT) & .568 & .774 & .578 & .781 & .545 & .760 & .567 & .770 & \textbf{.588}$^*$ & \textbf{.787} \\
& TextGNN(Mean) & .746 & .883 & .723 & .868 & .721 & .867 & .703 & .852 & \textbf{.748}$\dagger$ & \textbf{.885}$\dagger$ \\
& TextGNN(Max) & .730 & .873 & .728 & .871 & .721 & .867 & .712 & .858 & \textbf{.756}$\dagger$$^*$ & \textbf{.890}$\dagger$$^*$ \\
& TextGNN(Attn) & .744 & .882 & .725 & .869 & .722 & .867 & .706 & .847 & \textbf{.741}$\dagger$ & \textbf{.881} \\
& TextGNN(CP) & .756 & .889 & .728 & .871 & .723 & .867 & .710 & .857 & \textbf{.760}$\dagger$ & \textbf{.892}$\dagger$ \\
& BERT4Graph & - & - & .739 & .877 & .733 & .873 & .722 & .864 & \textbf{.771}$\dagger$ & \textbf{.898}$\dagger$ \\
& GraphFormers & .737 & .879 & .715 & .864 & .711 & .862 & .701 & .852 & \textbf{.759}$\dagger$$^*$ & \textbf{.891}$\dagger$ \\
\bottomrule
\end{tabular}
\end{table*}
\subsection{Model Settings}
In our experiments, UniLMv2-base \citep{Bao2020UniLMv2} is applied as the backbone of BERT. As for the ad-hoc neighbor selector, the word embedding layer is initialized with the underlying word vectors in UniLMv2-base. Dimensions of the word embeddings and hidden states are set as 768. We utilize the uncased WordPiece~\cite{Wu2016google} to tokenize all text sequences. The max length of sequences is set as 64 for Wikidata5M, 32 for DBLP, 32 for Product. For the CNN text encoder, the size of the context window is 3. The batch size is 300 and the learning rate is 1e-5. Adam optimizer is applied for training the selector.
As for high-capacity matching models, on Wikidata5M, DBLP and Product, the batch size is 160, 240, 240; the learning rates are 5e-6, 1e-6, 1e-5. `In-batch negative samples' and Adam are used for optimization. Each training sample is comprised of two groups of documents: 1 query document with 5 randomly sampled neighbors; and 1 key document with 5 randomly sampled neighbors. The training is conducted with 8x Nvidia V100-16GB GPUs.
\begin{figure}
\centering
\includegraphics[width=0.6\linewidth]{Figures/sensitivity.pdf}
\caption{Performance curves of the TextGNN(CP) model with different numbers of neighbors selected by different methods.}
\label{fig:sensitivity}
\end{figure}
\begin{figure*}
\centering
\includegraphics[width=1.0\linewidth]{Figures/performance_curves.pdf}
\caption{Performance curves of different semantic matching models with different number of neighbors selected by CDSM. The best results are marked by black circles.}
\label{fig:performance_curve}
\end{figure*}
\section{Experimental Results and Analysis}~\label{sec:results}
In this section, we conduct extensive experiments to explore the following research questions:
\begin{itemize}[leftmargin=*]
\item \textbf{RQ1}: As a generic framework, can CDSM consistently improve both the accuracy and efficiency of the semantic matching task when combined with various graph-based semantic matching networks? (Discussed in Subsection~\ref{subsec:rq1})
\item \textbf{RQ2}: Different truncation approaches are proposed to determine the number of selected neighbors. How do they impact the effect and efficiency of the semantic matching task respectively? (Discussed in Subsection~\ref{subsec:rq2})
\item \textbf{RQ3}: Can the simplified selector learn to identify the usefulness of neighbors precisely enough? (Discussed in Subsection~\ref{subsec:rq3})
\item \textbf{RQ4}: How about the effect and efficiency of the one-step and multi-step ranking functions in CDSM? (Discussed in Subsection~\ref{subsec:rq4})
\end{itemize}
\subsection{Overall Performance (RQ1)}~\label{subsec:rq1}
To demonstrate the generality and effectiveness of CDSM, we compare the performance of different semantic matching models in various scenarios where different neighbor sets are available: all neighbors, 5 randomly sampled neighbors, 5 most popular neighbors, 5 neighbors most similar with the center document and 5 neighbors filtered by the ad-hoc neighbor selector in CDSM. The comparison results are presented in Table~\ref{tab:overall_performance}. We also conduct sensitivity testing with TextGNN(CP) on the number of neighbors selected by different methods, shown in Figure~\ref{fig:sensitivity}. Furthermore, we check the matching accuracy with the top $k$ neighbors selected by CDSM as $k$ becomes larger, shown in Figure~\ref{fig:performance_curve}. Due to the limitation of computing resources, at most 5 neighbors are tested for BERT4Graph and GraphFormers. Observing all these results, we have several findings:
First, \textbf{extrinsic neighbor features provide helpful information for the semantic matching task, but these neighbor features are indeed highly noisy. Selecting an optimal neighbor subset can achieve better performance than using all neighbors.} With joint consideration of the center document and neighbors, these graph-based semantic matching models outperform the BERT only baseline in most cases. BERT4Graph and GraphFormers which make fuller use of the neighbor features achieve the best results. However, only a small fraction of neighbors actually contribute to the semantic matching accuracy while others are noise. Comparing the results of different graph-based matching models with all neighbors and the best-performed 5 neighbors (shown in bold) on all datasets in Table~\ref{tab:overall_performance}, most matching models present similar performance. This result demonstrates that a lot of neighbors take no information to improve the matching accuracy. Focusing on the performance curves displayed in Figure~\ref{fig:performance_curve}, the curve of most models rises first and then goes down as more and more neighbors with little informativeness are involved. This trend proves that selecting a set of truly informative neighbors can achieve better matching accuracy than utilizing all neighbors.
Second, \textbf{our proposed lightweight ad-hoc neighbor selector has the ability to efficiently select the truly informative neighbors to enhance the semantic matching accuracy.} As shown in Table~\ref{tab:overall_performance}, the 5 neighbors selected by our CDSM framework perform much better than the neighbor subsets constructed by other selection baselines. Random sampling is unable to distinguish the usefulness of neighbors. In Popularity and Similarity, a static set of neighbors with a specific attribute is assigned to each document and used in matching tasks with various counterparts, thus leading to negative performance. Especially for the Popularity method, a popular neighbor node on the textual graph may be general and contain less informativeness to help specific document matching tasks, which is obvious on the Wiki dataset. Differently, our neighbor selection is performed in an ad-hoc manner to filter neighbors that are relevant to the current counterpart to facilitate the current matching task. Figure~\ref{fig:sensitivity} further presents the comparison between different selection methods with different numbers of neighbors. CDSM could always filter more informative neighbors to achieve better results than other methods, especially for cases where the computation resources are limited and the number of available neighbors is small. From Figure~\ref{fig:performance_curve}, we can come to that the neighbors ranked at high positions by CDSM significantly improve the semantic matching accuracy, whereas the neighbors with lower scores hardly improve the accuracy and even reduce the results. This observation proves that our selector can precisely measure the usefulness of neighbors for a specific matching task. Besides, we also test the time and space cost of neighbor selections. Table~\ref{tab:cost_comparison} shows that the neighbor selector is sufficiently lightweight and efficient.
Third, \textbf{our generic CDSM framework can be well combined with various graph-based matching models to consistently achieve better effects and efficiency on the semantic matching task.} As shown in Table~\ref{tab:overall_performance}, for different graph-based matching models, our CDSM framework can consistently select an effective neighbor subset to achieve comparable or better results than using all neighbors. This verifies the generality of our proposed CDSM framework. In Figure~\ref{fig:performance_curve}, we find that the best results of different models are all achieved with a small subset of informative neighbors selected by our selector, instead of encoding all the presented neighbors. Thus, a large amount of unnecessary encoding cost is saved and much background noise is avoided to get better results. Observing Table~\ref{tab:cost_comparison}, little selection cost is increased while large encoding cost can be reduced by selecting a subset of neighbors by CDSM. Therefore, both the effects and efficiency of semantic matching can be improved with the CDSM framework.
To conclude, we confirm that \textbf{neighbor selection is critical for the graph-based semantic matching task. Our CDSM framework can efficiently select a more effective neighbor subset for the matching task, improving both effectiveness and efficiency.}
\begin{table*}[t]
\centering
\caption{Comparison of truncation methods. ``Avg.N'' indicates the average number of selected neighbors.}
\label{tab:stopping_conditions}
\begin{tabular}{p{0.07\textwidth}p{0.17\textwidth}p{0.055\textwidth}p{0.05\textwidth}p{0.055\textwidth}p{0.05\textwidth}p{0.055\textwidth}p{0.05\textwidth}p{0.055\textwidth}p{0.05\textwidth}}
\toprule
\multirow{2}*{Datasets} & \multirow{2}*{Methods} & \multicolumn{2}{c}{Fixed Capacity} & \multicolumn{2}{c}{Absolute Score} & \multicolumn{2}{c}{Overall Ranking} & \multicolumn{2}{c}{Relevance Score}\\
\cline{3-10}
& & NDCG & Avg.N & NDCG & Avg.N & NDCG & Avg.N & NDCG & Avg.N \\
\hline
\multirow{5}*{Wiki} & TextGNN(GAT) & .784 & 14.00 & .784 & 7.09 & \textbf{.785} & \textbf{4.04} & .784 & 5.79 \\
& TextGNN(Mean) & .850 & 6.00 & .850 & 4.23 & \textbf{.851} & \textbf{5.62} & .850 & 9.99 \\
& TextGNN(Max) & .853 & 5.00 & .852 & 2.99 & .852 & 2.80 & \textbf{.853} & \textbf{3.22} \\
& TextGNN(Attn) & .850 & 7.00 & .850 & 5.71 & .850 & 5.71 & \textbf{.851} & \textbf{10.28} \\
& TextGNN(CP) & .856 & 20.00 & .855 & 10.33 & .856 & 14.85 & \textbf{.856} & \textbf{10.66} \\
\hline
\hline
\multirow{5}*{DBLP} & TextGNN(GAT) & .937 & 10.00 & \textbf{.938} & \textbf{10.13} & .938 & 11.06 & .937 & 6.80 \\
& TextGNN(Mean) & .911 & 16.00 & .910 & 11.06 & .911 & 11.80 & \textbf{.911} & \textbf{8.13} \\
& TextGNN(Max) & .905 & 11.00 & .901 & 8.95 & .905 & 8.47 & \textbf{.905} & \textbf{7.32} \\
& TextGNN(Attn) & .910 & 15.00 & .910 & 12.93 & .910 & 12.47 & \textbf{.910} & \textbf{8.87} \\
& TextGNN(CP) & .920 & 18.00 & .919 & 14.28 & .920 & 14.32 & \textbf{.920} & \textbf{9.48} \\
\hline
\hline
\multirow{5}*{Product} & TextGNN(GAT) & .788 & 7.00 & \textbf{.788} & \textbf{2.27} & .788 & 3.36 & .788 & 4.77 \\
& TextGNN(Mean) & .885 & 6.00 & .885 & 4.71 & \textbf{.886} & \textbf{3.27} & .886 & 3.91 \\
& TextGNN(Max) & .893 & 3.00 & .893 & 2.56 &.892 & 1.76 & \textbf{.893} & \textbf{2.55} \\
& TextGNN(Attn) & .883 & 8.00 & .883 & 5.82 & \textbf{.883} & \textbf{4.05} & .882 & 4.46 \\
& TextGNN(CP) & .892 & 6.00 & .892 & 4.67 & \textbf{.892} & \textbf{3.31} & .891 & 4.34 \\
\bottomrule
\end{tabular}
\end{table*}
\subsection{Analysis of Truncation (RQ2)}~\label{subsec:rq2}
As for the ad-hoc neighbor selector in our CDSM framework, in addition to the ranking function that predicts the relative importance of all neighbors, we set truncation to determine how many top-ranked neighbors should be selected. Several different truncation approaches are proposed. We take empirical experiments to analyze their impacts on the effects and efficiency of semantic matching respectively. The results are displayed in Table~\ref{tab:stopping_conditions}. For all cases, the max number of selected neighbors is restricted to 20.
First of all, setting a relatively small fixed capacity as the truncation shows very stable performance on various matching models. For the documents with few informative neighbors, these neighbors are involved without too much noise. For those documents with a lot of effective neighbors, selecting a part of top-tanked neighbors may be sufficient to distinguish them from the negative keys. Introducing adaptive strategies further reduces the computation cost, even promoting the matching accuracy. By setting an appropriate absolute value threshold, we could adaptively select informative neighbors for each pair of matching documents. Fewer neighbors will be selected for the scenarios where only a small fraction of neighbors are informative, instead of a fixed number, thus saving a lot of computing resources. More neighbors would be selected for the documents that have many informative neighbors, providing more supporting evidence to enhance the matching. The relevance score threshold shows the best performance in most cases. Recall that in Definition~\ref{def:1}, we argue that a neighbor contributes to a specific document matching task when it provides additional evidence. As such, the relevance score threshold performs as a serious filter to highlight neighbors that are more informative than the center document.
\begin{table}[t]
\centering
\caption{Comparison about the time and space cost of the lightweight selector and high-capacity semantic matching network.}
\label{tab:cost_comparison}
\begin{tabular}{p{0.2\linewidth}p{0.15\linewidth}p{0.16\linewidth}p{0.15\linewidth}p{0.16\linewidth}}
\toprule
\multirow{2}*{Scenarios} & \multicolumn{2}{c}{All 50 Neighbors} & \multicolumn{2}{c}{Select 5 Neighbors} \\
\cmidrule(lr){2-3}
\cmidrule(lr){4-5}
& Time(ms) & Space(MB) & Time(ms) & Space(MB) \\
\hline
Selection & - & - & 1.72 & 1000 \\
Matching & 1425.0 & 10219 & 217.0 & 2361 \\
\hline
Total & 1425.0 & 10219 & 218.72 & 3361 \\
\bottomrule
\end{tabular}
\end{table}
\begin{figure}
\centering
\includegraphics[width=0.7\linewidth]{Figures/selected_neighbors.pdf}
\caption{Distribution of the top 10 neighbors selected in the CDSM framework. The rank position is decided by the usefulness annotated by the well-trained semantic matching model.}
\label{fig:selected_neighbors}
\end{figure}
\subsection{Effects and Efficiency of Selector (RQ3)}~\label{subsec:rq3}
To ensure the running efficiency, the neighbor selector in our CDSM framework should be lightweight. We compare its computation cost with the high-capacity matching network and present the results in Table~\ref{tab:cost_comparison}. The time and space cost of the selector are both much smaller than the expensive matching model, which could be ignored. Then, we conduct an experiment to analyze whether the highly simplified selector can learn to accurately identify useful neighbors.
Due to a lack of labels to explicitly measure the usefulness of neighbors, we develop a weak-supervision strategy to train the neighbor selector on top of weak annotations generated by the well-trained matching model. Thus, we evaluate the learning ability of the simplified selector by how well it could adapt to the annotations from the matching model. We make a comparative analysis of their respective evaluations about the neighbors. At first, we rank all neighbors of each matching task according to their usefulness measured by the semantic matching model as Definition~\ref{def:1}. Then, we apply the trained selector to score the neighbors and observe which neighbors in the above ranking are scored as the top 10. The distribution of original ranking positions is displayed in Figure~\ref{fig:selected_neighbors}. We find that most of the top 10 neighbors scored by the selector still correspond to those ranked at the top 10 positions by the high-capacity matching model, some at 10-20. This demonstrates that the highly simplified selector fits well to the annotations provided by the high-capacity matching model. It can identify useful neighbors efficiently and accurately.
\begin{figure}
\centering
\includegraphics[width=0.8\linewidth]{Figures/onestep_multistep.pdf}
\caption{Performance curves of One-Step Selector and Multi-Step Selector on the Wiki dataset.}
\label{fig:onestep_multistep}
\end{figure}
\subsection{One-Step v.s. Multi-Step Selection (RQ4)}~\label{subsec:rq4}
As for the ad-hoc neighbor selector in CDSM, we propose two different ranking functions, i.e. one-step and multi-step ranking functions. The one-step ranking function measures the usefulness of all neighbors based on only $Q, K$ and selects the top-$k$ highest-scoring neighbors at one step. The multi-step ranking function ranks and selects neighbors one by one. In each step, the neighbor leading to the largest information gain is selected. We experiment to compare these two selectors with TextGNN. Limited by the computing resources, at most 5 neighbors are selected.
Observing the performance curve of the two ranking functions in Figure~\ref{fig:onestep_multistep}, both approaches have the ability to distinguish the informativeness of different neighbors and select effective neighbors for the matching task. The multi-step ranking function performs a little better than the one-step. We infer that it may be because the multi-step method selects neighbors in a greedy way to construct a best-performed neighbor subset, instead of evaluating each neighbor separately. In this case, the computation cost of multi-step selection would be much larger than the one-step selection since it needs to evaluate the neighbors multiple times. On the whole, the more efficient one-step selection can achieve a better trade-off between effects and efficiency. We employ the one-step ranking function in other studies.
\subsection{Case Study}~\label{subsec:case_study}
The neighbor selector is the core module in our proposed CDSM framework, and the quality of selected neighbors would directly affect the accuracy of the subsequent text matching. In order to evaluate the quality of neighbor selection, we carry out a qualitative case study on the DBLP dataset. For each pair of documents (Query $Q$, Key $K$) to be matched, we adopt the neighbor selector to score all neighbor nodes. Then, we compare the information contributed to the current matching task by the top 5 neighbors and the worst 5 neighbors respectively. Experimental results are presented in Figure~\ref{fig:case_study}.
We make the following observations. As for the neighbors highly scored by the selector, they can contribute some valuable information for determining the relationship between the current query and key documents. For example, facing the query ``Reinforcement learning: a survey'', the neighbor selector highlights the node relevant with ``reinforcement learning'' for discrimination. As for the query ``'DeepLab: Semantic Image Segmentation...', neighbors related to image segmentation are selected. However, the low-scoring neighbor nodes are much less relevant to the query but only relevant to the key, and even introduce noisy signals.
\begin{figure}
\centering
\includegraphics[width=0.99\textwidth]{Figures/case_study.pdf}
\caption{Case study of the selected and discarded neighbor nodes of the key document for the corresponding query. ``yellow'' highlights relevance with the query and ``blue'' highlights relevance with the key.}
\label{fig:case_study}
\end{figure}
\section{Conclusion} \label{sec:conclusion}
In this paper, we identify the importance of neighbor selection in the graph-based semantic matching task and propose a novel framework, Cascaded Deep Semantic Matching (CDSM). It leverages a two-stage cascaded workflow for the semantic matching task. A lightweight neighbor selector is employed to efficiently filter informative neighbors for the given matching documents in the first stage. Then, the matching model calculates fine-grained relevance scores based on these selected neighbors. Both higher matching accuracy and speed are achieved by our CDSM framework, as unnecessary computation and background noise from irrelevant neighbors are avoided. We develop CDSM as a generic framework that can be seamlessly incorporated with mainstream graph-based models. A weak-supervision strategy is proposed to train the selector with weak annotations generated by the matching model. Empirical experiments on three large-scale textual graph datasets confirm the effectiveness and generality of our CDSM framework.
In summary, one limitation of the current CDSM is that the neighbor selector can accurately compare the usefulness of neighbors to highlight informative ones, but presents weak performance on truncation, i.e. determining how many neighbors should be selected. In Section~\ref{subsec:cdsm_framework}, we discuss several truncation approaches, without one consistently performing the best on all datasets. Designing a more universal automatic truncation method is a research topic in the future. In addition, the current two-step optimization method of CDSM can be iterated multiple times. How to enhance the ability of both the selector and matching model through iterative optimization is also under-explored.
\newpage
\bibliographystyle{ACM-Reference-Format}
| {'timestamp': '2022-12-01T02:19:35', 'yymm': '2211', 'arxiv_id': '2211.17171', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17171'} | arxiv |
\section{Introduction}
\begin{figure}[!htp]
\centering
\includegraphics[width=0.85\linewidth]{figures/1.1.pdf}
\caption{Visualization of the localized regions returned from Eigen-CAM~\cite{muhammad2020eigen} based on a ProtoNet~\cite{NIPS2017_cb8da676} model (trained on CUB-200-211 dataset) optimized by the traditional method, the FRN~\cite{Wertheimer_2021_CVPR}, and the proposed method. The higher energy region denotes the more discriminative part in the image.}
\label{fig:1}
\end{figure}
Few-shot fine-grained image classification~\cite{Huang2021LowRankPA,9293172} has emerged very recently as an important means to tackle the data scarcity problem widely facing fine-grained analysis~\cite{3401454f29a841a29142c97833857e78}. As per the conventional few-shot setting, it asks for effective model transfer given just a few support samples. The differences however lies in the unique characteristics brought by the fine-grained nature of the problem -- the model needs to focus on learning subtle and discriminative features to discriminate not only on the category level (as per conventional few-shot), but importantly also on intra-class level differentiating fine-grained visual differences amongst class instances.
It is therefore not surprising that traditional few-shot methods, when applied to the {fine-grained} problem, can no longer hold their promises. This is clearly seen in Figure~\ref{fig:1}, where we apply ProtoNet~\cite{NIPS2017_cb8da676} on the ``birds'' dataset~\cite{WelinderEtal2010} -- the model {tends to encourage} lower inter-class variations and higher intra-class variations, which is the very opposite of our goal of fine-grained image classification.
Attempts have been made on adapting traditional few-shot learning methods to the fine-grained scenario. Early attempts~\cite{Huang2021LowRankPA, sun2020few, zhu2020multi} have however focused on devising complex architectural designs which resulted in marginal gains over their vanilla counterparts. It was not until very recently that reconstruction-based methods have gained popularity~\cite{Wertheimer_2021_CVPR, NEURIPS2020_fa28c6cd} and consequently achieved state-of-the art performance. Through specifically engineering for {support-query} feature alignment, they naturally encourage fine-grained transfer. Effects of this can be observed in Figure \ref{fig:1}, where feature regions learned by FRN~\cite{Wertheimer_2021_CVPR} tend to be more fine-grained when compared with ProtoNet~\cite{NIPS2017_cb8da676}.
\begin{figure*}[ht]
\centering
\includegraphics[width=0.8\linewidth]{figures/1.2.pdf}
\caption{(a) is the traditional metric based method. (b) is the method proposed in~\cite{Wertheimer_2021_CVPR}. (b) + (c) is the method proposed in this paper. (b) can help the model increase the inter-class variations, and (c) can help the model decrease the intra-class variations.}
\label{fig:1.2}
\end{figure*}
However upon careful inspection, we importantly observe that although the model can focus on more subtle and discriminative regions, the semantic information they represented is nonetheless disparate between any two samples belonging to the same class (e.g., ``Class 1'' FRN focused on different parts of a bird). This seems to suggest that these reconstruction-based methods still suffer from having large intra-class variations, which is counter-productive for overall fine-grained learning (large inter-class variations and small intra-class variations). In other words, such methods only help to increase inter-class variations and do not reduce intra-class variations very well. The reason, we conjecture, is that the existing reconstruction-based methods~\cite{Wertheimer_2021_CVPR, NEURIPS2020_fa28c6cd} (as shown in Figure~\ref{fig:1.2}(b)) works in a unidirectional fashion, i.e., reconstruction only happens one way from support features to query features.
Consequently, it can only constrain the relationship between reconstructed query features and original query features to increase inter-class variations. This however fails to constrain the relationship between samples within each class in the support set, which is pivotal in decreasing intra-class variations.
As such, in this paper, we for the first time introduce a bi-directional reconstruction mechanism for few-shot fine-grained classification. Instead of using the support set to reconstruct the query set to increase inter-class variations only (as shown in Figure~\ref{fig:1.2}(b)),
we additionally use the query set to reconstruct the support set to simultaneously reduce intra-class variations (as shown in Figure~\ref{fig:1.2}(c)). This modification might sound overly simple at first sight, it however importantly fulfills both desired learning outcomes for the fine-grained setting -- support to query to encourage large inter-class variations, and query to support to encourage small intra-class variations
(see Section \ref{Ablation} for a detailed explanation).
Our bi-directional feature reconstruction framework mainly contains four modules: (i) a feature extraction module, (ii) a self-reconstruction module, (iii) a mutual bi-directional reconstruction module, and (iv) a distance metric module. (i) and (iv) are common to a reconstruction-based approach~\cite{Wertheimer_2021_CVPR}. In addition to the proposed bi-directional module (iii), we also find use of a self-reconstruction module (ii) to benefit fine-grained feature learning, and works well with the former in terms of increasing inter-class variations and reducing intra-class variations. Ablative studies in Section \ref{Ablation} show both to be effective {and indispensable} for few-shot fine-grained learning.
In summary, our contributions are three-fold:
1) We reveal the key problem in current reconstruction-based few-shot fine-grained classification lies with its inability in minimising intra-class variations.
2) We for the first time propose a bi-directional reconstruction network that simultaneously increase inter-class variations while reducing intra-class variations by way of a mutual {support-query and query-support} reconstruction.
3) Experimental results and ablative analyses on three fine-grained few-shot image datasets consistently demonstrate the superiority of the proposed method and reveal insights on why the bi-directional approach is effective.
\section{Related works}
\textbf{Metric-Based Few-shot Learning:}
In few-shot learning methods, metric-based methods have received extensive attention owing to their simplicity and efficiency~\cite{Li2021DeepML}.
{A plethora of earlier works have adopted fixed metric or learnable module to learn a good metric embedding~\cite{NIPS2017_cb8da676, DBLP:conf/nips/VinyalsBLKW16, 8578229}. These methods classify samples according to distance or similarity.}
Recently, GNN-based few-shot methods~\cite{garcia2018fewshot, Kim_2019_CVPR, Yang_2020_CVPR} adopted graph neural networks (GNN) to model the similarity measurement -- their advantage being that samples have a rich relational structure.
In addition to these classic ones, some metric-based methods for fine-grained image classification have also emerged.
While DN4~\cite{8953758} proposed a local descriptor-based image-to-class measure, using local features of samples to learn feature metric, {BSNet~\cite{9293172} used a bi-similarity network to learn fewer but more discriminative regions using a combination of two different metrics.}
NDPNet~\cite{Zhang2021NDPNetAN} designed a feature re-abstraction embedding network that projects the local features into the proposed similarity metric learning network to learn discriminative projection factors.
Our method adopts a fixed euclidean distance to measure the error between construction features and origin features.
\textbf{Alignment-based Few-shot Learning:}
Alignment-based fine-grained few-shot methods pay more attention to align the spatial positions of objects in images and then classify them based on a similarity measure.
Unlike PARN~\cite{Wu_2019_ICCV} which is a position-aware relational network that aligns similar objects in spatial position and learns more flexible and robust metric capabilities,
Semantic Alignment Metric Learning (SAML)~\cite{Hao2019CollectAS} aligns the semantically relevant dominant objects in fine-grained images using a collect-and-select strategy.
DeepEMD~\cite{Zhang_2020_CVPR} uses the Earth Mover's Distance to generate the optimal matching flows between two local feature sets and computes the distance between two images based on the optimal matching flows and matching costs.
In addition to these alignment-based methods above, reconstruction-based methods are also good for aligning spatial positions of objects from different fine-grained images.
CTX~\cite{NEURIPS2020_fa28c6cd} constructs a novel transformer-based neural network, which can find a coarse spatial relationship between the query and the labelled images, and then compute the distances between spatially-corresponding features to predict the label of samples.
Alleviating the need for any new modules or large-scale learnable parameters FRN~\cite{Wertheimer_2021_CVPR} obtains the optimal reconstruction weights in the closed form solution to reconstruct query features from support features.
Unlike these existing reconstruction based methods, we introduce bi-directional reconstruction method, that not only reconstructs query samples based on support samples for increasing the inter-class variations, but also reconstructs support samples based on a query sample for reducing the intra-class variations.
\textbf{Attention Mechanism:}
Vaswani et al.~\cite{NIPS2017_3f5ee243} first proposed the self-attention mechanism and then used it to built a new simple network architecture, namely Transformer.
Besides achieving success in natural language processing~\cite{NIPS2017_3f5ee243, Devlin2019BERTPO, brown2020language}, this architecture also works well in computer vision tasks~\cite{dosovitskiy2021an, hassani2021escaping, Chen2021CrossViTCM}.
Recently, some few-shot learning works have gradually begun to adopt the self-attention mechanism. Han-Jia Ye et al.~\cite{Ye_2020_CVPR} proposed a Few-shot Embedding Adaptation with Transformer (FEAT) for few-shot learning. Here authors constructed set-to-set functions using a variety of approximators and found Transformer to be the most efficient option that {can model interactions between images in a set and hence enable co-adaptation of each image.}
{Unlike FEAT where the transformer structure is only used for support samples, CTX~\cite{NEURIPS2020_fa28c6cd} uses self-attention to calculate the spatial attention weights of query sample and support samples and learn a query-aligned class prototype. It then calculates the distance between the query sample and the aligned class prototype to classify the query sample.}
The proposed few-shot classification method also introduced the self-attention mechanism adopted in the transformer to learn optimal reconstruction weights in our self-reconstruction module and mutual reconstruction module.
\section{Methodology}
In this section, we describe our proposed method, starting with a formulation of the proposed method followed by an overview and an in-depth description of each component.
\subsection{The Problem Formulation}
Given a dataset $D = \{(x_i,y_i), y_i \in Y\}$, we divide it into three parts, that is, $D_{base} = \{(x_i,y_i), y_i \in Y_{base}\}$, $D_{val} = \{(x_i,y_i), y_i \in Y_{val}\}$ and $D_{novel} =\{ (x_i,y_i), y_i \in Y_{novel}\}$, where $x_i$ and $y_i$ are the original feature vector and class label of the $i^\text{th}$ image, respectively.
The categories of these three parts are disjoint, i.e., $Y_{base} \cap Y_{val} \cap Y_{novel} = \varnothing$, and $Y_{base} \cup Y_{val} \cup Y_{novel} = Y$.
Few-shot classification aims to improve a $C$-way $K$-shot classification performance on $D_{novel}$ by learning knowledge from $D_{base}$ and $D_{val}$.
For such a task, there are $C$ classes sampled randomly from $D_{novel}$, and each class only has $K$ {randomly sampled} labelled (support) samples $S$, and $M$ {randomly sampled} unlabelled (query) samples $Q$.
Many few-shot methods adopt the meta-learning paradigm~\cite{Finn2017ModelAgnosticMF, ye2022how}. Specifically, the training process of these methods on $D_{base}$ is the same as the prediction process on $D_{novel}$. Their purpose is to learn the meta-knowledge of learning a category concept based on a few labelled samples.
In the meta-training phase, the few-shot classification model learns the categories of query samples based on few support samples in each task on $D_{base}$. The optimal model is selected by evaluating performance of the {few-shot classification model} on multiple tasks on $D_{val}$. In meta-test phase, the final performance of the optimal model are commonly evaluated by the average accuracy on all sampled tasks of $D_{novel}$.
\subsection{Overview}
\begin{figure*}[!ht]
\centering
\includegraphics[width=0.9\linewidth]{figures/3.1.pdf}
\caption{The proposed Bi-Directional feature reconstruction network. FSRM refers to Feature Self-reconstruction Module and FMRM refers to Feature Mutual Reconstruction Module.}
\label{fig:3.1}
\end{figure*}
Learning subtle and discriminative features is crucial for fine-grained few-shot image classification. Considering that the existing reconstruction-based methods, which mostly reconstruct query features based on support features, fail to reduce intra-class variations adequately, we propose a bi-directional reconstruction network.
As shown in Figure~\ref{fig:3.1}, our model consists of four modules:
the first is embedding module $f_{\theta}$ for extracting deep convolutional image features. This can be a traditional convolutional neural network or a residual network.
The second is a feature self-reconstruction module $g_{\phi}$, in which the convolutional features of each image are reconstructed by themselves based on a self-attention mechanism.
This module can make the similar local features become more similar, while dissimilar ones even more dissimilar, and additionally benefits the following feature mutual reconstruction.
The third is a feature mutual reconstruction module, $h_{\gamma}$, which reconstructs sample features in a bidirectional form. This module not only uses the support sample to reconstruct the query sample but also reconstructs the support sample from the query sample. Compared with the existing unidirectional reconstruction which only focuses on increasing inter-class variations of features, the bi-directional reconstruction adds another function -- reducing the intra-class variations of features.
Finally, the fourth is a {Euclidean} metric module, which is in charge of calculating the distance between query sample and reconstructed query sample, as well as support samples and reconstructed support samples. The weighted sum of the two distances are used for classifying query samples.
\subsection{Feature Self-Reconstruction Module (FSRM)}
\begin{figure}[htp]
\centering
\includegraphics[width=0.85\linewidth]{figures/3.2.pdf}
\caption{Feature self-reconstruction module.}
\label{fig:3.2}
\end{figure}
We constructed the feature self-reconstruction module (FSRM), as shown in Figure~\ref{fig:3.2}. For a $C$-way $K$-shot classification task, we input $C \times (K+M)$ samples $x_i$ into the embedding module $f_{\theta}$ to extract features $\hat{x_i} = f_\theta(x_i) \in \mathbb{R}^{d\times h \times w}$, where $d$ is the channel number, $h$ and $w$ represents the height and the width of features, respectively.
Each image feature $\hat{x_i}$ is the input of the FSRM, $g_{\phi}$, and the output of the FSRM is recorded as ${\hat{z_i}} \in \mathbb{R}^{r \times d}$.
First, we reshape the feature $\hat{x_i}$ as $r$ local features in spatial positions $[\hat{x}_i^1, \hat{x}_i^2, \cdots, \hat{x}_i^{r}]$, where $r=h\times w$. The traditional vision transformers~\cite{dosovitskiy2021an} build on standard transformers~\cite{NIPS2017_3f5ee243}, taking the sequence of image patches as input. We {however} compute the summation of the sequence of local features $\hat{x}_i^{j}$ and the corresponding spatial position embedding $E_{pos} \in R^{r \times d}$ as the input of the transformer, i.e.,
${z_i} = [\hat{x}_i^1, \hat{x}_i^2, \cdots, \hat{x}_i^{r}] + E_{pos}$,
where $E_{pos}$ adopts sinusoidal position encoding~\cite{NIPS2017_3f5ee243}.
The output of FSRM module is computed based on the standard self-attention operation in Transformer Encoder, and the computing operation is shown as follows:
\begin{equation}
Attention(Q, K, V) = Softmax(\frac{QK^T}{\sqrt{d_k}})V.
\label{equ:2}
\end{equation}
Therefore, we can obtain $\hat{z_i}$ as,
\begin{equation}
\hat{z_i} = Attention(z_i W_{\phi}^Q, z_i W_{\phi}^K, z_i W_{\phi}^V), \hat{z_i} \in \mathbb{R}^{r\times d},
\end{equation}
where $W_{\phi}^Q$, $W_{\phi}^K$, and $W_{\phi}^V$ are a set of learnable weight parameters with $d\times d$ size. Next, the $\hat{z_i}$ are calculated continually by a Layer Normalization ($LN$) and a Multi-Layer Perceptron ($MLP$).
\begin{equation}
\hat{z_i} = MLP(LN(z_i + \hat{z_i})).
\end{equation}
\subsection{Feature Mutual Reconstruction Module (FMRM)}
\begin{figure}[ht]
\centering
\includegraphics[width=0.8\linewidth]{figures/3.3.pdf}
\caption{Feature mutual reconstruction module.}
\label{fig:3.3}
\end{figure}
We propose Feature Mutual Reconstruction Module (FMRM), as shown in Figure~\ref{fig:3.3}, which contains two operations:
reconstructing support features in one class given a query feature and reconstructing query feature given support features in one class.
For $C$-way $K$-shot classification task, after going through FSRM, we can obtain reconstructed support features of the $c^\text{th}$ class, i.e. $S_c = [\hat{z}_k^c] \in \mathbb{R}^{kr\times d} $, where $k \in [1,\cdots, K]$ {and $c \in [1,\cdots, C]$}, and reconstructed query feature $Q_i =\hat{z_i} \in \mathbb{R}^{r\times d}$, where
$i \in [1,\cdots, C\times M]$.
$S_c$ multiplies by weights $W_{\gamma}^Q$, $W_{\gamma}^K$ and $W_{\gamma}^V$,respectively, obtaining $S_c^Q$, $S_c^K$ and $S_c^V$, where $W_{\gamma}^Q, W_{\gamma}^K, W_{\gamma}^V \in \mathbb{R}^{d\times d}$. Similarly, $Q_i$ multiplies by weights $W_{\gamma}^Q$, $W_{\gamma}^K$ and $W_{\gamma}^V$, respectively, obtaining $Q_i^Q$, $Q_i^K$ and $Q_i^V$.
We calculate the reconstructed $i^\text{th}$ query feature $\hat{Q}_{(c,i)}$ from {support features $S_c^V$ in the $c^\text{th}$ class and the reconstructed support features $\hat{S}_{(i,c)}$ in the $c^\text{th}$ class} from $i^\text{th}$ query using the two equations below.
\begin{equation}
\hat{Q}_{(c, i)} = Attention(Q_i^Q, S_c^K, S_c^V), \hat{Q}_{(c, i)} \in \mathbb{R}^{r\times d},
\label{equ:5}
\end{equation}
\begin{equation}
\hat{S}_{(i, c)} = Attention(S_c^Q, Q_i^K, Q_i^V), \hat{S}_{(i, c)}\in \mathbb{R}^{kr\times d}.
\label{equ:6}
\end{equation}
where $Attention(\cdot, \cdot, \cdot)$ is shown in Equation~\ref{equ:2}.
To our best knowledge, the existing reconstruction methods only use unidirectional reconstruction -- using support features to reconstruct the query feature. Building on existing methods, we add the reverse reconstruction shown in Equation~\ref{equ:6} -- using query feature to reconstruct support features.
\subsection{Learning Objectives}
After FMRM, we use the {Euclidean} metric to compute the distance from this query sample $Q_i$ to the support samples in the $c^\text{th}$ class (Figure~\ref{fig:1.2}(b)) as:
\begin{equation}
d_{Q_i \to S_c} = ||Q_i^V - \hat{Q}_{(c, i)}||^2,
\label{equ:7}
\end{equation}
and compute the distance from the support samples in the $c^\text{th}$ class to the query sample $Q_i$ (Figure~\ref{fig:1.2}(c)) as:
\begin{equation}
d_{S_c \to Q_i} = ||S_c^V - \hat{S}_{(i, c)}||^2.
\label{equ:8}
\end{equation}
The total distance can be obtained by weighted summation of two distances $d_{Q_i \to S_c}$ and $d_{S_c \to Q_i}$, as,
\begin{equation}
d_i^c = \tau(\lambda_1 d_{Q_i \to S_c} + \lambda_2 d_{S_c \to Q_i}),
\label{equ:9}
\end{equation}
where $\lambda_1$ and $\lambda_2$ are learnable weight parameters, and both of them are initialized as $0.5$. $\tau$ is a learnable temperature factor, following~\cite{Wertheimer_2021_CVPR, Ye_2020_CVPR, Chen2020ANM, Gidaris2018DynamicFV}.
We normalize $d_i^c$ to obtain $\hat{d_i^c}$ as:
\begin{equation}
\hat{d_i^c} = \frac{e^{-d_i^c}}{\sum_{c=1}^C e^{-d_i^c}}.
\end{equation}
Based on $\hat{d_i^c}$, the total loss in one $C$-way $K$-shot task can be calculated as:
\begin{equation}
\mathcal{L} = -\frac{1}{M \times C} \sum_{i=1}^{M \times C} \sum_{c=1}^C \textbf{1}(y_ i==c) log(\hat{d_i^c}),
\end{equation}
where $\textbf{1}(y_i==c)$ equals $1$ when $y_i$ and $c$ are equal, otherwise $0$.
During the training process, for a $C$-way $K$-shot task on $D_{base}$, we minimize $\mathcal{L}$ to update the proposed network, and repeat this process on all randomly generated tasks.
\section{Experimental results and Analysis}
\subsection{Datasets and Implementation Details}\label{data_imp}
\textbf{Datasets:}
To evaluate the performance of the proposed method, we selected {three} benchmark fine-grained datasets,
CUB-200-2011 (CUB)~\cite{WelinderEtal2010} is a classic fine-grained image classification dataset. It contains $11,788$ images from $200$ bird species. Following~\cite{Zhang_2020_CVPR,Ye_2020_CVPR}, we crop each image to a human annotated bounding box.
Stanford-Dogs (Dogs)~\cite{KhoslaYaoJayadevaprakashFeiFei_FGVC2011} is a challenging fine-grained image categorization dataset. The dataset includes $20,580$ annotated images of $120$ breeds of dogs from around the world.
Stanford-Cars (Cars)~\cite{6755945} is also a commonly used benchmark dataset for fine-grained image classification. The dataset contains $16,185$ images of $196$ car-types.
For each dataset, we divided it into $D_{train}$, $D_{val}$ and $D_{test}$. The ratio of $D_{train}$, $D_{val}$ and $D_{test}$ is same as the literature ~\cite{zhu2020multi}, and all images are resized to $84 \times 84$.
\textbf{Implementation Details:}
{We conducted experiments on two widely used backbone architectures: Conv-4 and ResNet-12. The architectures of Conv-4 and ResNet-12 are the same as that of ~\cite{Wertheimer_2021_CVPR, Ye_2020_CVPR}.
We implemented all our experiments on NVIDIA 3090Ti GPUs via Pytorch~\cite{Paszke2019PyTorchAI}.
In our experiments, we train all Conv-4 and ResNet-12 models for $1,200$ epochs using SGD with Nesterov momentum of $0.9$. The initial learning rate is set to $0.1$ and weight decay to 5e-4. Learning rate is decreased by a scaling factor of 10 after every 400 epochs.
For Conv-4 models, we train the proposed models using $30$-way $5$-shot episodes, and test for $1$-shot and $5$-shot episodes. We use $15$ query images per class in both settings.
Furthermore, for ResNet-12 models we train our proposed model using $15$-way $5$-shot episodes, in order to save memory.
We employ standard data augmentation, including center crop, random horizontal flip and colour jitter for better training stability. Thereafter, we select the best-performing model based on the validation set, and validate every $20$ epochs. For all experiments, we report the mean accuracy of $10,000$ randomly generated tasks on $D_{test}$ with $95\%$ confidence intervals on the standard $5$-way, $1$-shot and $5$-shot settings.}
\subsection{Comparison with State-of-the-Arts}
\begin{table*}[!ht]
\centering
\caption{5-way few-shot classification performance on the \textit{CUB}, \textit{Dogs} and \textit{Cars} datasets. {The top block uses Conv-4 backbone and the bottom block uses ResNet-12 backbone.} Methods labeled by $\dag$ denote our implementations.}
\label{tab:1}
\begin{tabular}{ccccccc}
\toprule[1pt]
\multirow{2}{*}{\it{Method}}
& \multicolumn{2}{c}{\it{CUB}}
& \multicolumn{2}{c}{\it{Dogs}}
& \multicolumn{2}{c}{\it{Cars}} \\
&\multicolumn{1}{c}{$1$-shot}
& \multicolumn{1}{c}{$5$-shot}
& \multicolumn{1}{c}{$1$-shot}
& \multicolumn{1}{c}{$5$-shot}
& \multicolumn{1}{c}{$1$-shot}
& \multicolumn{1}{c}{$5$-shot} \\ \midrule
ProtoNet$\dag$~(NeurIPS 2017
& 64.82$\pm$0.23
& 85.74$\pm$0.14
& 46.66$\pm$0.21
& 70.77$\pm$0.16
& 50.88$\pm$0.23
& 74.89$\pm$0.18 \\
Relation~(CVPR 2018
& 63.94$\pm$0.92
& 77.87$\pm$0.64
& 47.35$\pm$0.88
& 66.20$\pm$0.74
& 46.04$\pm$0.91
& 68.52$\pm$0.78 \\
DN4~(CVPR 2019
& 57.45$\pm$0.89
& 84.41$\pm$0.58
& 39.08$\pm$0.76
& 69.81$\pm$0.69
& 34.12$\pm$0.68
& {87.47$\pm$0.47} \\
PARN$\dag$~(ICCV 2019
& {74.43$\pm$0.95}
& 83.11$\pm$0.67
& 55.86$\pm$0.97
& 68.06$\pm$0.72
& 66.01$\pm$0.94
& 73.74$\pm$0.70 \\
SAML~(ICCV 2019
& {65.35$\pm$0.65}
& 78.47$\pm$0.41
& 45.46$\pm$0.36
& 59.65$\pm$0.51
& 61.07$\pm$0.47
& 88.73$\pm$0.49 \\
DeepEMD~(CVPR 2020
& 64.08$\pm$0.50
& 80.55$\pm$0.71
& 46.73$\pm$0.49
& 65.74$\pm$0.63
& 61.63$\pm$0.27
& 72.95$\pm$0.38 \\
LRPABN~(TMM 2021
& 63.63$\pm$0.77
& 76.06$\pm$0.58
& 45.72$\pm$0.75
& 60.94$\pm$0.66
& 60.28$\pm$0.76
& 73.29$\pm$0.58 \\
BSNet(D\&C)~(TIP 2021
& 62.84$\pm$0.95
& 85.39$\pm$0.56
& 43.42$\pm$0.86
& 71.90$\pm$0.68
& 40.89$\pm$0.77
& 86.88$\pm$0.50 \\
CTX$\dag$~(NeurrIPS 2020
& 72.61$\pm$0.21
& 86.23$\pm$0.14
& 57.86$\pm$0.21
& 73.59$\pm$0.16
& 66.35$\pm$0.21
& 82.25$\pm$0.14 \\
FRN$\dag$~(CVPR 2021
& 74.90$\pm$0.21
& 89.39$\pm$0.12
& 60.41$\pm$0.21
& 79.26$\pm$0.15
& 67.48$\pm$0.22
& 87.97$\pm$0.11 \\
FRN+TDM$\dag$~(CVPR 2022
& 72.01$\pm$0.22
& 89.05$\pm$0.12
& 51.57$\pm$0.23
& 75.25$\pm$0.16
& 65.67$\pm$0.22
& 86.44$\pm$0.12 \\
Ours
& \textbf{79.08$\pm$0.20}
& \textbf{92.22$\pm$0.10}
& \textbf{64.74$\pm$0.22}
& \textbf{81.29$\pm$0.14}
& \textbf{75.74$\pm$0.20}
& \textbf{91.58$\pm$0.09} \\ \midrule
ProtoNet$\dag$~~(NeurIPS 2017
& 81.02$\pm$0.20
& 91.93$\pm$0.11
& 73.81$\pm$0.21
& 87.39$\pm$0.12
& 85.46$\pm$0.19
& 95.08$\pm$0.08 \\
CTX$\dag$~(NeurIPS 2020
& 80.39$\pm$0.20
& 91.01$\pm$0.11
& 73.22$\pm$0.22
& 85.90$\pm$0.13
& 85.03$\pm$0.19
& 92.63$\pm$0.11 \\
DeepEMD$\dag$~(CVPR 2020
& 75.59$\pm$0.30
& 88.23$\pm$0.18
& 70.38$\pm$0.30
& 85.24$\pm$0.18
& 80.62$\pm$0.26
& 92.63$\pm$0.13 \\
FRN$\dag$~(CVPR 2021
& 84.30$\pm$0.18
& 93.34$\pm$0.10
& {76.76$\pm$0.21}
& {88.74$\pm$0.12}
& 88.01$\pm$0.17
& 95.75$\pm$0.07 \\
FRN+TDM$\dag$~(CVPR 2022
& 85.15$\pm$0.18
& 93.99$\pm$0.09
& \textbf{78.02$\pm$0.20}
& \textbf{89.85$\pm$0.11}
& 88.92$\pm$0.16
& 96.88$\pm$0.06 \\
Ours
& \textbf{85.44$\pm$0.18}
& \textbf{94.73$\pm$0.09}
& {76.89$\pm$0.21}
& 88.27$\pm$0.12
& \textbf{90.44$\pm$0.15}
& \textbf{97.49$\pm$0.05} \\ \bottomrule
\end{tabular}
\end{table*}
\begin{table*}[ht]
\centering
\caption{Ablation studies using only FSRM module or FMRM module.}
\label{tab:3}
\begin{tabular}{ccccccccc}
\toprule[1pt]
\multirow{2}{*}{\it{Backbone}}
&
\multirow{2}{*}{\it{Method}}
& \multicolumn{2}{c}{\it{CUB}}
& \multicolumn{2}{c}{\it{Dogs}}
& \multicolumn{2}{c}{\it{Cars}} \\
&
& \multicolumn{1}{c}{$1$-shot}
& \multicolumn{1}{c}{$5$-shot}
& \multicolumn{1}{c}{$1$-shot}
& \multicolumn{1}{c}{$5$-shot}
& \multicolumn{1}{c}{$1$-shot}
& \multicolumn{1}{c}{$5$-shot} \\ \midrule
\multirow{4}{*}{Conv-4}
&
Baseline (ProtoNet)
& 64.82$\pm$0.23
& 85.74$\pm$0.14
& 46.66$\pm$0.21
& 70.77$\pm$0.16
& 50.88$\pm$0.23
& 74.89$\pm$0.18 \\
&
(FSRM)
& 75.37$\pm$0.21
& 88.61$\pm$0.12
& \textbf{65.10$\pm$0.22}
& 79.94$\pm$0.15
& 71.61$\pm$0.22
& 84.70$\pm$0.14 \\
&
(FMRM)
& 74.92$\pm$0.21
& 89.97$\pm$0.11
& 61.28$\pm$0.21
& 80.07$\pm$0.14
& 70.22$\pm$0.21
& 88.45$\pm$0.11 \\
&
(FSRM+FMRM)
& \textbf{79.08$\pm$0.20}
& \textbf{92.22$\pm$0.10}
& 64.74$\pm$0.22
& \textbf{81.29$\pm$0.14}
& \textbf{75.74$\pm$0.20}
& \textbf{91.58$\pm$0.09} \\ \midrule
\multirow{4}{*}{ResNet-12}
&
Baseline (ProtoNet)
& 81.02$\pm$0.20
& 91.93$\pm$0.11
& 73.81$\pm$0.21
& 87.39$\pm$0.12
& 85.46$\pm$0.19
& 95.08$\pm$0.08 \\
&
(FSRM)
& 82.53$\pm$0.19
& 92.43$\pm$0.10
& 75.64$\pm$0.21
& 87.44$\pm$0.12
& 85.95$\pm$0.18
& 94.44$\pm$0.08 \\
&
(FMRM)
& 84.33$\pm$0.18
& 94.25$\pm$0.09
& 76.29$\pm$0.21
& \textbf{89.06$\pm$0.11}
& 89.62$\pm$0.15
& 97.45$\pm$0.05 \\
&
(FSRM+FMRM)
& \textbf{85.44$\pm$0.18}
& \textbf{94.73$\pm$0.09}
& \textbf{76.89$\pm$0.21}
& 88.27$\pm$0.12
& \textbf{90.44$\pm$0.15}
& \textbf{97.49$\pm$0.05} \\ \bottomrule
\end{tabular}
\end{table*}
\begin{table*}[!htp]
\centering
\caption{Ablation on reconstruction designs of FMRM.}
\label{tab:4}
\begin{tabular}{cccccccc}
\toprule[1pt]
\multirow{2}{*}{\it{Backbone}}
& \multirow{2}{*}{\it{Method}}
& \multicolumn{2}{c}{\it{CUB}}
& \multicolumn{2}{c}{\it{Dogs}}
& \multicolumn{2}{c}{\it{Cars}} \\
&
& \multicolumn{1}{c}{$1$-shot}
& \multicolumn{1}{c}{$5$-shot}
& \multicolumn{1}{c}{$1$-shot}
& \multicolumn{1}{c}{$5$-shot}
& \multicolumn{1}{c}{$1$-shot}
& \multicolumn{1}{c}{$5$-shot} \\ \midrule
\multirow{4}{*}{Conv-4}
&
Baseline (ProtoNet)
& 64.82$\pm$0.23
& 85.74$\pm$0.14
& 46.66$\pm$0.21
& 70.77$\pm$0.16
& 50.88$\pm$0.23
& 74.89$\pm$0.18 \\
&
Ours (Q$\to$S)
& \textbf{79.88$\pm$0.20}
& 91.76$\pm$0.11
& \textbf{65.26$\pm$0.22}
& 80.81$\pm$0.14
& 75.61$\pm$0.20
& 90.49$\pm$0.10 \\
&
Ours (S$\to$Q)
& 76.54$\pm$0.21
& 88.03$\pm$0.14
& 64.39$\pm$0.22
& 78.36$\pm$0.15
& 72.71$\pm$0.22
& 85.11$\pm$0.14 \\
&
Ours (Mutual)
& 79.08$\pm$0.20
& \textbf{92.22$\pm$0.10}
& 64.74$\pm$0.22
& \textbf{81.29$\pm$0.14}
& \textbf{75.74$\pm$0.20}
& \textbf{91.58$\pm$0.09} \\ \midrule
\multirow{4}{*}{ResNet-12}
&
Baseline (ProtoNet)
& 81.02$\pm$0.20
& 91.93$\pm$0.11
& 73.81$\pm$0.21
& 87.39$\pm$0.12
& 85.46$\pm$0.19
& 95.08$\pm$0.08 \\
&
Ours (Q$\to$S)
& 83.72$\pm$0.19
& 93.31$\pm$0.09
& 76.50$\pm$0.21
& 87.95$\pm$0.12
& 87.37$\pm$0.17
& 95.10$\pm$0.08 \\
&
Ours (S$\to$Q)
& 81.72$\pm$0.19
& 90.83$\pm$0.11
& 75.62$\pm$0.22
& 86.47$\pm$0.13
& 85.90$\pm$0.18
& 93.17$\pm$0.10 \\
&
Ours (Mutual)
& \textbf{85.44$\pm$0.18}
& \textbf{94.73$\pm$0.09}
& \textbf{76.89$\pm$0.21}
& \textbf{88.27$\pm$0.12}
& \textbf{90.44$\pm$0.15}
& \textbf{97.49$\pm$0.05} \\ \bottomrule
\end{tabular}
\end{table*}
To validate the efficiency of our method for fine-grained few-shot image classification, we conducted experiments on the {three} fine-grained image classification datasets discussed earlier.
The results of Relation~\cite{8578229}, DN4~\cite{8953758} and BSNet~\cite{9293172} are from literature BSNet~\cite{9293172}, and the results of SAML~\cite{Hao2019CollectAS} and DeepEMD~\cite{Zhang_2020_CVPR} are from DLG~\cite{Cao2022AFF}, and the results of LRPABN~\cite{Huang2021LowRankPA} are from MattML~\cite{zhu2020multi}. The results of methods marked with $\dag$, such as ProtoNet~\cite{NIPS2017_cb8da676}, PARN~\cite{Wu_2019_ICCV}, CTX~\cite{NEURIPS2020_fa28c6cd}, FRN~\cite{Wertheimer_2021_CVPR}, FRN+TDM~\cite{lee2022task} and DeepEMD~\cite{Zhang_2020_CVPR} are obtained via the code officially provided by the author, which is replaced by the dataset used in this paper.
\begin{figure*}[ht]
\centering
\includegraphics[width=0.8\linewidth]{figures/5.pdf}
\caption{Recovered images of different features by our method for the CUB dataset. }
\label{fig:visualize}
\end{figure*}
We use Conv-4 and ResNet-12 as the backbone of all compared methods and test $5$-way $1$-shot and $5$-way $5$-shot classification performance.
As seen from Table~\ref{tab:1}, the proposed method achieves highest accuracy on all three datasets when the Conv-4 is adopted.
Apart from the result on the {Dogs}~\cite{KhoslaYaoJayadevaprakashFeiFei_FGVC2011} dataset where performance falls slightly behind the FRN+TDM method when the ResNet-12 is adopted, our method achieves highest accuracy.
In a nutshell, compared with other newly proposed methods, our method achieves stable and excellent performance on the three fine-grained image datasets on both $5$-way $1$-shot and $5$-way $5$-shot classification tasks, majorly owing to our network structure. The two modules FSRM and FMRM, conditions the model to learn the subtle and discriminative features for fine-grained classification.
\subsection{Ablation Study}\label{Ablation}
To further justify the design choices of our method and model components towards efficiency and accuracy, we perform a few ablation studies on three datasets using both Conv-4 and ResNet-12 as backbone networks.
\textbf{The Effectiveness of FSRM and FMRM:} We compare our method's efficacy by removing components in a strip-down fashion. In other words, we conduct experiments and report in Table~\ref{tab:3}, where we remove FSRM module (\textit{FMRM}), FMRM module (\textit{FSRM}), and then both which becomes equivalent to ProtoNet~\cite{NIPS2017_cb8da676} (\textit{Baseline (ProtoNet)}).
{Evidently, performance improves further in our method where both FSRM and FMRM are used together (\textit{FSRM+FMRM}). Therefore, FSRM and FMRM modules are indispensable and complementary.}
\textbf{The Effectiveness of Mutual Reconstruction in FMRM:}
For our method, we remove reconstruction of support samples based on query samples in FMRM, i.g., $\lambda_2$ becoming $0$ in Equation~\ref{equ:9}, which is marked as Ours ($Q \to S$). And we remove reconstruction of query samples based on support samples, i.g., $\lambda_1$ becoming $0$ in Equation~\ref{equ:9}, which is marked as Ours ($S\to Q$).
{As per Table~\ref{tab:4}, both unidirectional reconstruction methods score lower than the proposed feature mutual reconstruction method (FMRM) in most cases. Therefore, it can be concluded that the design of the Feature Mutual Reconstruction Module (FMRM) is reasonable and effective.}
\subsection{Visualization Analysis}
To demonstrate the efficiency of our proposed network better, we recovered the original and reconstructed features. We trained an inverse ResNet as a decoder, the input of which is the feature value in the mutual reconstruction module, and the output of which is a $3 \times 84 \times 84$ recovered image. In the training process, we use an Adam optimizer with an initial learning rate of $0.01$, set batch size as $200$ and train for $1,000$ epochs, with an L1 loss to measure the prediction error.
As per Figure ~\ref{fig:visualize}, the left-most block shows the support images of $5$ classes, each of which occupies one row and contains $5$ images. The right-most column is a query image, which we copied $5$ times simply for convenient comparison and aesthetics.
The second block from left is the recovered images of support features $S_c^V$, whereas second column from the right is the recovered images of the $i^\text{th}$ query features $Q_i^V$.
The third block from left is the recovered images of reconstructed support feature $\hat{S}_{(i,c)}$ based on $i^\text{th}$ query feature, while that from the right is the recovered images of reconstructed query features $\hat{Q}_{(c,i)}$ based on each $c$ class support feature.
From the first and second {blocks} (first being left-most), it can be seen that the decoder we trained is capable of recovering images from features. For the third {and fourth ones}, it can be seen that if a query sample is used to reconstruct the support samples which has same class as the query sample, the reconstructed features will be similar to the original support features. However if we use a query sample to reconstruct the support samples which has a class different from the query sample, the reconstructed features will be quite different from the original support features. Likewise, when we use support samples to reconstruct the query samples, similar results are obtained. This indicates that the proposed network can effectively alleviate inaccurate similarity measure of the unaligned fine-grained images.
\section{Conclusion}
\label{Conclusion}
In this paper, we proposed a bi-directional feature reconstruction network for few-shot fine-grained image classification. Our major contribution is a mutual reconstruction module that works in both directions, i.e., support to test and test to support. Compared to the existing reconstruction-based methods, the proposed method can achieve larger inter-class variations and lower the intra-class variations which is crucial to fine-grained learning.
Extensive experiments show that the proposed network can perform well on {three} fine-grained image datasets consistently, competing strongly and at times surpassing contemporary state-of-the-arts.
| {'timestamp': '2022-12-01T02:19:25', 'yymm': '2211', 'arxiv_id': '2211.17161', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17161'} | arxiv |
\section{Introduction}\label{sec:introduction}
Submodularity fundamentally captures a diminishing-return property of set function: the reward of adding an item into a set will decrease as this set grows. Submodular maximization aims at finding a subset of some ground set such that the submodular objective function can be maximized with some (or without any) constraints on cost or feasibility. Submodular function maximization appears in a wide variety of scenarios, from combinatorial optimization to machine learning, such as the coverage problem, facility location planning, information gathering, feature selection, data summarization, factorization in graphical models, and so forth~\citep{Krause-2012-submodular-surv,Wu-2018-submodular,Bilmes-2022-submodular-surv}.
In general, submodular maximization problems are NP-hard, regardless of whether they are constrained or not. A lot of approximation algorithms with guaranteed performance have been presented to maximize (1) unconstrained functions or (2) constrained-but-monotone functions.
So far, however, the \emph{constrained nonmonotone submodular maximization} has not been fairly well-understood.
Recently, a number of studies have tried to maximize nonmonotone submodular functions with additive or cardinality-based constraints, and presented algorithms with provable guarantees.
In practical settings, however, the constraints are often more complex, or even infeasible to evaluate in poly-time~\citep{Wu-2019-wpt-mobile,Amantidis-2019-submodular,Jakkala-2022-submodular-app,Durr-2020-submodular}. For instance, in the big-data system with networked processors, multiple processors are often selected to concurrently execute a computation task on their local datasets.
For timely applications, these selected processors are orchestrated as a delay-minimum multicast routing tree and expected to return to the user more representative results within a time threshold.
Another example of nonmonotone submodular maximization is to complete an informative data collection with an energy-budgeted robot, which passes through a TSP route on some points of interest to collect data.
The two examples will be detailed in section \ref{sub:problem}. Their objective functions are usually nonmonotone submodular, and evaluating their cost constraints is generally NP-Hard, more complex than evaluating additive or cardinality-based constraints.
In this paper, our goal is to maximize nonmonotone submodular function with the constraints that need to be evaluated by some route planning.
To the best of our knowledge, no literature has investigated such a submodular-maximization setting constrained by a routing budget.
Part of our problem's difficulty stems from its submodularity, but a great deal more of the difficulty is attributed to its computationally-intractable routing constraints, which hinder the development of constant-factor approximate solution.
In response to this issue, we present an iterated two-stage algorithm framework, which uses any $(1+\theta)$-approximation algorithm to evaluate the routing constraint within polynomial time. We elaborately draw a connection between the error parameter $\theta$ and the iteration's termination condition. Additionally, by exploring the routing cost function, we find it belongs to a kind of $k$-independence system, where $k$ is bounded by the ground set's size and usually a positive constant in practical settings. This observation offers our algorithm a lower-bound performance guarantee. Based on all the above, we develop the proof machinery that proves our algorithm can achieve a $[1/4k, 1+\theta]$-bicriterion approximation solution, that is, our objective value is at least as good as $1/4k$ of the optimal one, while the ratio of over-budget is upper bounded by $\theta$ (which is usually less than one or can be any small in some cases).
The remainder of this paper is organized as follows. Section \ref{sec:RelatedWork} discusses the related works. Section \ref{sec:ModelProblem} gives the necessary preliminaries and formulates our problem. Section \ref{sec:Designs} details the designs of our algorithm and analyze its performance bound. Section \ref{sec:Experiment} numerically evaluates our designs with two case studies. Finally, section \ref{sec:Conclustion} concludes this paper.
\section{Related Work}\label{sec:RelatedWork}
Submodular function maximization subsumes a wide range of NP-Hard combinatorial optimization problems, and then, has long been studied~\cite{Krause-2012-submodular-surv}. The unconstrained submodular maximization is NP-hard but well-approximable. For the unconstrained settings, if the objective function is nonnegative and monotone, the greedy policy that simply selects the item with the highest marginal profit can achieve a poly-time, $(1-1/e)$-approximation solution. In practice, maximizing submodular function is usually restricted by some feasibility or cost constraints. In this section, therefore, we will only give a brief introduction to some main studies on the constrained submodular maximization and their results, some of which are listed in Table \ref{tab:ratios}.
\begin{table}[t]
\renewcommand\arraystretch{1.15}
\centering
\caption{Main results of submodular maximization}\label{tab:ratios}
\small
\begin{tabularx}{\linewidth}{lcrX}\toprule
paper (year) & \thead{objective function} & \thead{constraint class} & \thead{approximation ratio} \\ \midrule
\cite{Nemhauser-1978-submodular} (1978) & monotone & cardinality & $1-1/e\approx 0.632$ \\
\citep{Krause-2005-submodular} (2005) & monotone & cardinality & randomized algo.: $1-1/e-\varepsilon$, $\varepsilon>0$ is any small \\
\citep{Sviridenko-2004-submodular} (2004) & monotone & 1-knapsack & $1-1/e$ \\
\citep{Calinescu-2011-submodular-matroid} (2011) & monotone & $1$-matroid & $1-1/e$ \\
\citep{Badanidiyuru-2014-submodular} (2014) & monotone & $k$-system $l$-knapsack & $1/(k+2l+1+\varepsilon)$, $\varepsilon>0$ determines time complexity \\
\citep{Zhang-2016-submodular-rt} (2016) & monotone & $\alpha$-submodular, routing & $[\frac{1}{2}(1-1/e), p(\alpha, k_c,\psi)]$, bi-criterion \\
\citep{Wu-2019-wpt-mobile} (2019) & monotone & TSP routing & $[\frac{1}{4}(1-1/e), p(\alpha, k_c,\psi)]$, bi-criterion \\
\citep{Buchbinder-2012-nonmonotone-submodular} (2012) & nonmonotone & -- & deterministic algo.: 1/2; randomized algo.: 2/5\\
\citep{Feldman-2011-submodular-matroid} (2011) & nonmonotone & 1-matroid & $1/e\approx 0.368$ \\
\citep{Buchbinder-2014-nonmonotone-submodular} (2014) & nonmonotone & cardinality & $1/e+0.004\sim 1/2$ \\
\citep{Lee-2009-submodular} (2009) & nonmonotone & $k$-matroid & $\frac{1}{k+2+1/k+\epsilon}$, $\epsilon>0$ is any small \\
\citep{AAGK-2010-nonsubmodular} (2010) & nonmonotone & $k$-system & $\frac{k}{(1+1/\alpha)(k+1)^2}\approx \frac{1}{(1+1/\alpha)k}$, $0<\alpha<1$ \\
\citep{Mirzasoleiman-2016-submodular} (2016) & nonmonotone & $k$-system & $\frac{k}{(k+1)(2k+1)}\approx\frac{1}{2k}$ \\
\citep{Feldman-2017-nonmonotone-submodular} (2017) & nonmonotone & $k$-system, $k$-extendible & $\frac{1}{k+\mathcal{O}(\sqrt{k})}$ \\
\citep{Shi-2020-submodular-psystem} (2020) & nonmonotone & $k$-system & $\frac{1}{2k+3+1/k}$ \\
\citep{Tang-2022-submodular} (2022) & nonmonotone & $k$-system & randomized algo.: $\frac{1}{2k+4}$ for adaptive submodularity\\
\bottomrule
\end{tabularx}
\end{table}
\subsection{Monotone Submodular Maximization}
In literature, most of efforts are put on maximizing monotone submodular functions with various types of constraints, and constant-factor approximation algorithms are presented.
\textbf{Cardinality Constraint}. \citet{Nemhauser-1978-submodular} first give the near-optimal solution for the cardinality setting, with an approximation ratio of $(1-1/e)$.
\citet{Krause-2005-submodular} give a randomized algorithm to achieve $(1-1/e+\varepsilon)$-approximation with high probability (here $\varepsilon>0$ can be any small).
\citet{Balkanski-2018-submodular} study the adaptive complexity of maximizing a submodular function with a cardinality constraint, and prove that there exists $\mathcal{O}(\log n)$-adaptive algorithm to achieve a $(1/3-\varepsilon)$-approximation for any small $\varepsilon>0$.
In \cite{Breuer-2020-submodular-cardi}, the authors introduce a parallel algorithm, and the performance is arbitrarily close to $(1-1/e)$.
\textbf{Matroid or Knapsack Constraint}. \citet{Calinescu-2011-submodular-matroid} give a $(1-1/e)$-approximation algorithm for monotone submodular maximization subject to a general matroid constraint.
For the settings with $k$-matroid constraints, \citet{Nemhauser-1978-submodular} proposes a $1/(k+1)$-approximation algorithm.
\citet{Badanidiyuru-2014-submodular} use the continuous greedy policy to design a $1/(k+2l+1+\varepsilon)$-approximation for the intersection of a $k$-system and linear $l$-knapsack constraints.
\textbf{More Complex Constraint}. A more recent work~\cite{Zhang-2016-submodular-rt} considers the monotone submodular maximization with an $\alpha$-submodular constraint (such as routing constraint), where evaluating the constraint is assumed to be NP-hard. The authors give a bi-criterion algorithm (i.e., their solution is bounded in performance, though it will to some extent disagree with the original constraint), with an approximation ratio of $(1-1/e)/2$; the constraint violence is bounded by a polynomial $p(\alpha, k_c, \psi)$, where $k_c$ is the curvature of the constraint function and $\psi$, the approximation ratio of the algorithm used to evaluate the constraint.
\citet{Wu-2019-wpt-mobile} model their wireless charging scheduling problem as a monotone submodular maximization problem restricted by TSP routing; they replace their objective function with a surrogate function and propose a $(1-1/e)/4$-approximation bi-criterion algorithm.
Nevertheless, these two studies' objective functions are monotone, and their analytical machinery cannot be applied to nonmonotone cases at all.
\subsection{nonmonotone Submodular Maximization}
Maximizing nonmonotone submodular functions is generally more difficult and usually investigated in the cases without any constraints, or just with cardinality, convex-set, or packing-type constraints.
For the unconstrained nonmonotone cases, \citet{Buchbinder-2012-nonmonotone-submodular} propose a local search-based exact algorithm and a randomized algorithm, both of which can achieve approximation ratios of $1/2$ and $2/5$, respectively.
\textbf{Cardinality Constraint}. \citet{Buchbinder-2014-nonmonotone-submodular} present an algorithm with constant factor ranging from $(1/e + 0.004)$ to 1/2, and a 0.356-approximation algorithm under an exact cardinality constraint.
\citet{Wang-submodular-partition} investigate the submodular partitioning problem with cardinality constraint, which divides a ground set into $m$ blocks to maximize the evaluation of the minimum block under constraints. They propose a greedy-based algorithmic framework to achieve an $\Omega(1/m)$-approximation.
\textbf{Matroid or Knapsack Constraint}. In the case with a single matroid constraint, \citet{Feldman-2011-submodular-matroid} design a $1/e$-approximation greedy algorithm.
\citet{Lee-2009-submodular} give the first constant-factor results for nonmonotone settings under $k$-matroid or $k$-knapsack constraints; the approximation ratios are $1/(k+2+1/k+\epsilon)$ and $(0.2-\epsilon)$ for the $k$-matroid and $k$-knapsack cases, respectively, where $\epsilon>0$ is any small.
\textbf{$k$-independence System Constraint}. \citet{AAGK-2010-nonsubmodular} investigate the algorithmic framework of nonmonotone submodular maximization constrained by a $k$-independence system ($k$-system, in short), which is a generalization of intersection of $k$ matroids. Their algorithm achieves an approximation ratio of $k/[(1+1/\alpha)(k+1)^2]\approx 1/[(1+1/\alpha)k]$, where $0<\alpha<1$ is the approximation guarantee for unconstrained nonmonotone submodular maximization. This result has remained competitive until now, and has motivated a number of studies focusing on the nonmonotone settings with $k$-system constraint.
\citet{Mirzasoleiman-2016-submodular} follow the above algorithm and slightly reduce the above approximation ratio down to $k/[(k+1)(2k+1)]$.
Also adopting the iterative algorithmic framework of~\cite{AAGK-2010-nonsubmodular}, \citet{Feldman-2017-nonmonotone-submodular} propose a deterministic algorithm that achieves an approximation ratio of $1/[k+\mathcal{O}(\sqrt{k})]$, and furthermore, they propose a randomized $k/(k+1)^2$-approximation algorithm for the nonmonotone settings with $k$-extensible constraint.
\citet{Shi-2020-submodular-psystem} extend the approach in \cite{Lee-2009-submodular} to make it suitable to the $k$-system constraint, and present an algorithm with the factor of $1/(2k+3+1/k)$; the authors also show that, if $k<8$, their algorithm will outperform that of \cite{Feldman-2017-nonmonotone-submodular}.
\citet{Tang-2022-submodular} proposes a sampling-based randomized algorithm for maximizing the $k$-system-constrained nonmonotone adaptive submodular function, and this algorithm achieves an approximation ratio of $1/(2k+4)$.
To date, the algorithms for nonmonotone submodular maximization under $k$-system have almost followed the seminal framework proposed in~\cite{AAGK-2010-nonsubmodular}. All these algorithms are $\frac{1}{\Omega(k)}$-approximation, merely with slightly-different time complexities.
In particular, their constraint functions are assumed to be computationally tractable. However,
it is not always true; for instance, evaluating routing restriction is generally NP-Hard.
Until now, there have not been any algorithmic frameworks and analytical machinery that can achieve a constant-factor or bi-criterion approximation for the nonmonotone submodular maximization with an intractable routing constraint.
\section{Preliminaries and Problem Statement}\label{sec:ModelProblem}
In this section, we first introduce some preliminaries as well as notations, and then, formalize our problem along with two motivating examples. Finally we analyze the intractability of our problem.
\subsection{Submodular Maximization}
Given the ground set $\Omega$ of $n$ items, we say that a utility function $f: 2^\Omega\rightarrow\mathbf{R}$ is a \emph{submodular set function} if and only if we have
\begin{equation}\label{eqn:submodularity1}
f(A\cup B) + f(A\cap B) \leq f(A) + f(B)
\end{equation}
\noindent for any $A\subseteq\Omega$ and $B\subseteq\Omega$~\cite{Fujishige-2005-submodular-bk}. Commonly, $f$ is nonnegative and $f(\emptyset)=0$. The submodularity of $f$ can be equivalently expressed with
\begin{equation}\label{eqn:submodularity2}
f(A\cup\{x\}) - f(A) \geq f(B\cup\{x\}) - f(B)
\end{equation}
\noindent for any $A\subseteq B\subset \Omega$ and $x\in \Omega\backslash B$. Submodular function $f(A)$ has a diminishing marginal gain as $A$ grows. We hereafter use $f^+_A(x) \triangleq f(A\cup\{x\}) - f(A)$ to denote the marginal gain of $f$ on $x\in\Omega$ with respect to $A\subset\Omega$, unless otherwise noted.
A submodular function $f$ defined on $2^\Omega$ is monotone if for all $A\subseteq B\subseteq \Omega$, we always have $f(A)\leq f(B)$ or a nonnegative marginal gain.
In a nonmonotone submodular case, however, $f^+_A(x)$ could be negative.
A constrained submodular maximization problem can be defined by $\max\{f(S)|g(S)\leq c,\,S\subseteq\Omega\}$, where $f$ is the objective function, and $g$, the cost function. In practice, cost functions are usually positive and monotone increasing.
\subsection{Routing-based Cost Function}
Given a ground set $\Omega$ of items, a weighted graph abstraction can be drawn over $\Omega$---the graph vertices are the items, and an edge exists between two items if both of them have a connection in some way. In such a graph, vertices (items) and edges are all associated with positive weights to represent the costs of visiting vertices and passing through edges.
With a nonnegative function $\rho: 2^\Omega\rightarrow\bf{R}_{\geq 0}$ and any $S\subseteq\Omega$, if $\rho(S)$ is mapped to the least total cost of the route that visits all the vertices of $S$ in some way, we say $\rho$ is a \emph{routing-based cost function}.
More specifically, the routing-based cost function on $S$ can be commonly written as $\rho(S)=\sum_{s\in S}c_s+r^*(S)$, where $c_s\geq 0$ is the cost in visiting $s$ and $r^*(S)$ is the minimum cost of traversing each vertex of $S$ at least once. In general, $r^*(S)$ is infeasible to compute within poly-time; clearly, it is the $r^*(S)$ term that results in the NP-hardness of determining $\rho(S)$.
To simplify notation, we also use $\rho$ to represent the optimal algorithm of achieving the least cost. In most real-life applications, we have $\rho(T)\leq\rho(S)$ for $T\subseteq S$, i.e., $\rho$ is nondecreasing. Specifically, it is easy to prove that for any $S, T\subseteq\Omega$ with $S=T\cup\{s\}$, we have $\rho(S)-\rho(T)\geq \cmin$ where $\cmin=\min\{c_s|s\in\Omega\}$, i.e., the gradient of function $\rho$ is at least $\cmin$. In this paper we assume $\rho(\emptyset)=0$ and $\rho$ is nondecreasing.
\subsection{Problem Definition and Examples}\label{sub:problem}
Given a nonempty ground set $\Omega$ and a nonmonotone submodular set function $f: 2^\Omega\rightarrow\mathbf{R}_{\geq 0}$, we aim at finding a subset $S^*\subseteq\Omega$ such that
\begin{equation}
S^* = \arg\max\limits_{S\subseteq\Omega}\{f(S)~|~\rho(S)\leq\bf{c}\}\,,
\end{equation}
\noindent where $\rho(S)$ is a routing-based cost function defined on $2^\Omega$ and $\bf{c}$ is the budget (a positive constant). Here, $\rho(\cdot)\leq\bf{c}$ is a \emph{routing constraint} to the objective function $f(\cdot)$. We assume that $\rho(\{s\})\leq\bgt$ for any singleton $s\in\Omega$.
Followed are two motivating examples of our problem.
\textbf{Example-1: Diversified Task Offloading in Big Data}. Big Data system is a networked distributed computing environment, in which each processor can store and process data, and processors are connected with delaying links. To effectively complete a computation task within a given time, users usually offload the task down to a subset of processors whose data is more representative. These selected processors can, in parallel, run the task on their local data sets, and return results to users for further combination.
In machine learning~\cite{Lin-2011-diversity,Mirzasoleiman-2016-submodular,Mirzasoleiman-2018-nonmonotone-submodular-app}, the functions of evaluating data representativeness are commonly nonmonotone and submodular (see Appendix \ref{appdxB:similarity}).
The user can calculate (foreknow) the time of each processor running a task before offloading it. Given a subset of processors, therefore, the completion time heavily depends on how long the in-network data transfer will take. Equivalently, what the user needs is find a delay-minimum multicast routing tree that is rooted at the user and spans all the selected processors, which is an NP-Complete task in general. Obviously, this example can be modeled as a nonmonotone submodular maximization with a multicast routing restriction.
\textbf{Example-2: Informative Data Collection with a Robot}. In this example, an on-ground or aerial robot departs from a depot and moves through some points of interest (already specified in a certain monitoring area) to capture data. The robot's objective is collect as informative data as possible, while not running out of its energy before returning to the depot. This scenario often falls into the category of informative path planning in robotics or social networks. The robot cannot visit all points due to its limited energy capacity. It has to select an informative subset of points, and visit them along a TSP tour that starts and ends at the depot. In real-life applications~\cite{Sharma-2015-entropy,Bachman-2019-mi,Tschannen-2020-representation}, ``informative'' can be measured with the mutual information between the visited and unvisited points; and mutual information is of nonmonotone submodularity. So, this example can be naturally modeled as a nonmonotone submodular maximization with TSP constraint.
\subsection{Hardness of Our Problem}
The computational intractability of our problem stems from three aspects. First, even if we ignore the constraint on our problem (for example, $\bf{c}$ is very large), maximizing a (nonmonotone) submodular function remains NP-hard. It is quite straightforward to know that our problem is NP-hard, too. Second, for a given subset of $\Omega$, we need to evaluate its feasibility by solving the routing-based cost function that is NP-hard in general settings. Third, our problem's objective function and constraint evaluation cannot be solved separately, because each is coupled with the other.
There have been lots of efforts to optimize monotone and nonmonotone submodular functions without constraints. In the past few years, there has been a surge of interest in applying constrained submodular maximization to machine learning. But most of these prior works usually focus on the maximization with computationally tractable constraints, such as cardinality, knapsack, and matroid constraints~\cite{Lee-2009-submodular,Iyer-2013-submodular,Buchbinder-2014-nonmonotone-submodular}. They, however, cannot be directly applied to our problem to achieve bounded performance.
\section{Our Algorithm}\label{sec:Designs}
In the seminal work~\cite{AAGK-2010-nonsubmodular}, the authors propose an iterative greedy algorithm (called SMS, for convenience) to maximize nonmonotone submodular function with $k$-system constraints. SMS can provide an approximation ratio of $\frac{k}{(1+1/\alpha)(k+1)^2}\approx\frac{1}{(1+1/\alpha)k}$, which remains competitive for general settings until now. Here, parameter $\alpha~(0<\alpha<1)$ is the approximation guarantee for unconstrained nonmonotone submodular maximization.
Each iteration of SMS covers two stages: (1) selecting as many items from available ones as possible, until the $k$-system property cannot hold, and (2) applying an unconstrained nonmonotone submodular maximization algorithm to those selected items. SMS repeats the two stages $k$ times. During iterations, it stores all the feasible solutions determined by the second stage, and the best one will be returned at last.
Our algorithm follows the algorithmic framework of SMS, and it can achieve at least the same performance as SMS's, while only needing polynomial time cost. Our basic idea is as follows. First, we prove the routing constraint on our problem is a kind of $k$-system, which transforms our problem into a $k$-system-constrained nonmonotone submodular maximization problem. This enables SMS's approximation ratio to work for our algorithm. Second, we recruit an algorithm $\rf$ to approximate $\rho$ in evaluating the routing cost, such that our algorithm can terminate in poly-time with an over-budget. Third, we prove that the amount of over-budget is bounded, by analyzing the performance gap in cost evaluation between $\rf$ and $\rho$.
\subsection{Algorithm Description}
Our algorithm is outlined in Algorithm \ref{algo}, and it is an iterative procedure. Each iteration includes two stages which are described below in detail.
\let\oldnl\nl
\newcommand{\renewcommand{\nl}{\let\nl\oldnl}}{\renewcommand{\nl}{\let\nl\oldnl}}
\SetAlgorithmName{Algorithm}{}{}
\begin{algorithm}
\caption{our algorithm}\label{algo}
\DontPrintSemicolon
\SetKwInOut{Input}{input}\SetKwInOut{Output}{output}
\SetKwFor{While}{while}{}{end}
\SetKwFor{For}{for}{}{end}
\Input{$\Omega$, $\bf{c}$, $k$, $\theta$, $\alpha$}
\Output{$T^*\subseteq\Omega$ and $f(T^*)$}
\BlankLine
$S_1\leftarrow\Omega$ and $\mathcal{T}\leftarrow\emptyset$ {~~{\tcp*[h]{two sets}}}\;
\For{$i=1$ \emph{up to} $k$}{ \label{algoline:forloop}
$X_i \leftarrow \emptyset$ and $Y_i\leftarrow \emptyset$ {~~{\tcp*[h]{two sequences}}}\;
{\renewcommand{\nl}{\let\nl\oldnl} {\color{blue}{$\triangleright$ Stage 1: add as many items as possible}} }\;
\While{$S_i\neq\emptyset$}{ \label{algoline:whileloop}
$s^* \leftarrow\arg\max\{f^+_{X_i}(s)|s\in S_i\}$ \label{algo:cherryPick}\;
\eIf{$s^*$~\emph{exists and}~$\rf(X_i+s^*)\leq(1+\theta)\bgt$}{\label{algo:rtEvaluation}
$X_i \leftarrow X_i+s^*$ and $S_i\leftarrow S_i\backslash s^*$ \;
\If{$\rf(X_i)>\bgt$}{\label{algo:beyondBudget}
$Y_i\leftarrow Y_i + s^*$ \; \label{algo:Y}
}
}{
break the while-loop (line \ref{algoline:whileloop})\;
}
}
\BlankLine
{\renewcommand{\nl}{\let\nl\oldnl} {\color{blue}{$\triangleright$ Stage 2: find the best from a set of local optima}} }\;
\eIf{$X_i\neq\emptyset$}{
$T^*_i \leftarrow \unst(X_i)$ \label{algo:xISopt}\;
\While{$y\leftarrow$~\emph{the last item of}~$Y_i$~\emph{exists}}{\label{algo:last}
$X_i\leftarrow X_i\backslash y$ and $Y_i\leftarrow Y_i\backslash y$ \label{algo:curtailXi1}\;
$T_y \leftarrow \unst(X_i)$ and $\mathcal{T}\leftarrow\mathcal{T}\cup\{T_y\}$ \label{algo:curtailXi2}\;
}
$\mathcal{T}\leftarrow\mathcal{T}\cup\{T^*_i\}$ \;
}{
break the for-loop (line \ref{algoline:forloop})\;
}
$S_{i+1} \leftarrow S_i$ {~~{\tcp*[h]{the $i$-th iteration stops here}}}\;
}
\Return $f(T^*)=\max\{f(T)|T\in\mathcal{T}\}$ and $T^*$\;
\end{algorithm}
\subsubsection{Stage-1: Maximization with Constraint Relaxed}
In the $i$-th iteration, the items, yet unexamined so far, form the set $S_i$. Stage-1 uses the {\tt whileloop}\xspace iteratively to examine all the items of $S_i$, picking out $s^*$, the item bringing the highest marginal gain. During the cherry-picking, our algorithm uses a $(1+\theta)$-approximation poly-time algorithm $\rf$ in place of optimal algorithm $\rho$ to verify whether the routing cost is under constraint, where $\theta$ is usually within $(0,1)$.
In the {\tt whileloop}\xspace, the constraint is relaxed from $\bgt$ to $(1+\theta)\bgt$, and the {\tt whileloop}\xspace continues until the routing cost evaluated by $\rf$ is beyond $(1+\theta)\bf{c}$. If the cost stays under the relaxed budget, $s^*$ will be moved from $S_i$ into the rear of $X_i$, which is an ordered set or a sequence; otherwise, the {\tt whileloop}\xspace breaks and then, Stage-1 is over in current iteration and outputs $X_i$ and $Y_i$. As shown on lines \ref{algo:beyondBudget} and \ref {algo:Y}, $Y_i$ is also a sequence and only stores the items that are examined after original budget $\bgt$ is violated.
The {\tt whileloop}\xspace tries to maximize $f$ with its original constraint slightly relaxed, and therefore, $\rf(X_i)$ output by Stage-1 may be larger than $\bgt$. But the over-budget can remain under $\theta\cdot\bgt$.
\subsubsection{Stage-2: Maximization without Constraints}
Once Stage-1 stops with $X_i\neq\emptyset$ as output, Stage-2 is prompt to take over the unfinished task.
Stage-2 tries to employ the \unst procedure to dig out a more profitable subset out of $X_i$. Here, \unst can be any solvers that maximize a general unconstrained nonmonotone submodular function, with a bounded approximation ratio $\alpha$ ($0<\alpha<1$). In this paper, \unst is fulfilled by the deterministic algorithm proposed in \cite{Buchbinder-2012-nonmonotone-submodular}, which can use $\mathcal{O}(n)$ value oracles to achieve $1/3$-approximation for unconstrained submodular maximization. Appendix \ref{appdxA:deterministicUSM} shows this concrete \unst.
Stage-2 first uses \unst to pick out $T^*_i$ from $X_i$. However, $T^*_i$ is not necessarily the best because of $f$'s non-monotonicity.
As shown on lines \ref{algo:curtailXi1} and \ref{algo:curtailXi2}, therefore, Stage-2 continues to curtail $X_i$ until $X_i\backslash Y_i$ is reached, and in the meantime, it repeatedly recruits \unst to explore for the solution $T_y$ that is possibly better than $T^*_i$.
After the {\tt forloop}\xspace completes at $i=k$ or $X_i=\emptyset$, our algorithm will immediately scan through all the routes in $\mathcal{T}$ and then return the ultimate winner and its objective value.
The {\tt forloop}\xspace goes ahead as $i$ increases from 1 to $k$. Here, $k$ is an integer constant, loosely upper-bounded by $|\Omega|-1$, and it will be discussed later in section \ref{subsec:timeComplexity}.
\subsection{Theoretical Performance}\label{subsec:approx}
Given a set function $f: 2^\Omega\rightarrow\mathbf{R}_{\geq 0}$, we say $(\Omega, \mathcal{I}\subseteq 2^\Omega)$ is an \emph{independence system} if the following two properties are satisfied: I (non-emptiness) $\emptyset\in\mathcal{I}$, i.e., $\mathcal{I}$ is not empty per se, and II (heredity) if $S_1\in\mathcal{I}$ and $S_2\subset S_1$, then $S_2\in\mathcal{I}$.
The heredity of independence system makes $\dsys$ be exponential in size in worst case, and therefore, the optimization via exhaustive search over $\dsys$ is infeasible in terms of computation.
Given $S\subseteq\Omega$ and $S_1\subseteq S$, we say $S_1$ is a {\it base} of $S$, if $S_1\in\dsys$ and we cannot find other $S_2\in \dsys$ such that $S_1\subseteq S_2\subseteq S$.
An independence system $(\Omega, \dsys)$ is called a $k$-{\it independence system} ($k$-{\it system}, in short), if and only if there exists an integer $k$ such that ${|B_1|}/{|B_2|}\leq k$ for any two bases, $B_1$ and $B_2$, of $\Omega$. As a special case, a matroid is a 1-independence system.
\begin{theorem}\label{thr:kSystem}
\emph{
Let $\dsys_\rho=\{S|S\subseteq\Omega~\mbox{and}~\rho(S) \leq \bf{c}\}$ and
$\dsys_\rf=\{S|S\subseteq\Omega~\mbox{and}~\rf(S)\leq (1+\theta)\mathbf{c}~
\mbox{with}~\theta>0\}$. Both $(\Omega, \dsys_\rho)$ and $(\Omega, \dsys_\rf)$
are a kind of $k$-system.
}
\end{theorem}
\begin{proof}
We first prove that $\dsys_\rho$ is an independence system. Since $\emptyset\subset\Omega$ and $\rho(\emptyset)=0$, we have $\emptyset\in\dsys_\rho$. Consider $S\in\dsys_\rho$ and a subset $T\subset S$. We know $\rho(T)<\rho(S)\leq\mathbf{c}$, which means $T\in\dsys_\rho$. Thus $(\Omega, \dsys_\rho)$ is an independence system.
For any item $s\in\Omega$, we have assumed $\rho(\{s\})\leq\bgt$, indicating that each base of $\dsys_\rho$ is not less than one in size. On the other hand, it is easy to prove, by contradiction, that if $\Omega$ has a base of size $n$, then all its bases are of size $n$.
That said, there must exist an integer $k_\rho$ ($1\leq k_\rho<n$) such that ${|B_1|}/{|B_2|}\leq k$ for any two bases, $B_1$ and $B_2$, of $\Omega$. Hence $\dsys_\rho$ is a $k_\rho$-system.
Applying similar analysis to $(\Omega, \dsys_\rf)$, we can conclude that there exists an integer $k_\rf$ ($1\leq k_\rf<n$) such that $(\Omega, \dsys_\rf)$ is a $k_\rf$-system.
\end{proof}
Theorem \ref{thr:kSystem} implies that our problem is also a nonmonotone submodular maximization problem with $k$-system constraint. That said, SMS's approximation ratio is hopefully true for our algorithm.
However, SMS requires that its $k$-system cost function be exactly evaluated or solved. Such a requirement cannot be satisfied in our setting, because our cost function is more complex and generally intractable. In exchange for polynomial computation complexity, our algorithm replaces $\rho$ with $\rf$.
Recall that $\rf$ is a $(1+\theta)$-approximation to $\rho$. Now, the crux of analyzing our algorithm's competitiveness is to profile how differently Stage-1 will perform when it uses $\rf$ under a relaxed budget and $\rho$ under the original budget.
Without loss of generality, we focus on Stage-1 of the $i$-th iteration of our algorithm. Suppose that we can, in parallel, run $\rho$ and $\rf$ in the cost evaluation (line \ref{algo:rtEvaluation} of Algorithm \ref{algo}), with $\bf{c}$ and $(1+\theta)\bf{c}$ as their budgets, respectively. For convenience, Stage-1's {\tt whileloop}\xspace is called $\rho$-{\tt whileloop}\xspace if $\rho$ is used in cost evaluation, and it is called $\rf$-{\tt whileloop}\xspace if $\rf$ is used.
\begin{theorem}\label{thr:stop1}
\emph{
Given $S_i$ at the beginning of Stage-1, assume the $\rf$-{\tt whileloop}\xspace stops with $X_i^\rf\subseteq S_i$. If $\rho$-{\tt whileloop}\xspace can stop with $X_i^\rho\subseteq S_i$, then we always have $X_i^\rho\subseteq X_i^\rf$ for any $\theta>0$.
}
\end{theorem}
\begin{proof}
In line \ref{algo:cherryPick} of our algorithm, picking $s^*$ (i.e., the item with the highest marginal gain) out of $S_i$ has nothing to do with the solver used by the cost evaluation (line \ref{algo:rtEvaluation}). Without considering the routing constraint, the sequence of best vertices chosen in the {\tt whileloop}\xspace would be always the same. We denote this sequence by $\langle s_{1}, s_{2},\cdots s_{m}\rangle$, where $m=|S_i|$ and $s_{j}$ is picked ahead of $s_{k}$ if $j<k$.
Consider a general case: $\rf$-{\tt whileloop}\xspace stops at $s_{k}~(k< m)$, while returning a route of cost $\rf_k$. As shown in Fig. \ref{fig:stopCondition}, in such a case, we have $\rf_{k}\leq (1+\theta)\bgt$~but~$\rf_{k+1}> (1+\theta)\bgt$.
Now suppose that optimal solver $\rho$ can stop at $s_{k+1}$ with the best route of cost $\rho_{k+1}$, meaning $\rho_{k+1}\leq\bgt$.
Since $\rf$ approximates $\rho$ with a factor of $(1+\theta)$, we readily have
\begin{equation}\label{eqn:contradiction1}
(1+\theta)\rho_{k+1}\geq \rf_{k+1} > (1+\theta)\bgt\,,
\end{equation}
\noindent which means $\rho_{k+1}>\bgt$. That contradicts. Hence, $\rho$ cannot stop at $s_{k+1}$ under budget $\bgt$, if $\rf$ stops at $s_{k}$ under budget $(1+\theta)\bgt$. Clearly, $\rho$ cannot stop at any $s_j$ for $k+2\leq j\leq m$, too. We thus have $X_i^\rho\subseteq X_i^\rf\subseteq S_i$ for any $\theta>0$.
\end{proof}
\begin{figure}\centering
\includegraphics[width=.6\textwidth]{figures/fig-stopCondition.pdf}
\caption{Demo of our algorithm's Stage-1 selecting $X_i^\rf$ out of $S_i=\{s_1, s_2\ldots s_m\}$, where $j<k\leq m$.}
\label{fig:stopCondition}
\end{figure}
Theorem \ref{thr:stop1} shows that, in Stage-1, $\rho$ cannot pick more items out of $S_i$ under the budget of $\bgt$ than $\rf$ does under the budget of $(1+\theta)\bgt$.
\begin{theorem}\label{thr:feasibleSolution}
\emph{
Given $S_i$ at the beginning of Stage-1, if $\rho$-{\tt whileloop}\xspace stops with $X_i^\rho$, then our algorithm must be able to meet $X_i^\rho$ in the subsequent Stage-2, and determine a subset of $X_i^\rho$ as a candidate solution.
}
\end{theorem}
\begin{proof}
We resort to Fig. \ref{fig:stopCondition} to finish this proof. Assume that the $\rf$-{\tt whileloop}\xspace stops in Stage-1 with $X_i^\rf$ and $Y_i^\rf$, and that $\rf_j\leq\bgt$ but $\rf_{j+1}>\bgt$. This means $Y_i^\rf=\langle s_{j+1}, s_{j+2}\ldots s_k\rangle$, according to our algorithm's lines \ref{algo:beyondBudget} and \ref{algo:Y}.
Since $\rf$ approximates $\rho$ and $\rf_{j}\leq\bgt$, we have $\rho_j\leq\bgt$, i.e., that $\rho$ will not stop earlier than meeting item $j$. Additionally, we know $X_i^\rho\subseteq X_i^\rf$ by Theorem \ref{thr:stop1}. Thus $\rho$ must stop at some item of $\{s_j\}\cup Y_i^\rf$.
If $X_i^\rho = X_i^\rf$, obviously, our algorithm can meet $X_i^\rho$ on Stage-2's line \ref{algo:xISopt}.
Moreover, in Stage-2's line \ref{algo:last}, we continue to shrink $X_i^\rf$~(i.e., $X_i$), by deleting its last item, until $X_i^\rf\backslash Y_i^\rf$ is hit. During such a shrinking process, we apply \unst to each of the intermediate subsets. Clearly, $X_i^\rho$ is either among these subsets, or equiverlant to $X_i^\rf$, i.e.,
our algorithm cannot miss $X_i^\rho$.
\end{proof}
Theorem \ref{thr:stop1} and Theorem \ref{thr:feasibleSolution} have paved the way to prove our algorithm's bicriterion competitiveness.
Next we introduce the formal definition of \emph{bicriterion approximation} as follows.
For a problem of $\max\{f(X)|g(X)\leq c\}$, a $(p, q)$-bicriterion approximation algorithm can output a solution $X$ that guarantees $f(X)\geq p\cdot f(X^{\rm opt})$ and $g(X)\leq q\cdot c$, where $X^{\rm opt}$ is an optimal solution, $0<p<1$ and $q>1$. These two parameters $p$ and $q$ approximately measure the optimality and the feasibility of approximation algorithm, respectively.
\begin{theorem}\label{thr:competitive}
\emph{
Using a $(1+\theta)$-approximation algorithm $\rf$ to evaluate the cost constraint under budget $(1+\theta)\bgt$, our algorithm can at least achieve a $\left[\frac{k}{4(k+1)^2}, 1+\theta\right]$-bicriterion approximation.
}
\end{theorem}
\begin{proof}
In each iteration's Stage-1, our algorithm always stops adding items when its budget is violated. So, any routes in $\mathcal{T}$ are not beyond $(1+\theta)\bgt$ in total cost; in other words, the over-budget amount of our solution is at most $\theta\cdot\bgt$.
Theorem \ref{thr:feasibleSolution} ensures that our algorithm with $\rf$ in cost evaluation can still achieve an approximation ratio that is at least as good as SMS's $\frac{k}{(1+1/\alpha)(k+1)^2}$.
Our algorithm's Stage-2 invokes the \unst procedure, whose approximation ratio is $0<\alpha<1$. It is proven in \cite{Buchbinder-2012-nonmonotone-submodular} that, for general unconstrained submodular maximization problems, there exist a deterministic and a randomized algorithms (i.e., \unst), which both need linear time and can achieve $1/3$-approximation and $1/2$-approximation (in expectation), respectively. If taking $\alpha=1/3$, our algorithm can achieve an approximation ratio of at least $\frac{k}{4(k+1)^2}\approx\frac{1}{4k}$.
In \cite{Feige-2011-submodular,Buchbinder-2012-nonmonotone-submodular}, two elegant deterministic $1/3$-approximation \unst algorithms are presented. We in this paper use the \unst algorithm proposed in \cite{Buchbinder-2012-nonmonotone-submodular}, which is given in Appendix \ref{appdxA:deterministicUSM}.
\end{proof}
\subsection{Asymptotic Time Complexity}\label{subsec:timeComplexity}
Without loss of generality, we first analyze the asymptotic time complexity in the $i$-th iteration with $S_i$ at the beginning.
\textbf{Time cost in Stage-1}. The {\tt whileloop}\xspace of Stage-1 will stop, if $S_i$ turns empty or if the relaxed constraint is violated; consequently, Stage-1 examines at most $|S_i|$ items.
In Stage-1, determining all possible $s^*$ on line \ref{algo:cherryPick} needs $\Theta(|S_i|^2)$ calls of $f$-oracles in total.
In addition, it is easy to know that Stage-1 needs $\Theta(|S_i|)$ calls of $\rf$-oracles in constraint evaluation.
\textbf{Time cost in Stage-2}. In Stage-2, \unst is called $|Y_i|$ times, and every call for \unst needs $\mathcal{O}(|X_i|)$ $f$-oracles.
With $Y_i\subseteq X_i\subseteq S_i$, therefore, Stage-2's time cost can be loosely upper bounded by $\mathcal{O}(|S_i|^2)$ calls of $f$-oracle.
Besides involving the two-stage {\tt forloop}\xspace as protagonist, our algorithm in its last step sorts through the collection $\mathcal{T}$ to return the best solution, and clearly, this process needs $\Theta(|\mathcal{T}|)$ time. Stage-2 of iteration $i$ adds into $\mathcal{T}$ at most $|Y_i|$ local optima; thus, the size of $\mathcal{T}$ is far less than $k|\Omega|$.
To sum up, the time complexity of our algorithm is upper bounded by $\mathcal{O}(kn^2)$ $f$-oracles plus $\mathcal{O}(kn)$ $\rf$-oracles, where $n=|\Omega|$. We will in future give each stage a tighter analysis that can further reduce this time complexity.
For the settings with $k$-system constraint, we cannot easily know $k$ in advance because determining $k$ often requires exponentially exhaustive computation. In literature, $k$ is usually replaced by the size of $\Omega$. Although doing so will not worsen the theoretical time complexity too much, less $k$ is preferable in practice.
In \cite{AAGK-2010-nonsubmodular}, the authors recommend that $k$ can be set to 2---running their SMS's iteration only twice instead of $|\Omega|$ times---in order to considerably reduce the run-time.
In \cite{Feldman-2017-nonmonotone-submodular}, the authors find that, in the SMS-like algorithms, reducing $k$ down to $\sqrt{k}$ will not impact the algorithm approximation performance; that is, in our algorithm's implementation, $k$ can be safely replaced by $\sqrt{|\Omega|}$, thereby leading to a significant reduction in computational time.
\subsection{Remark about the Over-budget}\label{subsec:control}
Our algorithm's solution may be beyond the original budget $\bgt$, and the amount of over-budget is at most $\theta\bgt$. Recall that the error parameter $\theta$ is the approximation factor of algorithm $\rf$ evaluating the routing cost. Obviously, the smaller $\theta$ is, the less the over-budget will be.
In many practical routing constraint settings, there exist $(1+\theta)$-approximation algorithms, where $\theta$ values are very small numbers, often less than one.
For instance, there exists 1.55-approximation algorithm (i.e., $\theta=0.55$) for minimum-weight multicast routing problem~\cite{Du-2012-approx-bk}.
If the routing cost is determined by Euclidean TSP, for instance, we can recruit a PTAS (Polynomial Time Approximation Scheme) for TSP problem and set its $\theta$ to be any small to control the over-budget below a very small scale.
In detail, PTAS is a type of approximation algorithm for computation-intractable problems. A PTAS algorithm can achieve $(1+\theta)$-approximation for minimization, or $(1-\theta)$-approximation for maximization, where $\theta>0$; and for any fixed $\theta>0$, it runs in time polynomial in the input instance's size. For instance, there exists PTAS for Euclidean TSP problems, which finds a $(1+\theta)$-approximation solution in time of at most $\mathcal{O}(n(\log n)^{o(1/\theta)})$; there exists PTAS for Subset-Sum problems, in time of $\mathcal{O}(n^3(\log n)^2/\theta)$.
In our algorithm, though a smaller $\theta$ of PTAS might lead to more computation time in Stage-1's cost evaluation, it can in some degree reduce the time cost in Stage-2 by reducing the size of $Y_i$. The following theorem gives an explanation about such a run-time reduction.
\begin{theorem}\label{thr:stop2}
\emph{
Given $S_i$, if the $\rho$-{\tt whileloop}\xspace stops with $X_i^\rho\subseteq S_i$ and the $\rf$-{\tt whileloop}\xspace, with $X_i^\rf\subseteq S_i$, then we always have $|X_i^\rf \backslash X_i^\rho|\leq 1$ for any feasible $0<\theta \leq \cmin/\bgt$, where $\theta$ is the error parameter of $\rf$.
}
\end{theorem}
\begin{proof}
Since Theorem \ref{thr:stop1} has proven $X_i^\rho\subseteq X_i^\rf$ for any $\theta$, we here suppose that, given $S_i$, the $\rho$-{\tt whileloop}\xspace can stop at $s_k$ if the $\rf$-{\tt whileloop}\xspace stops at $s_{k+2}$. We next complete this proof by contradiction.
From the conditions in which $\rho$ and $\rf$ stop, we have (1) $\rf_{k+2}\leq(1+\theta)\bgt$, and (2) $\rho_{k}\leq\bgt$ but $\rho_{k+1}>\bgt$. According to the property of routing cost function, it is easy to know $\rho_{k+2}\geq\rho_{k+1}+c_{k+2}>\bgt+\cmin$, where $c_{k+2}$ is the visiting cost at item $s_{k+2}$.
Because $\rf$ approximates $\rho$ and $\theta\leq\cmin/\bgt$, we have $\rf_{k+2}\geq\rho_{k+2}$, which further leads to
\begin{equation}\label{eqn:contradiction2}
\rf_{k+2}\geq\rho_{k+2}>\bgt+\cmin\geq\bgt+\theta\bgt\,.
\end{equation}
This inequality contradicts $\rf_{k+2}\leq(1+\theta)\bgt$. If $\rf$-{\tt whileloop}\xspace stops at $s_{k+2}$, therefore, $\rho$-{\tt whileloop}\xspace cannot stop at $s_k$. Moreover, the $\rho$-{\tt whileloop}\xspace cannot stop at $s_{j}$ for any $j< k$, too. Thus, $\rho$-{\tt whileloop}\xspace can only stop either at $s_{k+1}$ or at $s_{k+2}$. This theorem holds true.
\end{proof}
If $\rf$ is a PTAS with $\theta\leq\cmin/\bgt$, then we will have $|Y_i|=|X_i^\rf\backslash X_i^\rho|\leq 1$ at the end of Stage-1. It means that Stage-2 can finish with at most two calls of \unst. So a PTAS of $\rho$ with small $\theta$ can lower Stage-2's time cost.
With Theorem, \ref{thr:stop2} we can readily have Corollary \ref{cor:theta}: the run-time and the budget control can be traded off according to practical settings and resource supply.
\begin{corollary}\label{cor:theta}
\emph{
Given $S_i$, if the $\rho$-{\tt whileloop}\xspace stops with $X_i^\rho\subseteq S_i$ and the $\rf$-{\tt whileloop}\xspace, with $X_i^\rf\subseteq S_i$, then we always have $|X_i^\rf \backslash X_i^\rho|\leq r$ for any $0<\theta\leq r\cdot\cmin/\bgt$, where $r$ is a positive integer ranging in $[1, \bgt/\cmin)$.
}
\end{corollary}
\section{Experiments}\label{sec:Experiment}
In this section we conduct numerical case studies to investigate our algorithm's performance.
We present two baseline algorithms, \bsRand and \bsRMax. Baseline Rand continually selects items in a random way until the budget is violated.
Like ours, baseline \bsRMax is also an iterated greedy algorithm, which adds the item $\arg\max\{f_X^{+}(x)/\rf_X^{+}(x)|x\in \Omega\}$ in each iteration, until it uses up the budget or its marginal profit turns negative. By maximizing a benefit-cost ratio, \bsRMax follows an intuitive idea: preferring to select the item that can bring higher marginal gain with less cost increase.
\subsection{Case 1: Diversified Task Offloading in Big Data}
This case study is about the Example-1 early mentioned in section \ref{sub:problem}. We disseminate a personalized movie recommendation task to a set of processors that are curated in a complete undirected graph; the edge weight represents the delay between processors. Each processor has a local movies' set, and the movies' meta data is foreknown to the user.
\begin{figure}
\centering
\includegraphics[width=.4\textwidth]{figures/fig-multicastRoutingTree.pdf}
\caption{Example of a multicast delay-aware routing tree.}
\label{fig:multicastTree}
\end{figure}
Fig. \ref{fig:multicastTree} shows a multicast routing tree that spans all the selected processors. Each processor executes the task and returns a result (in the form of packet), along the tree, to the user. We here assume that the links are all simplex and associated with a delay (i.e., edge weight). In Fig. \ref{fig:multicastTree}, for example, processor $w$ first takes (26+12) time units to collect the packets from both $u$ and $v$, and then takes 30 time units to forward a combined (or compressed) packet to the user. In the multicast routing tree, therefore, the sum of all edge weights measures the total time for the user to retrieve the results from all the selected processors.
Our goal in this example is to recommend a list of more representative movies while the response time stays under a certain time budget.
Our dataset comes from MovieLens \cite{movielens} which involves the user information and their ratings of movie. However, the dataset is sparse in rating because most users rated only a handful of movies, i.e., the user-rating matrix is of low-rank. To address this issue, we used the PMF (probabilistic matrix factorization) model \cite{Salakhutdinov-2007-matrix} to generate a linearly-scaled rating matrix ${\rm M}_{k\times n}$ for $k$ users and $n$ movies.
We used the function in \eqref{diversity1} to calculate the objective value or the \emph{score} of movie recommendation, and set $\lambda$ to one.
For two movies $i$ and $j$, we evaluated their similarity $s_{i,j}$ by using the inner product of their non-normalized feature vectors.
In experiments, we assigned to each link a uniform random delay ranging from one to two hundred time units; and we applied the KMB~\cite{Kou-1981-steiner}, a 2-approximation algorithm, to producing a delay-minimum multicast tree over the processors selected in each iteration.
\begin{figure}[htbp]\centering
\subfigure[\sf ours]{
\includegraphics[width=0.20\textwidth]{figures/graph.pdf}
\label{fig:graphOurs}
}\hfil
\subfigure[\sf rMax]{
\includegraphics[width=0.20\textwidth]{figures/graph_2.pdf}
\label{fig:graphrMax}
}\hfil
\subfigure[\sf Rand]{
\includegraphics[width=0.20\textwidth]{figures/graph_3.pdf}
\label{fig:graphRand}
}
\caption{Illustration of three algorithms in processor selection.}
\label{fig:multicastTrees}
\end{figure}
\begin{figure}\centering
\includegraphics[width=.685\textwidth]{figures/fig-score-scale.pdf}
\caption{Comparison of three algorithms under different network scales, where gray region is Rand's error band.}
\label{fig:scoreVsSize}
\end{figure}
Fig.~\ref{fig:multicastTrees} shows the processors selected by the three algorithms to complete movie recommendation in the case where there are 20 available processors; for clarity, Fig.~\ref{fig:multicastTrees} only shows the result of a small-scale experiment.
Fig.~\ref{fig:scoreVsSize} plots the effect of network scale on recommendation performance. For the three algorithms, an intuitive result is that the more processors (i.e., the more movies) are available, the higher the scores. For instance, with 100 processors, our algorithm can achieve a recommendation score of $1.43\times 10^5$, while, with 500 processors, its recommendation score is $8\times 10^5$, almost five times the score under 100 processors.
Such a comparison shows that more processors can bring a larger search space and our algorithm can find better solution.
Of these three algorithms, \bsRand's recommendation scores the lowest for the two network scales. From the two sub-plots of Fig.~\ref{fig:scoreVsSize}, we can see that, for the 100-processor case, our algorithm's score is 0.7\% higher than \bsRMax's; however, for the 500-processor case, the performance enhancement stretches to 6.7\%.
\begin{figure}\centering
\subfigure[\sf \bsRand]{
\includegraphics[width=0.20\textwidth]{figures/fig-sensing-rand.pdf}
\label{fig:senseRand}
}\hfil
\subfigure[\sf \bsRMax]{
\includegraphics[width=0.20\textwidth]{figures/fig-sensing-rmax.pdf}
\label{fig:senseRMax}
}\hfil
\subfigure[\sf ours]{
\includegraphics[width=0.20\textwidth]{figures/fig-sensing-ours.pdf}
\label{fig:senseOurs}
}
\caption{Illustration of three algorithms in the selection of PoI's (gray squares) and the robotic data-collecting trajectory.}
\label{fig:sensing}
\end{figure}
\subsection{Case 2: Informative Robotic Data Collection}
We consider a scenario of Example-2, where 45 points of interest (PoI's) are specified within a $35\times 40$ square monitoring area. A charging depot is located at the corner of the monitoring area, and a robot departs from the depot to visit the PoI's to collect spatial data. The robot needs to pay energy both for traveling and for collecting data, and it must return to the depot for energy replenishment before it runs of energy.
We assume that the traveling-energy rate is 0.6 (i.e., it needs to pay $0.6d$ energy units for moving a distance of $d$), and the data-collecting energy at some PoI is a random number within $(0,2)$ that is specified in advance.
We here use mutual information to measure how informative a subset of PoI's is, and create the spatial correlation between all the PoI's, from the data set obtained in a testbed experiment~\cite{Krause-2008-submodular-gaussian}. This testbed deployed 54 sensors monitor the environmental temperature and humidity in an area of $35\times 40\mbox{m}^2$.
To determine robot's energy-least TSP tour, we use the PTAS algorithm proposed in \cite{Mitchell-2007-TSPN} and set its error parameter $\theta$ to 0.1 in our experiments.
In this case, our goal is to find a data-collection schedule for the robot, such that the mutual information can be maximized while its energy budget is not violated. Appendix \ref{appdxC:MutualInfo} calculates the mutual information on the basis of Gaussian process model.
Fig. \ref{fig:sensing} compares our algorithm and the two baselines, in which the robot's energy budget is set to 120 energy units. The PoI's selected by our algorithm are the most evenly in terms of spatial distribution.
Fig. \ref{fig:gain} plots how the three algorithms will perform as the energy budget, and how their information gains change as the number of selected PoI's increases.
An abundant energy supply usually leads to higher information gain, but it is not a panacea: for instance, \bsRMax's information gain can no longer be enhanced when the energy budgets reach 240. In particular, although \bsRand recklessly tries to use up budget to observe as many PoI's as possible, its information gain turns down as the budget goes higher than 320 energy units, because the mutual information measure is nonmonotone (i.e., more PoI's could lead to lower mutual information values).
\begin{figure}\centering
\subfigure[under different budgets]{
\includegraphics[width=0.35\textwidth]{figures/fig-MIvsBudget.pdf}
\label{fig:MIvsBudget}
}\hfil
\subfigure[with different PoI counts]{
\includegraphics[width=0.35\textwidth]{figures/fig-MIvsNum.pdf}
\label{fig:MIvsNum}
}
\caption{Comparison of three algorithms in information, where gray regions are Rand's error band.}
\label{fig:gain}
\end{figure}
Fig. \ref{fig:energyAlloc} illustrates the energy allocation of three algorithms under repeated experiments with random seeds. In the case of budget=100, our algorithm pays 38.5\% of, and 51.9\% of, the energy budget for collecting data and for traveling, respectively, while \bsRand and \bsRMax pay less energy for collecting data. On average, our algorithm visits about seven PoI's, while the two baselines can visit less-than-four PoI's.
On the other hand, the total energy consumption rates are 90\%, 78\%, and 68\% for our algorithm, \bsRand, and \bsRMax, respectively.
Similar comparison can also be found in the case of budget=200. Fig. \ref{fig:energyAlloc} shows that our algorithm can exploit the limited energy budget more effectively than the two baselines.
\begin{figure}\centering
\subfigure[budget=100]{
\includegraphics[width=0.375\textwidth]{figures/fig-energy-alloc-e100.pdf}
\label{fig:budget100}
}\hfil
\subfigure[budget=200]{
\includegraphics[width=0.375\textwidth]{figures/fig-energy-alloc-e200.pdf}
\label{fig:budget200}
}
\caption{Comparison of three algorithms in energy efficiency.}
\label{fig:energyAlloc}
\end{figure}
\section{Conclusion}\label{sec:Conclustion}
In this paper, we have investigated the nonmonotone submodular maximization problem with routing constraint, proved it to be a $k$-system-constrained nonmonotone submodular maximization problem, and proposed a $[1/4k, 1+\theta]$-bicriterion approximation algorithm. Considering the intractability of constraint evaluation, we in our algorithm draw an elegant connection between the constraint evaluation's error parameter (i.e., $\theta$) and the amount of over-budget. Further we have developed the proof machinery for our problem; we believe it can shed light on maximizing nonmonotone submodular function whose constraint evaluation is generally NP-hard.
In addition, we have applied our algorithm to two motivating examples. The experimental results show our two-stage algorithm's effectiveness.
\input{paper2.bbl}
| {'timestamp': '2022-12-01T02:18:35', 'yymm': '2211', 'arxiv_id': '2211.17131', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17131'} | arxiv |
\section{Summary and future directions}
Our results show that the Index (or Inner-Product) gadget is not a good disperser for low min-entropy deficiency rectangles $\mathcal{X} \times \mathcal{Y}$ when $m$ is much smaller than $\log N$.
Thus to reduce the gadget size beyond logarithmic using current techniques we need to consider other properties on the rectangle $\mathcal{X} \times \mathcal{Y}$ maintained during the simulation that can ensure that Index is a good disperser.
Our counterexample to the conjecture of Lovett et al.~\cite{DBLP:conf/innovations/LovettMMPZ22} suggests the following natural property for $\mathcal{X}$, $\mathcal{Y}$ in addition to having low entropy deficiency:
\begin{itemize}
\item
Except for a small subset of blocks $J$ of size $O(\Delta)$, every block of every $y$ in $\mathcal{Y}$ is “almost” balanced in terms of the number of zeroes and ones. That is, for any $i \in [N]\setminus J$ and for any $y \in \mathcal{Y}$, $ |y^i|_1 \approx m-|y^i|_1$, where $|y^i|_1$ denotes the number of ones in the $i$-th block of $y$.
\end{itemize}
Note that our counterexample is avoided by $\mathcal{Y}$ satisfying this property;
indeed this property is violated in the extreme by our counterexample as every $y$ in the set $\mathcal{Y}$ we construct has $\omega(\Delta)$ blocks that are maximally unbalanced.
The standard simulation paradigm allows considerable flexibility in choosing which subset to focus on in the rectangle of inputs associated with each node
of the communication protocol. Maintaining something like the property above is easy to do and it is plausible that this or related properties will indeed be sufficient to yield general lifting theorems with very small Index gadgets.
Although our counterexample ruled out improving the gadget size to constant for Index in deterministic lifting theorems using current techniques, we were able to prove a lifting theorem with constant-sized gadgets for the restricted class of protocols where Bob is restricted to sending parities. A natural extension of this direction is to consider semi-structured protocols where Bob is restricted to sending other interesting functions of his input bits.
A natural class of restricted functions are threshold functions.
The ideas used in our lifting theorem do not work in this case.
As illustrated by the application of our semi-structured lifting theorem to Res$(\oplus)$ lower bounds, such restricted lifting theorems may have immediate applications in proof complexity.
They may also be a natural avenue for developing new tools and techniques that could potentially help in proving general lifting theorems with constant sized gadgets.
\section{On the insufficiency of low deficiency and
high min-entropy rate}
In this section we prove \cref{thm:main,thm:inner-product}.
Let $K$ be any function of $N$ with $K\ge 1$
for all $N$
and assume that $2^m\le N/(K\Delta)$.
We will construct a specific distribution $\mathcal{Y}$, with deficiency bounded by $\Delta$ and min-entropy rate at
least $1-1/m$, such that for any $I\subseteq [N]$ with $|I|\leq (K-1)\Delta$, $\text{IND}_m^{[N]\setminus I}([m]^N,\mathcal{Y})$ does not contain the all-1 string.
We establish this simply by showing that for all $(x,y)\in [m]^N \times \mathcal{Y}$, $\text{IND}_m^N(x,y)$ has Hamming weight more than $(K-1)\Delta$.
Thus any projection of $\text{IND}(\mathcal{X},\mathcal{Y})$ onto $N-|I|\ge N-(K-1)\Delta$ coordinates will contain at least one $1$, and would therefore miss the all-0 string.
To this end, we will construct $\mathcal{Y}$ as the uniform distribution on a subset $S\subseteq (\set{0,1}^m)^N$ with the following properties :
\begin{enumerate}
\item\label{prop:AtLeastKOnes} Every $y\in S$ has at least $k > (K-1)\Delta$ blocks that are equal to $1^m$.
\item\label{prop:LowDeficiency} $|S|\ge 2^{mN-\Delta}$
\item\label{prop:HighMinEntropyRate} The min-entropy
on any subset of $b\le N$ blocks is at least $(m-1)b$.
\end{enumerate}
The second property ensures that the deficiency of $\mathcal{Y}$ is at most $\Delta$ and the first property guarantees that every
output has at least $k$ 1-bits no matter what the input $x$ is.
The third property is simply that the min-entropy rate
is at least $(1-1/m)$.
The essence of the proof idea applies in the case that $\Delta=1$; the general case is a simple extension
of that special case:
\paragraph*{Counterexample when $\Delta=1$:}
We derive a counterexample in this case
by choosing $k=\lfloor K\rfloor>K-1$ and setting $S$ to be the set of all inputs in $(\set{0,1}^m)^N$ that have at least $k$ blocks of the form $1^m$; i.e., all-1 blocks.
The key observation that makes this work is the
following:
\begin{observation}
\label{all-1}
For $y$ chosen uniformly at random from $(\set{0,1}^m)^N$, the number of all-1 blocks in $y$ is distributed according to the binomial distribution $B(N,1/2^m)$.
\end{observation}
In particular, since $\Delta=1$ this means that the expected number of all-1
blocks in $y$ chosen uniformly from $(\set{0,1}^m)^N$ is
$N/2^m\ge K$.
By applying a bound on the median of binomial distributions, we obtain the following:
\begin{lemma}
\label{all-1-tail}
For $2^m\le N/K$, at least
$1/2$ of all strings in $(\set{0,1}^m)^N$ have more than
$K-1$ all-1 blocks.
\end{lemma}
\begin{sloppypar}
\begin{proof}
By~\cref{all-1}, the number of all-1 blocks is given by the binomial distribution $B(N,1/2^m)$.
By \cref{prop:binomomial-median}, the median of this
distribution is at least $\lfloor N/2^m\rfloor\ge \lfloor K \rfloor > K-1$.
The claim follows since
the binomial is integer-valued.
\end{proof}
\end{sloppypar}
\cref{all-1-tail} shows that $\mathcal{Y}$ is a uniform
distribution with deficiency
at most 1, which means that the projection on any $b$
blocks has min-entropy at least $mb-1$ and hence $\mathcal{Y}$
has min-entropy rate at least $1-1/m$.
\paragraph*{Counterexample for $\Delta>1$ but $o(N)$:}
For this we assume without loss of generality that $\Delta$ is
an integer and $N=N'\Delta$ for some integer $N'$ since rounding can add only $\Delta-1$ extra coordinates.
Since $2^m\le N/(K\Delta)$, we have
$2^m\le N'/K$.
This means that we can use the counterexample distribution
$\mathcal{Y}'$ for the
case $\Delta=1$ on $N'$ coordinates.
We define $\mathcal{Y}$ to the direct
product of $\Delta$ independent copies of the distribution $\mathcal{Y}'$ on disjoint coordinates.
By construction, $\mathcal{Y}$ has
deficiency at most $\Delta$; it also has min-entropy
rate at least that of each $\mathcal{Y}'$ which is $1-1/m$
since it is a product over disjoint coordinates.
Also by construction, every $y$ in the support of $\mathcal{Y}$ has
more than $(K-1)\Delta$ all-1 blocks which means that no
set $I$ of at most $(K-1)\Delta$ coordinates cannot
cover all of the all-1 blocks of $y$, which would be necessary to
have
the all-0 string in
$\text{IND}_m^{[N]\setminus|I|}([m]^{N},\mathcal{Y})$.
\paragraph*{Extending the counterexamples to other gadgets}
\label{subsec:extendingToOtherGadgets}
We note that the above result also disproves a similar conjecture for any 2-party gadget $g:X\times Y\rightarrow \set{0,1}$
whose communication matrix has a row or column that has a
constant value.
For example, the Inner-Product gadget on $\IP_b:\set{0,1}^b\times
\set{0,1}^b$ has
this property for the row or column of its communication matrix
indexed by $0^b$.
That is, $\langle x,0^b\rangle=0$ for all
$x\in \set{0,1}^b$.
It is easy to see that the above analysis works
to disprove the analogous conjecture for Inner-Product under the
same conditions, though
in this case, the output vector that would be missed is
the all-1 vector.
\section{Introduction}
In recent years, a substantial number of long-standing problems~\cite{DBLP:journals/toc/GargGK020,DBLP:journals/siamcomp/Goos0018,LRS15conf,DBLP:journals/siamcomp/GoosP18,RPRC16conf}
have been resolved using the method of \emph{lifting}.
Lifting results take a gadget function $g$ and show
that any function $f:\set{0,1}^N\rightarrow\set{0,1}$ that is
hard to compute by decision trees can be modified to a new
function $F=f\circ g^N$ that is hard for a more powerful
computational model, typically that of 2-party
communication complexity, in which case
$g:X\times Y\rightarrow\set{0,1}$ and the inputs for $F$ for the
two players are
partitioned into $\mathbf{x}\in X^N$ and $\mathbf{y}\in Y^N$.
A particularly natural and important choice of gadget $g$ is the \emph{Index} gadget $\text{IND}_m:[m]\times \set{0,1}^m$ given by
$\text{IND}_m(x,y)=y_x$.
The Index gadget is universal for all gadgets
$g:X\times Y\rightarrow\set{0,1}$ where $|X|=|Y|=m$ via the simple
reduction where $y$ is replaced by the string $(g(x,y))_{x\in X}$.
Since $\text{IND}_m$ has a 2-party protocol of cost $\log_2 m +1$,
the communication complexity of $f\circ \text{IND}_m^N$ is at
most $O(C^{dt}(f)\log m)$, where $C^{dt}(f)$ is the decision
tree complexity of $f$. Another important gadget $g$ is the Inner-Product function $\IP_b:\set{0,1}^b\times\set{0,1}^b\rightarrow\set{0,1}$ given by $\IP_b(x,y)=x\cdot y\bmod 2$.
An important limitation on the quality of lower bounds that can be
proven by
lifting with a gadget
$g:X\times Y\rightarrow \set{0,1}$ comes from the fact that the input size for $F$
grows by a factor of $\log_2 |X|+\log_2 |Y|$ bits from that
of $f$.
This limits the lower bounds on the lifted function $F$
compared to the input size of $F$.
The original lifting theorems of \cite{RazM97conf} and \cite{DBLP:journals/siamcomp/GoosP018} used Index gadgets with $m$ a large polynomial in $N$.
Subsequently, \cite{CKLM19journ, WuYY17eccc} proved a lifting theorem for Inner-Product gadgets with $b=c\log_2 N$ for some constant $c>5$. Later,~\cite{CKLM19journ} improved $c$ to almost 2.
The first lifting theorem for randomized computation was proved by~\cite{DBLP:journals/siamcomp/GoosPW20} again for Index but for $m$ an even larger polynomial in $N$ and later again, by \cite{DBLP:journals/siamcomp/ChattopadhyayFK21}, for Inner-Product for $b$ a larger constant multiple of $\log_2 N$ than for deterministic lifting.
A key question asked in a precursor paper to these lifting theorems~\cite{DBLP:journals/siamcomp/GoosLMWZ16} is whether lifting is possible with a sub-logarithmic or even constant-size Inner-Product gadget.
Smaller gadgets imply sharper lifting results and
more general classes of functions for which lifting
may be used to prove lower bounds.
Proving such lifting theorems would imply breakthrough results in other areas.
For example, proving lifting theorems with constant-size gadgets would give us a near-complete understanding of communication complexity of lifted search problems and would imply breakthrough results in associated areas like proof complexity and circuit complexity\footnote{In this paper we focus on the setting of query-to-communication lifting where the query complexity of $f$ is lifted to the communication complexity of $F$ using the gadget $g$.
There are other lifting theorems (see~\cite{Sherstov11journ}) which lift analytical parameters of the function $f$ to the communication complexity of $F$.
In these settings, lifting theorems with constant-size gadgets are known~\cite{Sherstov11journ}
but for many interesting applications of lifting, there is a significant gap between analytical parameters of $f$ like approximate-degree (used in~\cite{Sherstov11journ}) and the query complexity of $f$.
Thus, such lifting theorems with constant-size gadgets are not enough to give the results alluded to above.}.
Even improving the gadget size for Index to poly-logarithmic in $N$ would improve the best known monotone circuit size lower bounds~\cite{HR00conf} from $2^{\Tilde{\Omega}(n^{1/3})}$ to $2^{\Tilde{\Omega}(n)}$.
In the dream range of constant size, by the universality of Index, if there is any lifting theorem for any constant-size gadget,
there would be one for constant-size Index
gadgets.
Recent work by Lovett, Meka, Mertz, Pitassi and Zhang~\cite{DBLP:conf/innovations/LovettMMPZ22} used a new bound for the Sunflower Lemma~\cite{ALWZ:sunflower-journal} to improve the size of the Index gadget
that can
be used in deterministic lifting results to $O(N\log N)$.
They also identified a conjecture
regarding entropy deficiency and the disperser property of the Index gadget that is essential for further reductions in gadget size using current techniques.
Before stating the conjecture of Lovett, Meka, Mertz, Pitassi and Zhang~\cite{DBLP:conf/innovations/LovettMMPZ22} we give an
outline of the meta-technique for proving query to communication lifting theorems, known as the simulation theorem framework.
\subsection*{The lifting paradigm}
The general paradigm for proving a query-to-communication lifting theorem is a step-by-step simulation argument that begins with a
communication protocol $\ensuremath \Pi$ for $f\circ g^N$ on inputs in $X^N\times Y^N$ and derives a decision tree $T$ computing $f$ on inputs $z\in \set{0,1}^N$.
Beginning at the root of $\ensuremath \Pi$ and with $T$ a single root node, the simulation proceeds
to follow a path in $\ensuremath \Pi$ maintaining sets of
inputs $\mathcal{X}\subseteq X^N$ and $\mathcal{Y}\subseteq Y^N$
consistent with the current node $u$ in protocol $\ensuremath \Pi$. (The exact procedure for choosing the path and the sets $\mathcal{X}$ and $\mathcal{Y}$ varies.)
At any point in time when $\mathcal{X}\times \mathcal{Y}$ has revealed too much about the value of $z_i=g(x_i,y_i)$
for some $i$, the simulation at the current leaf
node $v$ of $T$ queries $z_i$ and adds the children
$v'$ and $v''$ to $T$, one for each outcome.
The simulation then splits into cases depending on whether the $0$ or $1$ out-edge from $v$ is being followed.
There may be multiple $i$ for which this may need
to be done at the same time.
The simulations maintain several invariants
at each corresponding pair of nodes $u$ in $\ensuremath \Pi$ and $v$ in $T$ that occur in this simulation.
In particular, if $\mathcal{X}$ and $\mathcal{Y}$ are associated with this pair of nodes and
$I\subseteq [N]$ is the set
of input indices queried on the path in $T$ to $v$
and $z_I$ is the assignment that takes $T$ to the node $v$
then we require
\begin{align*}
g^I(\mathcal{X},\mathcal{Y})&=z_I&\mbox{(Consistency)}\\
g^{[N]\setminus I}(\mathcal{X},\mathcal{Y})&=\set{0,1}^{[N]\setminus I}.\qquad&\mbox{(Disperser/Extensibility)}
\end{align*}
The consistency property is obviously required for
correctness.
The disperser property is required
because the simulation cannot
predict what query indices will be needed for $T$
in the future.
Overall, in order to yield a good complexity bound,
the argument also has to bound the length of the path to $v$ in
$T$, which is the size of the set $I$, as a function
of the length of the path from the root to $u$ in $\ensuremath \Pi$.
In order to maintain these properties, the simulations also maintain some ``nice'' structure
on the sets $\mathcal{X}$ and $\mathcal{Y}$.
The most common notions of nice structure are
small \emph{entropy deficiency} of
the induced distributions on the unqueried coordinates $[N]\setminus I$ or high \emph{min-entropy rate} (equivalently
the \emph{block min-entropy})\footnote{Many existing results for the Index gadget use bounds on the min-entropy rate on the $X^N$ side and entropy deficiency on the $Y^N$ side.}.
The min-entropy rate is the minimum ratio of the min-entropy of the induced distributions on any subset of unqueried blocks compared to the maximum possible entropy on those blocks.
There are other "nice" properties that were used in the past. For example, one of the first lifting theorems by Raz and McKenzie~\cite{RazM97conf} used a combinatorial notion of niceness defined as average-degrees in a layered graph corresponding to $\mathcal{X}$. This property was also used in the later reproving of the result by~\cite{DBLP:journals/siamcomp/GoosP018}, and the result on extending deterministic lifting theorems to a larger class of gadgets including Inner Product by~\cite{WuYY17eccc,CKLM19journ}\footnote{\cite{CKLM19journ} uses it slightly differently from the application of the property for the Index gadget.}. All of the results using this combinatorial property crucially depend on a transformation in layered graphs from average degree to minimum degree known as the ``thickness lemma'' to prove the disperser property of the gadget. It is a folklore result that such average-degree to min-degree transformations do not work for Index gadgets of linear size. Thus, using "average-degree" as the nice property cannot yield lifting theorems with sublinear-size Index gadgets using existing techniques.
\subsection*{The LMMPZ conjecture on entropy deficiency and disperser properties of $\text{IND}$}
The conjecture of Lovett et al.~\cite{DBLP:conf/innovations/LovettMMPZ22} is a necessary condition for small entropy deficiency to be sufficient for lifting with the Index function.
To motivate the parameters of the conjecture we first note how entropy deficiency relates to the numbers of bits of communication sent in the protocol $\ensuremath \Pi$:
In the course of following a path in $\ensuremath \Pi$ to a node $u$, each bit communicated may
split the set of consistent inputs in either $X^N$
or $Y^N$ by a factor of 2, which increases the
entropy deficiency by 1.
If good min-entropy rate is also required,
additional pruning must be done, which further increases the entropy deficiency.
Therefore, the best one can do in terms of maintaining small entropy deficiency is to maintain a bound $\Delta$ on
entropy deficiency for $\mathcal{X}$ and $\mathcal{Y}$ that is proportional to
the number of bits sent in $\ensuremath \Pi$.
Bounding the length of the path in the decision in terms of
the number of bits sent means that $|I|$ should not be too large as a function of $\Delta$.
This
led Lovett et al.\ to formulate the following
conjecture on the disperser properties of
Index as a first step towards obtaining
lifting theorems for small gadget sizes:
\begin{conjecture}[{\cite[Conjecture 11]{DBLP:conf/innovations/LovettMMPZ22}}]
\label{conj:TonisConj}
There exists $c$, such that for all large enough $m$ the following holds: Let $\mathcal{X},\mathcal{Y}$ be distributions on $[m]^N$, ${(\set{0,1}^m)}^{N}$, respectively, each with entropy deficiency at most $\Delta$. Then $\text{IND}_m^N(\mathcal{X},\mathcal{Y})$ contains a sub-cube of co-dimension at most $c \Delta$.
That is, there exists $I\subseteq [N]$, $|I|\leq c\Delta$, and $\gamma \in \set{0,1}^I$ such that for all $z\in \set{0,1}^N$ with $z_I=\gamma$ we have
{ \setboolean{@fleqn}{false}
\begin{equation}
\Pr_{x\sim\mathcal{X},\ y\sim\mathcal{Y}} [\text{IND}_m^N(x,y)=z] > 0.\label{cond:conjecture}\\[-1ex]
\end{equation}
}
\end{conjecture}
\paragraph*{Remark:}
Note that the condition \cref{cond:conjecture} is somewhat weaker than
the combination of the consistency and disperser
conditions in the above lifting paradigm. The lifting paradigm would correspond to additionally requiring that the $(x,y)$ pair in \cref{cond:conjecture} come from some $\mathcal{X}'\subseteq\mathcal{X}$ and $\mathcal{Y}'\subseteq\mathcal{Y}$ such that $\text{IND}_m^I(\mathcal{X}',\mathcal{Y}')=\gamma$.
Here, one could satisfy \cref{cond:conjecture} using pairs $(x,y)$ and $(x',y')$ with $\text{IND}_m^I(x,y)=\text{IND}_m^I(x',y')=\gamma$ but
$\text{IND}_m^I(x,y')\ne\gamma$.
\vspace*{1ex}
The results in~\cite{DBLP:conf/innovations/LovettMMPZ22} prove the conjecture for $m=O(N \log N)$,
in fact the stronger version with separate consistency and disperser properties required for lifting; previously it was only known when $m \gg N^2$.
Based on a related statement about $p$-biased $(\mathcal{X},\mathcal{Y})$ proved in the Robust Sunflower Theorem from~\cite{ALWZ:sunflower-journal}, the authors~\cite{DBLP:conf/innovations/LovettMMPZ22} also suggest that it is hopeful to prove the conjecture when $m=\poly(\log N)$ using techniques from their work and~\cite{ALWZ:sunflower-journal}.
\subsection*{Our results}
We disprove the LMMPZ conjecture when $m$ is
$\log_2 N-\omega(1)$, even when $\mathcal{X}$ and $\mathcal{Y}$ are also assumed to have extremely high min-entropy rate.
In our counterexample the distribution for
$\mathcal{X}$ is uniform on $[m]^N$ and so has
full entropy and maximum possible min-entropy rate.
The distribution on $\mathcal{Y}$ is also uniform so we
view both $\mathcal{X}$ and $\mathcal{Y}$ as subsets of
$[m]^N$ and $(\set{0,1}^m)^N$ respectively.
Though the parameter $\Delta$ governing the entropy deficiency in the conjecture is universally quantified, the failure of the
conjecture occurs over a very wide range of values of $\Delta$.
In fact, when $m\le (1-\alpha)\log_2 N$, we prove
a much larger gap and show
that $|I|$ must be
$\Omega(N^\alpha)$ independent of $\Delta$ for \cref{cond:conjecture} to hold.
\begin{theorem}
\label{thm:main}
For any $\Delta\ge 1$ and $m$ with $2^m\le N/(K\Delta)$
for $K\ge 1$ there is a set
$\mathcal{Y}\subseteq (\set{0,1}^m)^N$ of entropy deficiency at most $\Delta$ and min-entropy rate at least
$1-1/m$ such that
for every $I\subseteq [N]$ with $\card{I} \leq (K-1) \Delta$,
the set $\text{IND}_m^{N\setminus I}([m]^N,\mathcal{Y})$ does not contain the all-0 string.
\end{theorem}
Since $\mathcal{X}=[m]^N$ has no deficiency (and min-entropy
rate 1) we immediately derive the following:
\begin{corollary}
\cref{conj:TonisConj} is false when
$m\leq \log_2 (N/\Delta)-\omega(1)$.
Moreover, for all $\Delta$, when
$m\le (1-\alpha)\log_2 N$, for any set
$I$,
$|I|$ must be
$\Omega(N^\alpha)$ for \cref{cond:conjecture} to hold.
\end{corollary}
Furthermore, an analogous property applies to the Inner-Product function:
\begin{theorem}
\label{thm:inner-product}
For $b\le \log_2(N/(K\Delta))$ for $K\ge 1$, there is a set
$\mathcal{Y}\subset (\set{0,1}^b)^N$ of entropy deficiency at most $\Delta$ and min-entropy rate more than
$1-1/b$ for every $I\subseteq [N]$ with $\card{I} \leq (K-1) \Delta$, the set
$\IP_b^{N\setminus I}((\set{0,1}^b)^N,\mathcal{Y})$
does not contain the all-1 string.
\end{theorem}
Therefore, though lifting theorems, both deterministic and randomized, have already been proven for
Inner-Product gadgets on $c\log_2 n$ bits using only properties of small entropy-deficiency and high min-entropy rate~\cite{DBLP:journals/siamcomp/ChattopadhyayFK21}, using these properties we can at best reduce the Inner-Product gadget
size in such
lifting theorems by at most a constant factor since lifting for Inner-Product gadgets with significantly fewer than $\log_2 n$ bits are impossible using those properties.
The proof idea for these theorems is quite simple and
relies on the fact that for such small values of $m$,
it is likely that a uniformly random string $y$ will
have many blocks $i$ where $y_i=0^m$ and hence
cannot have 1 output values in any of those coordinates.
Despite this setback, the dream of lifting theorems for constant-size gadgets remains.
Our second main result is that, though we can rule out the disperser properties of \cref{conj:TonisConj} for $\text{IND}_m$ with sub-logarithmic $m$,
there is an interesting class of protocols, one in
which Bob's messages are constrained to be parity functions of his input string $y$, in which we can prove a deterministic lifting theorem using
$\text{IND}_m$ gadget for \emph{constant size} $m$.
Since Alice is unrestricted and Bob is restricted,
we call such protocols semi-structured protocols.
We obtain a lifting theorem for semi-structured protocols showing that the decision tree height is asymptotically at most a $1/\log m$ fraction of the complexity of
the communication protocol for the lifted function with $\text{IND}_m^N$.
As is typical for deterministic lifting theorems, this works
both for functions and for search problems.
For protocols in which both Alice and Bob only send parities of their inputs, we obtain an even stronger simulation that
applies to the size of the decision tree produced in terms of the number of leaves (size) of the communication protocol for the
lifted function.
In particular a modification of this idea gives us a generic theorem that lifts decision tree lower bounds of height $t$
or size $s$
for any explicit function $f$ on $n$ inputs to a corresponding lower bound for parity decision trees of height $\Omega(t)$
or size $\Omega(s)$
for an explicit function $f'$ on $O(n)$ inputs.
The latter also yields new lower bounds for tree-like proofs in the
$Res(\oplus)$ proof system (also known as $ResLin_2$) introduced by
Raz and Tzamaret~\cite{DBLP:journals/apal/RazT08}.
Itsykson and Sokolov~\cite{DBLP:conf/mfcs/ItsyksonS14,DBLP:journals/apal/ItsyksonS20}
had previously shown tight exponential lower bounds for the pigeonhole principle as well as exponential lower bounds for a very restricted kind
of lifted formula based on Tseitin formulas from~\cite{bps:kfoldtseitin-journal}.
Huynh and Nordstr\"{o}m~\cite{DBLP:conf/stoc/HuynhN12} gave lifting theorems for a variety of other proof systems using constant-size Index gadgets (indeed with $m=3$) but these only yield good bounds for a restricted class of formulas whose search
problems have high ``critical block sensitivity".
Here we obtain exponential lower bounds for a substantially broader class of formulas.
In particular, for any of the vast class of $k$-CNF formulas $\varphi$ for which exponential tree-resolution lower bounds are known, we obtain lifted
$O(k)$-CNF formulas $\varphi'$ with a constant factor increase in number of variables (and a constant factor increase in number of clauses if $k$ is constant)
requiring tree-like $Res(\oplus)$ refutations of
exponential size (indeed at least the tree-like resolution refutation size for
$\varphi$).
\paragraph*{Related Work}
Independently of our work,
Chattopadhyay, Mande, Sanyal, and Sherif~\cite{ChattopadhyayMSS23-arxiv} have obtained closely related lifting results for parity decision tree size and the size of tree-like $Res(\oplus)$ proofs.
Their lifting theorem works not only for lifting with Index gadgets but, more generally, for lifting with a class of gadgets that includes Inner-Product and other simple gadgets.
Their methods and ours have considerable
similarity, particularly in the use of
row-reduction as a key component.
\section{Lifting theorem for semi-structured protocols}
Since \cref{conj:TonisConj} is false for $m = (1- o(1) )\log N$, without modification, existing techniques cannot reduce the gadget size below this threshold.
However, this does not rule out other approaches to proving lifting theorems with very small gadgets, even for constant-size ones.
Are such theorems
with constant-sized gadgets possible at all?
As a first step towards answering this question, in this section we prove a (deterministic) lifting theorem with constant-size Index gadgets for a restricted family of communication protocols.
The restricted family that we consider are deterministic communication protocols in which Alice is unrestricted, but Bob is only allowed to communicate parities of his input bits.
Since Alice is unrestricted and Bob is restricted,
we call such protocols \emph{semi-structured} or
$(*,\oplus)$-protocols.
For a Boolean function $F: X \times Y \to \set{0,1}$,
we use $C^{*,\oplus}(F)$ to denote the
deterministic communication complexity of $F$ by
such protocols.
Similarly, for a relation (search problem) $R\subseteq X\times Y\times W$
we use $C^{*,\oplus}(R)$ to denote the deterministic
communication complexity of such protocols solving $R$,
that is, when Alice receives $x\in X$ and Bob receives
$y\in Z$, the protocol outputs some $w\in W$ with
$(x,y,w)\in R$ or outputs $\bot$ if no such $w$ exists.
\begin{theorem}[Lifting theorem for semi-structured protocols]
\label{thm:liftingForSemiStructured}
Let $m \ge 4$ be an integer.
For every $f: \set{0,1}^N \to \set{0,1}$,
$$C^{*,\oplus}(f\circ \text{IND}_m^N)\ge \frac{1}{2} C^{dt}(f) \log_2 m.$$
Furthermore for every $R\subseteq Z^N\times W$,
$$C^{*,\oplus}(R\circ \text{IND}_m^N)\ge \frac{1}{2} C^{dt}(R)\log_2 m.$$
\end{theorem}
Let $\ensuremath \Pi$ be a $(*,\oplus)$-protocol for $R\circ \text{IND}_m^N$ of complexity
$C^{*,\oplus}(R)$.
Without loss of generality we can assume that $C^{*,\oplus}(R)\le N (\log_2 m +1)$.
Following the lifting theorem paradigm we prove \cref{thm:liftingForSemiStructured} by
showing how to produce a decision tree $T$ for $R$
of height at most that of $\ensuremath \Pi$ by simulating
$\ensuremath \Pi$.
\subsection{High level overview and invariants}
Since Bob is only allowed to communicate parity equations, we will follow the lifting
paradigm and maintain the set $\mathcal{Y}$ as an affine subspace over $\mathbb{F}_2^{[N]\times[m]}$.
We will also maintain the property that the codimension $d$ of $\mathcal{Y}$ is at most the total number of bits communicated during the protocol.
At every point in our simulation we will maintain
a set $\ensuremath{D}_\mathcal{Y}\subseteq [N]\times [m]$
of \emph{dependent} coordinates.
All other coordinates in $[N]\times [m]$ will be
\emph{free}.
We maintain $\mathcal{Y}$ of codimension $d$ as the
set of a solutions of a system $\mathcal{E}$ of $d$ affine equations over $\mathbb{F}_2$ in
\emph{row-reduced} form
$$\mathbf{M}\cdot y=\mathbf{b},$$
such that $\mathbf{M}$ (up to permutation of rows) is a $d\times d$ identity submatrix on the
columns $\ensuremath{D}_\mathcal{Y}$ that we have designated
as dependent coordinates.
It is immediate from this set-up that we have
the properties:
\begin{description}
\item[(A)] $|\ensuremath{D}_\mathcal{Y}|=\mathrm{codim}(\mathcal{Y})$.
\item[(B)] For every
total assignment to the free coordinates, there is a unique assignment to $\ensuremath{D}_\mathcal{Y}$ that extends it to an element of $\mathcal{Y}$.
\end{description}
Bob's communication of some parity function
$\oplus_{(i,j)\in S}\ y_{i,j}$ of his
input can add at most one new affine equation to $\mathcal{E}$, depending on whether or not the value of that parity function is already fixed on $\mathcal{Y}$.
There is no change to $\mathcal{E}$ if and only if the parity is in
$\textrm{span}(\mathcal{E})$, the $\mathbb{F}_2$
span of the parities defining $\mathcal{E}$.
As in the general lifting paradigm, we maintain a set
$I\subseteq [N]$ of \emph{fixed} indices\footnote{As in the discussion so far, to
keep notions separate we will use the term ``indices'' to refer to elements of $[N]$ and ``coordinates'' to refer to elements of $[N]\times[m]$.} on which there is a single fixed output for
$\text{IND}_m^I(\mathcal{X},\mathcal{Y})$.
In addition to the above, we also maintain the following
invariants.
\begin{description}
\item[(C)] For all indices that are not fixed, elements of $\mathcal{X}$ only point to free coordinates; that is, for every $i\in [N]\setminus I$, and every $x\in \mathcal{X}$ we have $(i,x_i)\notin \ensuremath{D}_\mathcal{Y}$.
\item[(D)] $\mathcal{X}$ has min-entropy rate at least
$\tau=1/2$ on $[N]\setminus I$.
\end{description}
Maintaining (C) is quite easy: Whenever we identify a new dependent coordinate $(i,j) \in [N]\times[m]$ in $\mathcal{Y}$, we simply update $\mathcal{X}$ by removing all $x\in \mathcal{X}$ with $x_i=j$.
We maintain (D) using the methods of G\"o\"os,
Pitassi, and Watson (GPW) to restore the
min-entropy rate whenever it falls too low.
Since the affine structure of $\mathcal{Y}$ allows for a precise definition of dependent coordinates, our lifting theorem differs from the GPW-style lifting theorems in its parameters and philosophy\footnote{GPW never makes queries based on Bob's communication, but we do!}. These differences allow us to overcome the dependence between $m$ and $N$ in such theorems.
\subsection{The Simulation Algorithm}
As we discussed in our high-level overview, we
maintain $\mathcal{Y}$ as an affine subspace of $(\set{0,1}^m)^N$ defined
by a set of linearly independent equations $\mathcal{E}$
in a row-reduced form that contain an identity matrix on the set
$\ensuremath{D}_\mathcal{Y}$ of dependent coordinates.
We need to be able to update this as new affine equations are added, either because of communication by Bob or because we have added some
$i$ to the set $I$ of fixed indices.
For this, we define a helper function
$\textbf{row-reduce}(\mathcal{E},\ensuremath{D}_\mathcal{Y},e)$ that takes
as input
\begin{itemize}
\item a set of row-reduced equations $\mathcal{E}$,
\item a set $\ensuremath{D}_\mathcal{Y}$
of coordinates for its dependent variables, and
\item a new affine equation $e$ linearly independent of
$\mathcal{E}$,
\end{itemize}
and uses Gaussian elimination to return a pair $(\mathcal{E}',(i,j))$ where
$\mathcal{E}'$ is equivalent to $\mathcal{E}\cup\set{e}$,
$(i,j)\notin \ensuremath{D}_\mathcal{Y}$ and $\mathcal{E}'$ is
row-reduced, as witnessed by the columns of $\ensuremath{D}_\mathcal{Y}\cup\set{(i,j)}$.
We note that when a new equation is introduced
while adding $i$ to the set of fixed
indices, the new equation $e$ will be of a particularly
simple form, namely $y_{i,j}=b$ where
$(i,j)\notin \ensuremath{D}_\mathcal{Y}$ by our maintenance of invariant (C), in which case
the new dependent coordinate returned will be
$(i,j)$.
\begin{sloppypar}
We follow a variant of the simulation algorithm of GPW\cite{DBLP:journals/siamcomp/GoosP018}, with a few modifications to identify and exclude dependent coordinates in $\mathcal{Y}$.
The algorithm uses a sub-routine \textbf{RestoreMinEntropyRateAndQuery} (see Algorithm~\ref{alg:restoreX}). This is essentially density restoration from GPW and makes sure that $\mathcal{X}$ has min-entropy rate at least $\tau=1/2$ by adding
fixed indices to $I$, adding queries to the decision tree and fixing some coordinate $y_{i,\alpha_i}$ to the query answer for $z_u$.
Note that GPW style lifting only uses this procedure to restore min-entropy rate at a node where Alice speaks, but
we also may need this when Bob speaks because we reduce $\mathcal{X}$ by
removing pointers to dependent coordinates.
Another difference in our version of density-restoration is that we only chose the first part in the partition (as we are doing deterministic lifting opposed to the randomized lifting in \cite{DBLP:journals/siamcomp/GoosPW20}).
\end{sloppypar}
\begin{algorithm}[tbp]
\DontPrintSemicolon
\caption{Simulation algorithm}
\label{algo:simulationAlgo}
\TitleOfAlgo{$\textbf{Query}_\ensuremath \Pi(z)$}
\KwData{$z\in \set{0,1}^N$, $\mathcal{X}=[m]^N$, $\mathcal{Y}= ( \set{0,1} )^N$, $\mathcal{E}=\varnothing$, $\ensuremath{D}_\mathcal{Y}=\varnothing$, $I=\varnothing$, $\rho=*^n$, protocol $\ensuremath \Pi$ for $R\circ \text{IND}_m^N$, $v$=root of $\ensuremath \Pi$. }
\KwResult{element of $R(z)$.}
\While{$v$ is not a leaf}{
Let $v_0,v_1$ be the children of $v$ following communication $0$ and $1$ respectively\;
\If{Bob speaks at $v$}
{Let the parity function at $v$ be $\oplus_{(i,j)\in S}\ y_{i,j}$\;
\eIf{$\oplus_{(i,j)\in S}y_{i,j} \in \textrm{span}(\mathcal{E})$}{
$v\leftarrow v_b$ for the unique $b$ such that
$\oplus_{(i,j)\in S}\ y_{i,j}=b$ for all $y\in \mathcal{Y}$\;
}{\tcp{Half of $\mathcal{Y}$ goes to $v_0$, half to $v_1$; we choose the smaller subtree.}
Choose $b\in \set{0,1}$ with subtree rooted at $v_b$ no larger than one rooted at $v_{1-b}$.\;
$\mathcal{Y} \leftarrow \set{y\in \mathcal{Y} \mid \oplus_{(i,j)\in S}\ y_{i,j}=b}$\;
$\left(\,\mathcal{E},(i^*,j^*)\,\right)\leftarrow \textbf{row-reduce}(\,\mathcal{E},\ \ensuremath{D}_\mathcal{Y}, \ \oplus_{(i,j)\in S}\ y_{i,j}=b\,)$\;
\textbf{add} $(i^*,j^*)$ to $\ensuremath{D}_\mathcal{Y}$\label{step:AddDependentCoordinate} \;
$\mathcal{X} \leftarrow \mathcal{X} \mid_{x_{i^*}\neq j^*}$ \tcp*[r]{Note: if $i^*\in I$ then $x_{i^*}\ne j^*$ already.}\label{step:updateXAvoidDependent}
$v\leftarrow v_b$
\;
}
}
\If{
Alice speaks at $v$ and partitions $\mathcal{X}$ into $\mathcal{X}^0 \cup \mathcal{X}^1$}{
Let $b\in \set{0,1}$ be such that $\card{\mathcal{X}^b}\geq \frac{1}{2} \cdot \card{\mathcal{X}}$\;
$\mathcal{X} \leftarrow \mathcal{X}^b$\label{step:chooseBiggerX}\;
$v\leftarrow v_b$\;
}
\If{$\textbf{min-entropy-rate}(\mathcal{X}) < \tau=1/2$}{
\textbf{RestoreMinEntropyRateAndQuery}($\mathcal{X},z$)\;
}
}
\Return{label of $v$}\;
\end{algorithm}
\begin{algorithm}[tbp]
\DontPrintSemicolon
\caption{Procedure \textbf{RestoreMinEntropyRateAndQuery}}
\label{alg:restoreX}
\TitleOfAlgo{\textbf{RestoreMinEntropyRateAndQuery}($\mathcal{X},z$)}
\KwData{$\mathcal{X} \subseteq [m]^N$, $z\in \{0,1\}^N$.}
\KwResult{Updates $\mathcal{X}$ to restore min-entropy rate to $\tau=1/2$ by fixing coordinates via queries to $z$.}
Let $I'\subseteq [N]\setminus I$ be a maximal set on
on which $\mathcal{X}$ has min-entropy rate $<\tau=1/2$\;
Let $\alpha_{I'}\in [m]^{I'}$ be such that $\Pr_{x\in \mathcal{X}}[ x_{I'}=\alpha_{I'}]>m^{-\tau |I'|}$ \;
$\mathcal{X} \leftarrow \set{x\in \mathcal{X}\mid x_{I'}=\alpha_{I'}}$ \label{step:updateXrestoredensity}\;
\textbf{Query} all coordinates in $I'$ and let $z_{I'}$ be the query answers\;
$\mathcal{Y} \leftarrow \set{y\in \mathcal{Y}\mid y_{(I',\alpha_{I'})}=z_{I'} }$\;
\ForEach{$i\in I'$}{
$\rho(i) \leftarrow z_{i}$\ \;
$\left(\,\mathcal{E},(i^*,j^*)\,\right)\leftarrow \textbf{row-reduce}(\,\mathcal{E},\ \ensuremath{D}_\mathcal{Y}, \ y_{i,\alpha_i}=\rho(i)\,)$\tcp*[f]{Note: $i^*=i$, $j^*=\alpha_i$}\;
\textbf{add} $(i,\alpha_i)$ to $\ensuremath{D}_\mathcal{Y}$
\label{step:updateRhoDueToXQuery}\;
}
$I\leftarrow I\cup I'$\;
\end{algorithm}
\subsection{Analysis of the simulation algorithm}
We first argue that $\mathcal{X}$ and $\mathcal{Y}$ are never empty during the run of our simulation algorithm. Thus, when the algorithm reaches a leaf node of $\ensuremath \Pi$ we can output a correct answer.
To do so we observe the following invariants on our simulation algorithm (\autoref{algo:simulationAlgo}).
\begin{lemma}[Invariants of the Simulation Algorithm (\autoref{algo:simulationAlgo})]\label{lemma:invariantsSimulationAlgo}
At the beginning of every iteration of the while loop in Algorithm~\ref{algo:simulationAlgo}, the following properties hold:
\begin{alphaenumerate}
\item \label{prop:path} $\rho$ defines the path in the decision tree $T$ that is the outcome of the queries and $\textrm{fixed}(\rho)=I$.
\item \label{prop:SetYequations} $\mathcal{Y}$ is the set of inputs satisfying $\mathcal{E}$ which is row-reduced on $\ensuremath{D}_\mathcal{Y}$.
\item\label{prop:SetXAvoidsDependent} For any $x\in \mathcal{X}$, and any $i\notin I$, $(i,x_i)$ is a free coordinate of $\mathcal{Y}$; that is $(i,x_i)\notin \ensuremath{D}_\mathcal{Y}$.
\item \label{prop:SetYunique} For every total assignment to the free coordinates $([N]\times [m])\setminus \ensuremath{D}_\mathcal{Y}$, there is a unique assignment to $\ensuremath{D}_\mathcal{Y}$ that extends it to an element of $\mathcal{Y}$. \item\label{prop:InvariantSetX} $\mathcal{X}$ has min-entropy rate at least $\tau$ on
$[N]\setminus I$
\end{alphaenumerate}
\end{lemma}
\begin{proof}
All but the last of the conditions of
\cref{lemma:invariantsSimulationAlgo} easily can be seen to
hold by inspection of \cref{algo:simulationAlgo,alg:restoreX}.
The last follows by the argument of GPW and follows from the maximality of the set $I'$ in \cref{alg:restoreX}.
It is easy to see that if $\mathcal{X}$ has non-zero min-entropy rate, then $\mathcal{X}$ is non-empty.
Moreover, since every element of $\mathcal{X}$ points only to free
coordinates in blocks outside of $I$ and the min-entropy on each block is large, $\mathcal{Y}$ must have many free coordinates outside
of $I$.
\end{proof}
We bound the number of queries $|I|$ by using a potential function equal to the deficiency of $\mathcal{X}_{[N]\setminus I}$.
Let $A$ be the number of bits spoken by Alice, and $B$
be the number of bits spoken by Bob in $\ensuremath \Pi$.
We analyze the change in $D_{\infty}(\mathcal{X}_{[N]\setminus I})$ due to updates of $\mathcal{X}$ and $I$:
\begin{itemize}
\item \autoref{step:updateXAvoidDependent} in Algorithm~\ref{algo:simulationAlgo}: removing $x_{i^*}=j^*$ from $\mathcal{X}$ for newly dependent $(i^*,j^*)$:\\
By \cref{lemma:invariantsSimulationAlgo}(\ref{prop:InvariantSetX}), we know that $\mathcal{X}$ has min-entropy rate at least $\tau=1/2$.
Thus, $\Pr_{x\sim \mathcal{X}}[x_{i^*}=j^*] \leq 1/m^{\tau}\le 1/2$ since $m\ge 4$ and $\tau=1/2$.
Consequently,
$\Pr_{x\sim\mathcal{X}}[x_{i^*}\neq j^*] \geq 1/2$.
So, by \cref{fact:conditioningMinEntropy}, $H_{\infty}(\mathcal{X} \mid_{x_{i^*}\neq j^*}) \geq H_{\infty}(\mathcal{X}) -1$.
Therefore, the change in $D_{\infty}(\mathcal{X}_{[N]\setminus I})$ is at most 1. This step is executed at most
$B$ times. (Note: For larger $m$ we could
maintain sharper bounds, but it seems that we don't need to do so.)
\item \autoref{step:chooseBiggerX} in Algorithm~\ref{algo:simulationAlgo}: choosing the more frequent bit of Alice to send:\\
This increases $D_{\infty}(\mathcal{X}_{[N]\setminus I})$ by at most 1. This step is executed $A$ times.
\item \autoref{step:updateXrestoredensity} and \autoref{step:updateRhoDueToXQuery} in Algorithm~\ref{alg:restoreX}: querying and fixing
coordinates $I'$ maximal for min-entropy loss:\\
First, \autoref{step:updateXrestoredensity}
increases $D_{\infty}(\mathcal{X}_{[N]\setminus I})$ by at most $\tau \cdot |I'| \cdot \log_2 m$ as shown
the proof of Lemma 3.5 in \cite{DBLP:journals/siamcomp/GoosPW20}.
Second, \autoref{step:updateRhoDueToXQuery} decreases
$D_{\infty}(\mathcal{X}_{[N]\setminus I})$ by precisely $|I'|\cdot \log_2 m$ since it adds
$|I'|$ blocks to $I$.
The net total of these changes is that
$D_{\infty}(\mathcal{X}_{[N]\setminus I})$ decreases by
at least $(1-\tau) \cdot |I'| \cdot \log_2 m$ in
this case.
\end{itemize}
Putting these together yields:
$$D_{\infty}(\mathcal{X}_{[N]\setminus I})\le A+B - (1-\tau)\cdot |I|\cdot \log_2 m.$$
Since $D_{\infty}(\mathcal{X}_{[N]\setminus I})\ge 0$ we must
have $$|I|\le \frac{A+B}{(1-\tau)\log_2 m}.$$
Since $\tau=1/2$, $A+B\ge 0.5 |I|\log_2 m$ and hence
$C^{*,\oplus}(R\circ \text{IND}_m^N)\ge A+B\ge 0.5\ C^{dt}(R) \log_2 m$.
\qed
We can strengthen the above in the case that each of Alice's
bits, like Bob's bits, either is irrelevant or splits
$\mathcal{X}$ exactly in half.
Then, as with our simulation of Bob's bits, we choose
to follow the side with the smaller protocol subtree.
We see that the paths followed in the
protocol $\ensuremath \Pi$ are of total length (in bits that matter to the simulation) at most the
logarithm of the size of $\ensuremath \Pi$.
In particular, this applies if $m$ is a power of 2 so that each $x_i$ is represented by a series of bits,
Alice's bits are
also parities, and we replace \autoref{step:updateXAvoidDependent} by constraining
one bit of $x_{i^*}$ that isn't already constrained to be different from the corresponding bit of $j^*$.
We write $L^{\oplus,\oplus}(R)$ for the number of
leaves (i.e., the size) of a protocol $\ensuremath \Pi$ for $R$ in which
both Alice and Bob only send parities, which we call
\emph{parity communication}.
Using this
obtain the following:
\begin{theorem}
\label{thm:fullparitylift}
$C^{dt}(R)$ is
$O(\log_m(L^{\oplus,\oplus}(R\circ\text{IND}_m^N)))$
\end{theorem}
\subsection{Parity decision trees and \texorpdfstring{Res$(\oplus)$}{Res(+)} proofs}
We can use the same ideas with small modifications to give a generic method for producing lower bounds for parity decision
trees from those for ordinary decision trees.
\begin{theorem}
\label{thm:pdt-lift}
For any sufficiently large $m$ that is a power of 2 and any function $f:\{0,1\}^N\rightarrow \set{0,1}$,
$C^{dt}_\oplus(f\circ\text{IND}_m^N)\geC^{dt}(f)$
and $\mathrm{size}^{dt}_\oplus(f\circ\text{IND}_m^N)\ge 2^{C^{dt}(f)}\ge \mathrm{size}^{dt}(f)$.
\end{theorem}
\begin{proof}
We follow the ideas of the proof of \cref{thm:fullparitylift} with a small modification that
combines the steps for Bob and for Alice as follows:
We maintain $\mathcal{X}$ as an affine subspace as before and
we maintain a set $\ensuremath{D}_\mathcal{Y}\subset [N]\times [m]$ of coordinates as before (though $\mathcal{Y}$ itself is not maintained), but now the equations that we maintain involving these coordinates
depend on the bits of the $x_i$ also.
At each parity that is not already implied, we row-reduce to remove the variables in $\ensuremath{D}_\mathcal{Y}$.
If a coordinate $(i^*,j^*)$ in $\mathcal{Y}$ remains, we choose it as
the new dependent coordinate and complete the row-reduction. We then apply the portion of the
simulation designated as Bob's simulation in order to
ensure that $x_{i^*}$ does not point to $j^*$.
If no such coordinate remains, then this becomes a
constraint on $\mathcal{X}$ and we apply the portion associated with Alice.
In either case, we add one defining equation for $\mathcal{X}$ for each bit that is sent that is not already
implied, so the deficiency of $\mathcal{X}$ is precisely this
number.
The same analysis shows that
$C^{dt}(f)$ is
$O(\log_m(\mathrm{size}^{dt}_\oplus(f\circ\text{IND}_m^N)))$
and hence $O(C^{dt}_\oplus(f\circ\text{IND}_m^N)/\log m)$.
By choosing $m$ a sufficiently large constant, we obtain
that $C^{dt}(f)\le \log_2(\mathrm{size}^{dt}_\oplus(f\circ\text{IND}_m^N))$ and hence
$\mathrm{size}^{dt}(f)\le 2^{C^{dt}(f)}\le \mathrm{size}^{dt}_\oplus(f\circ\text{IND}_m^N)$ and
$C^{dt}(f)\le C^{dt}_\oplus(f\circ\text{IND}_m^N)$.
\end{proof}
We can use this (in the form for relations, which we could easily have stated above) to show that we can convert each $k$-CNF $\varphi$ to an $O(k)$-CNF $\varphi\circ \text{IND}_m^N$ that requires tree-like $Res(\oplus)$ refutations for $\varphi\circ \text{IND}_m^N$ that are at least linear in the size of tree-like resolution refutations for $\varphi$.
\begin{corollary}
For any sufficiently large integer $\ell$, $m=2^\ell$,
and any unsatisfiable $k$-CNF formula with $M$ clauses on $N$ Boolean variables,
$\varphi\circ \text{IND}_m^N$ is a $k(\ell+1)$-CNF formula with $M'=m^k M$ clauses on
$N'=N(\ell+m)$ variables that requires
$\mathrm{tree}_{Res(\oplus)}(\varphi\circ\text{IND}_m^N)\ge\mathrm{tree}_{Res}(\varphi)\ge 2^{\mathrm{width}_{Res}(\varphi)-k}$.
\end{corollary}
\begin{proof}
By \cref{prop:reslin2}, for any minimal tree-$Res(\oplus)$ refutation of
$\varphi\circ \text{IND}_m^N$ there is an isomorphic parity decision tree solving the search problem
$\mathrm{Search}_{\varphi\circ \text{IND}_m^N}$.
Using the form of \cref{thm:pdt-lift} for relations we can
convert a parity communication protocol for $\mathrm{Search}_{\varphi\circ \text{IND}_m^N}$ into one of at most the same size that solves the
search problem $\mathrm{Search}_\varphi$, since each correct output of $\mathrm{Search}_{\varphi\circ \text{IND}_m^N}$ yields the name of a violated clause
of $\varphi\circ \text{IND}_m^N$ that corresponds to a unique clause of
$\varphi$ and can be output by the ordinary decision tree.
The final result follows using the equivalence of decision trees
for $\mathrm{Search}_\varphi$ and tree-resolution refutations of $\varphi$ from \cref{prop:dpll} and the tree-size/width
relationship from \cref{prop:bsw}.
\end{proof}
We note that Itsykson and Kojevnikov~\cite{DBLP:conf/mfcs/ItsyksonS14,DBLP:journals/apal/ItsyksonS20}
previously used a much more specialized lifting theorem from~\cite{bps:kfoldtseitin-journal} for the specific
case of Tseitin formulas to give tree-like $Res(\oplus)$ lower bounds. Our
new simple method is much more general and yields a large class of hard formulas.
We also note that Huynh and Nordstr\"{o}m~\cite{DBLP:conf/stoc/HuynhN12} gave lifting theorems for a variety of other proof systems using constant-size index gadgets (indeed with $m=3$) but these only yield good bounds for a restricted class of formulas whose search
problems have high ``critical block sensitivity".
\section{Preliminaries}
\paragraph*{Notation:} For a set of vectors (or a distribution $\mathcal{X}$) on $U^N$ and $I\subseteq [N]$, we use $\mathcal{X}_I$ to denote
the projection of $\mathcal{X}$ onto the coordinates in $I$.
For a function $h$ on $U$, we let $h^I(\mathcal{X})$
denote the set of all possible vectors of outputs of $h^I$ on
$\mathcal{X}_I$; if this set is a singleton $w$ we abuse notation and simply define the value to be $w$.
\paragraph*{Information theory:}
We use several definitions for forms of entropy:
\begin{definition}The \emph{entropy deficiency} (sometimes simply \emph{deficiency}) of a distribution $\mathcal{X}$ on
a universe $U$, $D_{\infty}(\mathcal{X})$, is
$\log_2 |U|-H_2(\mathcal{X})$.
For a subset $\mathcal{V}\subseteq U$, the deficiency of $\mathcal{V}$ is that of the uniform
distribution on $\mathcal{V}$.
In particular, for example, the deficiency of a set of inputs $\mathcal{Y} \subseteq (\set{0,1}^m)^N$ of Bob satisfies
$$2^{-D_{\infty}(\mathcal{Y})}=\frac{ \card{\mathcal{Y}} } { 2^{m \cdot N} }.$$
\end{definition}
\begin{definition}
The \emph{min-entropy} of a distribution
$\mathcal{X}$ on $U$,
$H_\infty(\mathcal{X})$, is
$$\min_{x\in U}\log_2(1/\Pr_{\mathcal{X}}(x)).$$
For a distribution $\mathcal{X}$ on a set $U^N$, the
\emph{min-entropy rate} of $\mathcal{X}$ is the maximum $\tau$ such that for every $J\subseteq [N]$,
$H_\infty(\mathcal{X}_J) \geq \tau |J|\log_2 |U|$ or,
equivalently, such that for all $\alpha_J\in U^J$,
$$\Pr_{x\sim \mathcal{X}}[x_J=\alpha_J]\le |U|^{-\tau\cdot |J|}.$$
\end{definition}
We use the following fundamental fact about the effect of conditioning on the min-entropy of a random variable.
\begin{fact}\label{fact:conditioningMinEntropy}
Let $\mathcal{X}$ be a random variable and let $E$ be an event. Then $H_{\infty}(\mathcal{X} \mid E) \geq H_{\infty}(\mathcal{X}) - \log_2 (1/\Pr[E])$.
\end{fact}
\paragraph*{Probability:}
We will use the following nice bound on the median of
any binomial distribution.
\begin{proposition}[\cite{kb:binomial-median}]
\label{prop:binomomial-median}
The median of a binomial distribution $B(n,p)$ lies between
$\lfloor np\rfloor$ and $\lceil np\rceil$.
\end{proposition}
\paragraph*{Linear algebra:}
We use row-reduced form to represent matrices in our simulation theorems.
\begin{definition}[Row-reduced matrices]
\label{def:row-reduced}
A matrix $M$ with $r$ rows is said to be \emph{row reduced} if it contains an $r\times r$ identity
submatrix.
\end{definition}
\paragraph*{Parity decision trees
and $Res(\oplus)$ refutations:}
A \emph{parity decision tree} over a set of Boolean variables
$Z$ defining a space $\set{0,1}^Z$ of Boolean vectors is a rooted binary tree in which each internal node is labeled by a parity of variables from $Z$ with out-edges labeled 0 and 1 respectively.
Each leaf is labeled by an output value. Such a decision tree computes a function on $\set{0,1}^Z$.
For a function or relation $f$ on Boolean inputs, let $C^{dt}(f)$ and $\mathrm{size}^{dt}(f)$ be the
minimal height and size, respectively of any decision tree computing $f$ and let $C^{\oplus dt}(f)$ and
$\mathrm{size}^{\oplus(dt)}(f)$ be the corresponding
measures for parity decision trees.
Before defining the proof system $Res(\oplus)$ and its relationship to parity decision trees, we first review the resolution proof system and its relationship to ordinary decision trees.
A \emph{resolution} ($Res$) refutation of an unsatisfiable CNF formula $\varphi$ on variables $Z$
is a sequence of clauses ending in the empty clause
$\bot$ in which each clause is either
a clause of $\varphi$, or follows from two prior
clauses using the inference rule
$$\frac{A\lor z_i,\ B\lor \overline {z_i}}{A\lor B}$$
for some variable $z_i\in Z$; we say that this step
\emph{resolves} on variable $z_i$.
This sequence yields a
directed acyclic graph (dag) of in-degree 2 each of whose nodes is labeled by a clause on the variables in $Z$, with sources labeled by clauses of $\varphi$ and sink
labeled by $\bot$.
The resolution refutation is \emph{tree-like} if this
associated dag is a tree and the associated refutation is
called a \emph{tree-resolution} refutation of $\varphi$.
For an unsatisfiable CNF formula $\varphi$, let $\mathrm{tree}_{Res}(\varphi)$ be the minimum size of
any tree-resolution refutation of $\varphi$.
Further, let $\mathrm{width}_{Res}(\varphi)$ denote the minimum over all
resolution refutations of $\varphi$ of the length of the longest clause
in the refutation.
We have the following result of Ben-Sasson and Wigderson~\cite{DBLP:journals/jacm/Ben-SassonW01}.
\begin{proposition}
\label{prop:bsw}
For any CNF formula $\varphi$ with clause-size at most $k$,
$\mathrm{tree}_{Res}(\varphi)\ge 2^{\mathrm{width}_{Res}(\varphi)-k}$.
\end{proposition}
Every unsatisfiable CNF formula $\varphi$ yields an
associated total search problem $\mathrm{Search}_\varphi$ which
takes as input an assignment $z\in\set{0,1}^Z$ and produces the name of a clause that
is falsified by $z$.
\begin{proposition}
\label{prop:dpll}
Given any unsatisfiable formula $\varphi$,
minimal tree-resolution refutations of $\varphi$ and
decision trees solving $\mathrm{Search}_\varphi$ are isomorphic.
This isomorphism identifies nodes that resolve on a
variable $z_i$ with those that branch on variable $z_i$.
\end{proposition}
Each node in a decision tree naturally corresponds to the sub-cube of the input set $\set{0,1}^Z$ given by the constraints on the path to the node from the root.
Similarly, any clause $C$ can be identified with a sub-cube of $\set{0,1}^Z$ consisting of the set of all inputs falsified by $C$.
We say that a clause $C$ is a \emph{weakening} of a clause $A$ iff there is some clause $B$ such that $C=A\lor B$; alternatively this is equivalent to saying
that the sub-cube corresponding to $C$ is contained in
the sub-cube corresponding $A$.
With this correspondence, the isomorphism in the above
proposition means that the sub-cube for each node in the
decision tree corresponds to a weakening of the clause at the isomorphic node in the tree-resolution refutation.
A \emph{$Res(\oplus)$ refutation} of an unsatisfiable CNF formula $\varphi$ in variables $Z$ is a sequence of affine subspaces of $\mathbb{F}_2^Z$ ending in
the subspace $\mathbb{F}_2^Z$ such that each subspace in the list is either
the sub-cube corresponding to a clause of $\varphi$ or follows from two prior
subspaces $A$ and $B$ via the inference rule:
$$\frac{A,\ B}{C}\qquad \mbox{if } C\subseteq A\cup B.$$
(Alternatively, one can replace each subspace by an expression for its dual, namely a disjunction of parity equations over $\mathbb{F}_2$, each of which is the negation of one of a set of linear equations defining the affine subspace.
Therefore, each line is a clause over parities and the subspace is the set
of inputs that falsifies it.
In this way, the single inference rule generalizes the weakening rule of resolution and generalizes resolving on a single
literal to resolving on a parity of variables; it is not hard to see that the subspace $C$ must be contained
entirely in $A$ or in $B$ unless there is a unique
linear constraint defining $A$ whose negation is a defining equation for $B$.
This representation is not unique since there may be many different choices
of defining equations for an affine subspace, but we assume that the
proof is representation independent.
As noted by Isykson and Sokolov~\cite{DBLP:conf/mfcs/ItsyksonS14,DBLP:journals/apal/ItsyksonS20},
the semantic view of $Res(\oplus)$ refutations we have presented is a standard proof system in the sense of Cook and Reckhow~\cite{DBLP:journals/jsyml/CookR79} since inference is explicitly verifiable in polynomial time.)
As with resolution refutations, we can define the dag of indegree (at most) 2 associated with a $Res(\oplus)$
refutation and let \emph{tree-$Res(\oplus)$} be the proof system consisting
of $Res(\oplus)$ refutations whose associated dag is a tree.
For an unsatisfiable CNF formula $\varphi$, let $\mathrm{tree}_{Res(\oplus)}(\varphi)$ be the minimum size of
any \emph{tree-$Res(\oplus)$} refutation of $\varphi$.
Using the analogous ideas to the isomorphism between
decision trees and minimal tree-resolution proofs, Itsykson and
Sokolov proved the following correspondence:
\begin{proposition}\cite{DBLP:conf/mfcs/ItsyksonS14,DBLP:journals/apal/ItsyksonS20}
\label{prop:reslin2}
Given any unsatisfiable formula $\varphi$,
minimal tree-$Res(\oplus)$ refutations of $\varphi$ and
parity decision trees solving $\mathrm{Search}_\varphi$ are isomorphic.
This isomorphism identifies nodes that resolve on a
parity function $\oplus_S(z)$ with those that branch on $\oplus_S(z)$.
\end{proposition}
\paragraph*{Lifting CNF formulas with $\text{IND}_m$:}
There are a few options for how to do this.
Since we will use this when $m=2^\ell$ is a constant, we choose a simple option that has $N\ell$ Boolean variables $x_{i,j'}$ for $j'\in \set{0,\ldots, \ell-1}$ and $i\in [N]$ and $Nm$ Boolean variables $y_{i,j}$ for $j\in\set{0,\ldots,m-1}$ and $i\in [N]$.
As usual, the interpretation we have for $\text{IND}_m^N$ is that $z_i=y_{i,x_{i,\ell-1}...x_{i,0}}$.
Given a $k$-CNF formula $\varphi$ in $N$ variables $Z=\set{z_1,\ldots,z_N}$,
we define an $(\ell+1)k$-CNF formula $\varphi\circ \text{IND}_m^N$ on
the $x_{i,j}$ and $y_{i,k}$ variables as follows:
Each clause $(z_{i_1}^{b_1}\lor \cdots z_{i_k}^{b_k})$ of
$\varphi$ is replaced by $m^k$ clauses of length
$(\ell+1) k$, one for each
tuple $(j^{(1)},\ldots,j^{(k)})$, which expresses the
statement that if the $\ell$ bits $x_{i_1,*}$ encode
value $j_1$, those of $x_{i_2,*}$ encode $j_2,...$ and
those of $x_{i_k,*}$ encode $j_k$, then
$y_{i_1,j_1}^{b_1}\lor \cdots y_{i_k,j_k}^{b_k}$ must be
true.
With this definition, each clause of $\varphi\circ\text{IND}_m^N$
corresponds to a unique clause of $\varphi$.
Moreover, a falsified clause of $\varphi\circ\text{IND}_m^N$ on one of its input vectors
yields a falsifying assignment to the corresponding
clause of $\varphi$ under the vector of $z$ values
given by $\text{IND}_m^N$.
| {'timestamp': '2022-12-01T02:20:35', 'yymm': '2211', 'arxiv_id': '2211.17211', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17211'} | arxiv |
\section{Introduction}
Reinforcement learning (RL) has demonstrated impressive performance in robotic control in recent years. Many real-world systems are subject to safety constraints.
As a result, safe RL has recently received a lot of attention, although there are different definitions of ``safety'' \cite{garcia2015comprehensive,brunke2022safe}. We limit our discussion to safe RL that aims to ensure satisfaction of {\it hard state constraints} all the time
during both training and deployment.
Among different safe RL paradigms, a commonly used one is to leverage {\it safety filters} (SFs) to constrain the actions of RL agents and modify them whenever necessary to ensure satisfaction of safety constraints. The advantages of this paradigm mainly lie in its flexibility, i.e., a safety filter can often work with many existing RL algorithms without (many) modifications to the RL algorithms. Along this line, researchers have proposed different safety filters based on shielding \cite{alshiekh2018safe}, control barrier functions (CBFs) \cite{cheng2019end, ohnishi2019barrier,SafembRL2022}, Hamilton-Jacobi reachability (HJR) \cite{fisac2018general-safety}, and model predictive safety certification (MPSC) \cite{wabersich2021probabilistic-safety}. Among these different SFs, the shielding SF \cite{alshiekh2018safe} only works for discrete state and action spaces.
All other SFs are model-based, and hinge on Gaussian process regression (GPR) to learn the uncertain dynamics together with quantifiable learned model error for robust safety assurance. When applying these SFs to model-free RL, the resulting safe RL framework will not be model-free anymore due to the involvement of model learning. More importantly, due to the reliance on model learning, when the learned model is poor due to insufficient data, existing model-based SFs will be overly conservative, preventing efficient exploration of RL agents. Additionally, it is well known that GPR is computationally demanding (standard GPR model training involves computing the inverse of an $N\times N$ covariance matrix, where $N$ is the number of data points). As a result, GPR is probably not scalable to high-dimensional systems.
\begin{figure}
\centering
\includegraphics[width=0.6\linewidth]{figs/DOB-RL.pdf}
\caption{Proposed safe RL framework via using DOB-CBF. At time step $t$, the RL agent action $u^{\text{RL}}_t$ potentially violates the predefined safety constraints. Hence, a DOB-CBF safe action filter will render a $u^{\text{safe}}_t$ based on $u^{\text{RL}}_t$, precomputed estimation error bound $\gamma$ and disturbance estimation $\hat{d}$. Then, $u^{\text{safe}}_t$ is applied to interact with the environment to enforce safety during and after the policy training.}
\label{fig:framework}
\vspace{-6mm}
\end{figure}
This paper presents a safe model-free RL approach using disturbance observer (DOB) based CBFs introduced in \cite{zhao2020aR-cbf}. As illustrated in Figure \ref{fig:framework}, our approach leverages a DOB to accurately estimate the value of the lumped disturbance at each time step with a pre-computable estimation error bound (EER). The estimated disturbance together with the EEB is incorporated into a quadratic programming (QP) module with robust CBF conditions that generates safe actions at each step by minimally modifying the RL actions.
Compared to existing CBF-based safe RL approaches, e.g., \cite{cheng2019end, ohnishi2019barrier,SafembRL2022}, our approach does not need model learning of the uncertain dynamics (although a nominal model is needed), facilitating real {\it model-free} RL. Additionally, it enables more efficient exploration and higher sample efficiency, thanks to the accurate estimation provided by the DOB, unlike GPR whose prediction performance can be quite poor due to insufficient data at the initial learning stage. Finally, it is much more computationally-efficient compared to existing approaches based on GPR. The efficacy of the proposed approach is demonstrated on a unicyle and a 2D quadrotor in simulations, in comparison with an existing method.
This article is organized as follows. Section \ref{preliminary} includes preliminaries related to DOBs, CBFs, RL. Section \ref{main_approach} presents the proposed safe RL framework, while Section \ref{simulation} includes the simulation results for verifying the proposed framework using a unicycle and a 2D quadrotor.
\section{Preliminary} \label{preliminary}
We consider a nonlinear control-affine system with uncertainties in the form of
\begin{equation}{\label{eq:dynamics}}
\dot{x}(t) = f(x(t)) + g(x(t))u(t) + d(x(t)),
\end{equation}
where $x(t) \in \mathcal{X} \subset \mathbb{R}^n$ denotes the state vector, $u(t) \in \mathcal{U} \subset \mathbb{R}^m$ is the input vector, $\mathcal{X}$ and $\mathcal{U}$ are compact sets, $ f: \mathbb{R}^n \to \mathbb{R}^n$ and $g: \mathbb{R}^n \to \mathbb{R}^m$ are known locally Lipschitz-continuous functions, and $d: \mathbb{R}^n \to \mathbb{R}^n$ is an unknown function that captures uncertain dynamics.
\begin{assumption}\label{assump:lipschitz-bound-d}(\cite{zhao2020aR-cbf})
There exist positive constants $l_d$ and $b_d$ such that for any $x,y\in \mathcal{X}$, the following inequalities hold:
\begin{align}
\|d(x)-d(y)\| & \leq l_d\|x-y\|, \\
\|d(0)\| & \leq b_d.
\end{align}
\end{assumption}
Moreover, the constants $l_d$ and $b_d$ are known.
\begin{remark} \cref{assump:lipschitz-bound-d} {\it does not assume} that the system states stay in $\mathcal{X}$ (and thus are bounded). We will leverage a DOB-CBF to ensure $x$ stays in $\mathcal{X}$ later.
\cref{assump:lipschitz-bound-d} merely indicates that the uncertain function $d(x)$ is {\it locally Lipschitz} continuous with a known {\it bound} on the Lipschitz constant {\it in the compact set $\mathcal{X}$} and is bounded by a known constant at the origin.
\end{remark}
\subsection{Reinforcement Learning}
Reinforcement learning aims to find the optimal policy $\pi^{*}$ in an environment which can be formulated as a Markov decision process (MDP). In this work, an MDP is defined by a tuple $(\mathcal{S}, \mathcal{A}, p, r)$, where state space $\mathcal{S}$ and action space $\mathcal{A}$ are continuous. Given the current state $s_{t}$, action $a_{t}$, and the probability of state transition $p: \mathcal{S} \times \mathcal{S} \times \mathcal{A} \to [0,\infty)$ represents the probability density of the succeeding state $s_{t+1}$. The environment provides a reward $r$ for each transition.
Soft actor-critic \cite{Tuomassac} is a state-of-the-art model-free RL algorithm that benefits policy training in two essential parts. SAC uses an off-policy formulation that reuses historical data to improve sample efficiency. Furthermore, it utilizes entropy maximization to improve the stability of training performance. In general, SAC aims to maximize an entropy objective which is formed as $\pi^*=\arg \max \sum_{t=0}^{T} \mathbb{E}_{\left(x_t, u_t^{R L}\right) \sim \rho_\pi}\left[r\left(x_t, u_t^{R L}\right)+\alpha \mathcal{H}\left(\pi\left(\cdot \mid x_t\right)\right)\right]$, where $\alpha$ is a positive parameter to determine the relative importance of the entropy term against the reward, $\mathcal{H}(\cdot)$ is the entropy term which incentivizes exploration, $\rho_\pi$ denotes the state distribution induced by the policy $\pi$, and $T$ is the termination time.
\subsection{Control Barrier Function}
The control barrier function in~\cite{ames2014control} is an online method to enforce the safety of the dynamical system. It instantly filters the unsafe part of control input from any baseline controller. Typically, control barrier functions consider non-disturbed (nominal) dynamics
\begin{equation}{\label{eq:nominal-dynamics}}
\dot{x}(t) = f(x(t)) + g(x(t))u(x(t)).
\end{equation}
A set $\mathcal{C}$ is forward invariant for (\ref{eq:nominal-dynamics}), if its solutions starting at any $x(t_0) \in \mathcal{C}$ lead to $x(t) \in \mathcal{C}$ for $\forall t \geq t_{0}$. Further, define a continuously differentiable function $h$ that satisfies $\mathcal{C} := \{x \in \mathbb{R}^n : h(x)\geq 0\}$. Nevertheless, in this work, we are looking for a method to make CBFs secure the system in a disturbed environment. Therefore, we utilize the control barrier functions to ensure system safety during policy training.
\begin{definition}{\label{def:rcbf}}(First-Order Control Barrier Function with Perturbed System Dynamics~\cite{zhao2020aR-cbf}).
Given a set $\mathcal{C}$ which is forward invariant for (\ref{eq:dynamics}), $h(x)$ is a valid robust control barrier function for (\ref{eq:dynamics}) if there exists an extended class $\mathcal{K}$ function\footnote{A function $\beta:(-b, a)\to (-\infty, \infty)$ is said to belong to extended class $\mathcal{K}$ for some $a,b > 0$ if it is strictly increasing and $\beta(0)=0$.} $\beta$ s.t. $\forall x \in \mathcal{C}$
\begin{equation}
\sup _{u \in \mathcal{U}}\left\{L_f h(x)+L_g h(x) u + h_{x}(x)d(x)\right\} \geq-\beta(h(x))\label{eq:rcbf},
\end{equation}
\end{definition}
where $L_f$ and $L_g$ are the Lie derivatives w.r.t. $x$ along $f$ and $g$, respectively, and $h_{x}$ denotes the partial derivative of $h(x)$ with respect to $x$. In addition to the first-order CBF, CBF with higher control input relative degree\footnote{The relative degree of a differentiable function $h: \mathbb{R}^n \to \mathbb{R}$ with respect to \ref{eq:dynamics} is the number of times we need to differentiate it along the \ref{eq:dynamics} and state $x$ until the control $u$ explicitly shows up.} as proposed by \cite{Tan2022HighOrderBF} and \cite{tan-high-order-cbf} are further considered.
\begin{assumption}\label{disturb-rel-degree}
The disturbance relative degree is equal to the relative degree of control input $u$.
\end{assumption}
We further define a sequence of functions $\phi_{i}: \mathbb{R}^n \to \mathbb{R}, i \in \{1,...,m\}$ as:
\begin{equation}{\label{eq:phi}}
\phi_{i}(x) = \dot{\phi}_{i-1}(x) + \beta_{i}(\phi_{i-1}(x)), \phi_{0} = h(x).
\end{equation}
Further, an associate sequence of sets can be defined as:
\begin{equation}{\label{eq:sets-c}}
\mathcal{C}_i=\left\{x \in \mathbb{R}^n: \phi_{i-1}(x) \geq 0\right\}, i \in\{1, \ldots, m\}.
\end{equation}
\begin{definition}{\label{def-horcbf}} (High Order Control Barrier Function with Perturbed System Dynamics (HOCBF)).
Consider a sequential function $\phi_{i}(x)$ in (\ref{eq:phi}) and a sequential set $\mathcal{C}_i, i \in \{1,...,m\}$ defined in (\ref{eq:sets-c}). A $m^{th}$ order differentiable function $h: \mathbb{R}^n \to \mathbb{R}$ is a high order robust control barrier function of relative degree m for (\ref{eq:dynamics}) if there exist extended differentiable class $\mathcal{K}$ functions $\beta_{i}, i \in \{1,...,m\}$ such that
\begin{equation}
\sup _{u \in U}\mathcal{L}_f^m h(x)+\mathcal{L}_g \mathcal{L}_f^{m-1} h(x) u+[\mathcal{L}_f^{m-1} h(x)]_{x} d(x)+O(h(x))+\beta_m\left(\phi_{m-1}(x)\right) \geq 0\label{eq:horcbf},
\end{equation}
\end{definition}
where $L^{m-1}_f$ is the $m-1$th partial Lie derivative w.r.t. $x$ along $f$, and $L^m_f$ and $L_g L^{m-1}_f$ are the Lie derivatives of $L^{m-1}_f$ w.r.t. $x$ along $f$ and $g$, respectively. In (\ref{eq:horcbf}), $O(\cdot)$ is given by $O(h(x))=\sum_{i=1}^{m-1} \mathcal{L}_f^i\left(\beta_{m-i} \circ \phi_{m-i-1}\right)(x), \forall x \in \mathcal{C}_{1}\cap ..., \cap \mathcal{C}_{m}$.
\begin{remark}
The true uncertainty $d$, in Definitions \ref{def:rcbf} and \ref{def-horcbf}, is not accessible in hardware applications. Therefore, it is impossible to evaluate whether a function obeys the constraints in (\ref{eq:rcbf}) or (\ref{eq:horcbf}).
\end{remark}
This issue is also discussed by \cite{zhao2020aR-cbf}. One way is to use a GP model to learn and estimate the disturbance $d$. Another direction is using the worst-case bound on the disturbance $d$ to derive a sufficient and provable condition for (\ref{eq:rcbf}) or (\ref{eq:horcbf}). The worst-case bound of first-order CBF has been proved by \cite{zhao2020aR-cbf}. We modified the worst-case bound in \cite{zhao2020aR-cbf} and extended the worst-case bound to the high-order CBF case in Section \ref{section-pc}
\subsection{Disturbance Observer (DOB)}
The piecewise-constant (PC) law in \cite{naira2010l1book-nh} has been demonstrated to work as an essential part of an adaptive controller for disturbance compensation and has shown impressive performance in many applications \cite{yikunRL1-ieee}, \cite{zhao2020robust}. The PC law typically contains two components, i.e., a state predictor that predicts the states of nominal dynamics (\ref{eq:nominal-dynamics}) and a piecewise-constant estimation law to estimate the uncertainty. For the disturbed system (\ref{eq:dynamics}), the state predictor can be formed as follows:
\begin{equation}{\label{state-predictor}}
\dot{\hat{x}}(t) = f(x) + g(x)u + \hat{d}(t) - a\Tilde{x},
\end{equation}
where $\Tilde{x} = \hat{x} - x$ denotes the prediction error, $a > 0$ is a constant, and $\hat{d}(t)$ is the estimated disturbance. For the sake of obtaining the estimation of $d(x)$, the piecewise-constant adaptive law is introduced, and the uncertainty estimation updates depend on
\begin{equation}{\label{eq:pc-law}}
\left\{\begin{aligned}
\hat{d}(t) &=\hat{d}(i T), \quad t \in[i T,(i+1) T), \\
\hat{d}(i T) &=-\frac{a}{e^{a T}-1} \tilde{x}(i T), i=0,1,...,
\end{aligned}\right.
\end{equation}
where $T$ is the sampling time of estimation.
Given the lumped uncertainty $d(x)$ is bounded as $\|d(x)\|\leq\theta$, the PC law error bound follows the succeeding definition.
\begin{lemma} (Estimation Error Bound \cite{zhao2020aR-cbf})\label{lemma:est_error_bound}
Given the system (\ref{eq:dynamics}), and the estimation law in (\ref{state-predictor}) and (\ref{eq:pc-law}), subject to Assumption \ref{assump:lipschitz-bound-d}, the estimation error can be bounded as
\begin{equation}
\begin{aligned}
\|\hat{d}(t)-d(x(t))\| &\leq \begin{cases}\theta, & \forall 0 \leq t<T, \\ \gamma(T), & \forall t \geq T,\end{cases} \\
& \lim _{T \rightarrow 0} \gamma(T)=0,\label{eq:error-bound}
\end{aligned}
\end{equation}
\end{lemma}
where $\gamma(T)$ denotes the error bounds for all $t \geq T$.
\section{Main Approach}\label{main_approach}
This section introduces a disturbance-observer-based high-order control barrier function framework for safe action generation with pre-defined and reducible error bounds. We prove that the uncertainty estimation could be utilized to formulate a revamped version of the high-order CBF in Definition \ref{def-horcbf}. Then, we propose the DOB-CBF-based safe RL scheme (DOB-CBF-RL) for ensuring safety of RL policy.
\subsection{High-order DOB-Based Control Barrier Function (DOB-CBF)} \label{section-pc}
Given the estimation error bound in Lemma \ref{lemma:est_error_bound}, we consider the worst-case bound on the uncertainty $d$. First, we develop the bound for $\|\hat{d}(t)\|$. In (\ref{eq:error-bound}), it is obvious that $\|\hat{d}(t)-d(x(t))\| \geq \|\hat{d}(t)\| - \|d(x(t))\|$. Given the disturbance bound $\|d(x(t))\|\leq \theta$ and the estimation error bound in (\ref{eq:error-bound}), we have $\|\hat{d}(t)\| \leq \theta + \gamma$ for any $t\geq T$. Hence, the worst-case bound on $d$ is straightforward to show that $[\mathcal{L}_f^{m-1} h(x)]_{x}d(x)\leq\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|\|d(x)\|\leq\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|\|d(x) + \hat{d}(t)- \hat{d}(t)\|\leq \|[\mathcal{L}_f^{m-1} h(x)]_{x}\|(\|d(x) - \hat{d}(t)\|+ \|\hat{d}(t)\|)\leq\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|(\theta +2\gamma(T))$. Therefore, the following lemma holds.
\begin{lemma}
A $m^{th}$ order differentiable function $h: \mathbb{R}^n \to \mathbb{R}$ is a high order robust control barrier function of relative degree m for (\ref{eq:dynamics}) if there exist extended class $\mathcal{K}$ functions $\beta_{i}, i \in \{1,...,m\}$ such that
\begin{equation}\label{worst-bound}
\sup _{u \in U}\mathcal{L}_f^m h(x)+\mathcal{L}_g \mathcal{L}_f^{m-1} h(x) u-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| (\theta+2\gamma(T))+O(h(x))+\beta_m\left(\phi_{m-1}(x)\right) \geq 0,
\end{equation}
for all $x \in \mathcal{C}_{1}\cap ..., \cap \mathcal{C}_{m}$.
\end{lemma}
It is obvious that if a control input $u$ is a solution for (\ref{worst-bound}), it also satisfies (\ref{eq:horcbf}). We next define
\vspace{-5mm}
\begin{equation}\label{cond1}
\mathcal{K}(t, x, u) \triangleq L^{m}_f h(x)+L_gL^{m-1}_f h(x) u+O(h(x))+[\mathcal{L}_f^{m-1} h(x)]_{x} \hat{d}(t)-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| \gamma(T).
\end{equation}
Then, the main theorem of the proposed approach is introduced as follows.
\begin{theorem}{\label{theorem1}}
Suppose the condition (\ref{worst-bound}) holds; then the condition
\begin{equation}
\sup _{u \in U} \mathcal{K}(t, x, u) \geq-\beta_m\left(\phi_{m-1}(x)\right){\label{condition-thm1}}
\end{equation}
is a sufficient condition for (\ref{eq:horcbf}), and a necessary condition for (\ref{eq:horcbf}) for any $t\geq T$ when $T \to 0$.
\end{theorem}
\begin{proof} We first prove that condition (\ref{condition-thm1}) is sufficient for (\ref{eq:horcbf}). Comparing (\ref{eq:horcbf}) and (\ref{condition-thm1}), it is only necessary to prove that $[\mathcal{L}_f^{m-1} h(x)]_{x}d(x)\geq[\mathcal{L}_f^{m-1} h(x)]_{x}\hat{d}(t)-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|\gamma(T)$ for any $t\geq T$. From (LHS) of preceding inequality, we have
$[\mathcal{L}_f^{m-1} h(x)]_{x}d(x) = \mathcal{L}_f^{m-1}(d(x) + \hat{d}(t) - \hat{d}(t))\\
\geq \mathcal{L}_f^{m-1}\hat{d}(t) - \|[\mathcal{L}_f^{m-1} h(x)]_{x}|\|d(x) - \hat{d}(t)\|\geq \mathcal{L}_f^{m-1}\hat{d}(t) - \|[\mathcal{L}_f^{m-1} h(x)]_{x}\|\gamma(T)$.
We next prove the necessity. When $T$ tends to $0$, $\gamma(T)\to 0$ according to (\ref{eq:error-bound}), and thus $\hat{d}(t)\to d(x)$ for any $t\geq T$, which indicates that (LHS) of (\ref{eq:horcbf}) is equal to the (LHS) of (\ref{condition-thm1}). Consequently, the necessity for any $t \geq T$, as $T\to 0$, is proved.
\end{proof}
We further discuss whether the condition (\ref{worst-bound}) is sufficient for condition (\ref{condition-thm1}) to hold. Comparing (\ref{worst-bound}) and (\ref{cond1}), we only need to show $[\mathcal{L}_f^{m-1} h(x)]_{x} \hat{d}(t)-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| \gamma(T) \geq -\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| (\theta+2\gamma(T))$ for any $t$. The foregoing inequality holds since
$[\mathcal{L}_f^{m-1} h(x)]_{x} \hat{d}(t)-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| \gamma(T) \geq -\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|(\|\hat{d}(t)\| +\gamma(T))\geq -\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|(\theta + 2\gamma(T))$.
Consequently, we proved the condition (\ref{worst-bound}) is sufficient for condition (\ref{condition-thm1}) to hold.
\subsection{DOB-CBF-RL Safe Policy Training}
Considering the condition in (\ref{condition-thm1}) that depends on the uncertainty estimation $\hat{d}(t)$, the DOB-CBF-based QP can be defined as
\begin{equation}
\begin{aligned}{\label{eq:DOB-QP}}
&u_{\text{safe}}=\argmin _{(u, \epsilon)\in \mathbb{R}^{m+1}} \frac{1}{2}(u-u_{\text{RL}})^{T}P(u-u_{\text{RL}}) ~(\textbf{DOB-CBF-QP})\\
\text{s.t.} & ~\mathcal{K}(t, x, u) +\beta_m\left(\phi_{m-1}(x)\right) \geq 0, \\
& u \in \mathcal{U},
\end{aligned}
\end{equation}
where $u_{\text{RL}}$ is the action of RL policy and $u_{\text{safe}}$ is the final control input applied to the system (\ref{eq:dynamics}) during both policy training and policy deployment.
\begin{algorithm2e}
\caption{DOB-CBF based safe RL framework}\label{alg:1}
\SetKwInOut{Input}{Input}
\Input{Initial policy $\pi_\theta$, number of episodes $N$, number of steps per episode $T$, number of policy update $G$, estimation error bound $\gamma$, nominal dynamics $\dot{x} = f(x)+g(x)u$, disturbance $d$}
\For{$i=1,....,N$}{
\For{$t=1,...,T$}{
Obtain action $u^{\text{RL}}_t$ from policy $\pi_{\theta}$\\
Obtain disturbance estimation $\hat{d}_t$ from DOB\\
Obtain safe action $u^{\text{safe}}_t$ from DOB-CBF-QP, using $u^{\text{RL}}_t$, $\gamma$ and $\hat{d}_t$\\
Take action $u^{\text{safe}}_t$ in environment\\
Add transition $(x_t, u^{\text{safe}}_t, x_{t+1}, r_t)$ to reply buffer $\mathcal{D}$
}
\For{$j=1,...,G$}{
Sample batch $\mathcal{B}$ from $\mathcal{D}$\\
Update parameter $\theta$ using $\mathcal{B}$}
}
\end{algorithm2e}
Given the DOB-CBF-QP in (\ref{eq:DOB-QP}), we present the final DOB-CBF-RL framework in Algorithm \ref{alg:1}.
While the vanilla RL policy usually takes action based on current observed states and focuses on minimizing long-term costs. Therefore, adding a DOB-CBF component after the RL agent will provide a safe action $u_{\text{safe}}$ for the agent to interact with the environment. Then we add the tuple $(x_t, u^{\text{safe}}_t, x_{t+1}, r_t)$ to the reply buffer $\mathcal{D}$. Thus, besides ensuring safety exploration, the final RL policy will also take safe action without further help from the safety constraint component.
\section{Simulation}\label{simulation}
In this section, we used a unicycle path-searching task and a 2D quadrotor trajectory tracking task to validate the proposed method. The DOB-based method was further compared with the recent GP-based safe RL method (GP-CBF-RL) proposed by \cite{cheng2019end} and discussed the results in detail. The policy training was done on a local machine with an INTEL i9-9980XE CPU, an NVIDIA 3090Ti GPU, and 64GB DDR4 RAM.
\subsection{Unicycle}
A unicycle model was modified from \cite{SafembRL2022}. The state $x = [p_x, p_y, \theta]^T$, where $p_x$ and $p_y$ denote the robot position along the x-axis and y-axis, respectively, and $\theta$ is the counterclockwise angle between the positive direction of the x-axis and the head direction of the robot. The control inputs are the linear velocity $v$ and angular velocity $\omega$ of the system. The goal is to navigate the unicycle from the red dot to the yellow dot without colliding with any obstacles, as shown in Figure \ref{fig:uni_train_traj} (Right). The matched uncertainty $d_m= -0.1v$ was used to mimic the slippery ground that causes the unicycle to lose partial control efficiency. The equations of motion for the unicycle are as follows:
\begin{equation}{\label{eq:quad_dyn}}
\begin{aligned}
v_x &=\cos{\theta}(v + d_{m}), \\
v_y &=\sin\theta(v + d_{m}), \\
\dot{\theta} &=\omega.
\end{aligned}
\end{equation}
We train the DOB-CBF-RL policy and the GP-CBF-RL policy separately and define $h(x) = \frac{1}{2}(\|p_{obs}-\sqrt{p^2_x+p^2_y}\|^2-r_{obs}^2)$, where $p_{obs}$ denotes the location of obstacles, and $r_{obs}$ is the radius of the obstacle. The reward function, defined by $r = -(p_x - p_{x}^{tar})^2 - (p_y - p_{y}^{tar})^2$,where $[p_{x}^{tar}, p_{y}^{tar}]$, is the target location in xy-plane. The constants in Assumption \ref{assump:lipschitz-bound-d} are selected as $l_d=0.1\cos{\theta}$ and $b_d =0.1$. We can see from Figure \ref{fig:uni_train_traj} (Left) that the DOB-CBF-RL policy converges around the sixtieth episode. However, the GP-CBF-RL policy can only find an equally good policy after the ninetieth episode. Considering the use of two hundred episodes to train a policy, a thirty-episode gap is a considerable improvement in training efficiency. It is worth noting that compared with DOB-CBF-RL, there is more variation with the training performance across five trials for GP-CBF-RL. It indicates that DOB-CBF-RL can further improve the training stability by providing accurate disturbance estimation. Figure \ref{fig:uni_train_traj} (Right) compares the navigation performance. DOB-CBF-RL provides a more aggressive way to approach the target. In other words, GP-CBF-RL offers a more conservative trajectory and fails to reach the target, although the deviation is negligible. The safety violation rate for each 50 training episodes is given by Table \ref{table:safety_violation_uni}. It is noteworthy that DOB-CBF demonstrates zero-violation rates during the entire training process. Nevertheless, GP-CBF has a higher violation rate at the initial training stage. With the estimation accuracy of GP model increasing, the violation rate gradually decreases.
\begin{figure}[h]
\centering
\includegraphics[scale=0.44]{figs/uni_training.pdf}
\includegraphics[scale=0.43]{figs/uni_traj.pdf}
\caption{(Left) Unicycle training curves for DOB-CBF-RL and GP-CBF-RL. The solid lines and shaded areas denote the mean and standard deviation over five trials. And a two-episode window was applied to smoothen the curves. The cumulative reward is normalized. (Right) Navigation performance for DOB-CBF-RL policy and GP-CBF-RL policy trained in 200 episodes.}\label{fig:uni_train_traj
\end{figure}
\begin{table*}[htb]
\vspace{-3mm}
\begin{center}
\caption{Safety Violation Rate during Training for Unicycle}\label{table:safety_violation_uni}
\begin{tabular}{|c|c|c|c|c|}
\hline
Training Episode & 1$\sim$50 & 51$\sim$100 & 101$\sim$150 & 151$\sim$200\\
\hline
{DOB-CBF} & 0.0$\%$ & 0.0$\%$ & 0.0$\%$ & 0.0$\%$ \\
{GP-CBF} & 12.0$\%$ & 6.0$\%$ & 2.0$\%$ & 0.0$\%$ \\
\hline
\end{tabular}
\end{center}
\vspace{-8mm}
\end{table*}
\subsection{2D Quadrotor}
\begin{figure}[h]
\centering
\includegraphics[scale=0.43]{figs/quad_training.pdf}
\includegraphics[scale=0.43]{figs/quad_traj.pdf}
\caption{(Left) Quadrotor training curves for DOB-CBF-RL and GP-CBF-RL. The solid lines and shaded areas denote the mean and standard deviation over five trials. And a five-episode window was applied to smooth the curves. The cumulative reward is normalized. (Right) Trajectory tracking performance for DOB-CBF-RL policy trained in 2500 episodes and GP-CBF-RL policy trained in 5000 episodes.}\label{fig:quad_train_traj}
\end{figure}
The state of the quadrotor is $x = [p_x, v_x, p_z, v_z, \theta,\dot{\theta}]^T$, where $[p_x, p_z]$ and $[v_x,v_z]$ are the position and velocity of the quadrotor in the $xz$-plane, respectively, and $[\theta, \dot{\theta}]$ are the pitch angle, that is the angle between $x$ direction of the quadrotor body frame and the $x$ direction of the inertia frame, and its angular velocity, respectively. The control input of the quadrotor is $u=[u_1, u_2]^T$, which denotes the thrust force generated by each motor. The objective is to enable a quadrotor to track the reference trajectory while ensuring that the quadrotor is within the boundary defined by $h(x) = \frac{1}{2}(\|p_{bound}\|^2-(p^2_x + p^2_y))$, where $p_{bound}$ is the location of the boundary. In this setup, both the matched and unmatched uncertainties were considered; $d_{u_1} = -0.05u_1$ and $d_{u_2} = -0.05u_2$ are the matched uncertainties to mimic the rotational friction of motors, $d_{um}=[d_{um}^x,d_{um}^z]^T$ denotes the air resistance along each axis, and $d_{um}^x = 0.01v^2_x$ and $d_{um}^z = 0.01v^2_z$. The dynamics are given as follows:
\begin{equation}{\label{eq:quad_dyn}}
\begin{aligned}
a_x &=-\sin \theta\left(u_1+u_2+d_{u_1}+d_{u_2}\right) / m + d_{um}^x,\\
a_z &=\cos \theta\left(u_1+u_2+d_{u_1}+d_{u_2}\right) / m-g+ d_{um}^z, \\
\ddot{\theta} &=\left(u_2-u_1-d_{u_1}+d_{u_2}\right) d / I_{y y},
\end{aligned}
\end{equation}
where $a_x$ and $a_z$ are the acceleration of the quadrotor in xz-plane, $\ddot{\theta}$ is the angular acceleration, $g=9.81\text{m}/\text{s}^2$ is gravity acceleration, $m=0.027\text{kg}$ denotes the total mass of the quadrotor, $d=0.033~\text{m}$ is the effective moment arm, and $I_{yy}=1.4\times 10^{-5} \text{kg}\cdot\text{m}^2$ is the moment of inertia around $y$-axis. The reward function is given by
$r = -8[(p_x - p^{ref}_x)^2 + (p_z - p^{ref}_z)^2] - 3[(v_x - v^{ref}_x)^2 + (v_z - v^{ref}_z)^2] - 1.5[(\theta - \theta^{ref})^2 + (\dot{\theta} - \dot{\theta}^{ref})^2]$,
where $[p^{ref}_x, p^{ref}_y]$ and $[v^{ref}_x, v^{ref}_z]$ are the desired position and velocity in xz-plane, respectively. The constants in Assumption \ref{assump:lipschitz-bound-d} are chosen as $\l_d=0.2u_{max}+0.02v_{max}$ and $b_d=0.1$, where $u_{max}=2\text{N}$ is the max thrust of single motor and $v_{max}=5\text{m}/\text{s}$ is the max velocity in x and z directions. To achieve better tracking performance, the input of the RL policy is defined as
$(p_x, v_x, p_z, v_z, \theta, \dot{\theta}, p_x^{ref}, v_x^{ref}, p_z^{ref}, v_z^{ref}, \theta^{ref}, \dot{\theta}^{ref})$.
A comparison of two methods in Figure \ref{fig:quad_train_traj} (Left) shows that the DOB-CBF-RL method can significantly improve the training efficiency, allowing the SAC policy to converge in less than two-thousand episodes. In any case, the GP-CBF-RL method failed to find an equally good policy in 6000 episodes in most trials. One can see from Figure \ref{fig:quad_train_traj} (Right), there is no doubt that DOB-CBF-RL enables the agent to generate a more aggressive trajectory. Knowing the accurate disturbance estimation, the policy trained with DOB-CBF-RL pushes the agent to finish the task as perfectly as possible, while still enforces the safety of the quadrotor.
Figure \ref{fig:quad_error_time} (Left) shows the disturbance estimation result at different training steps. DOB shows a relatively stable and decent estimation performance starting from the beginning and consistently yields an estimation error that is smaller than 5$\%$, while the GP model gradually decreases the error and yields larger estimation error even at $6\times 10^5$ steps.
It is well known that GP model training involves computing a $N\times N$ covariance matrix $\Sigma$, where $N$ is the number of data points, which is computationally expensive when $N$ is large. Figure \ref{fig:quad_error_time} (Right) shows the average computation time per one thousand training steps, from which the computation time of GP-CBF-RL is at least about three times longer than the computation time of DOB-CBF-RL. To better validate the safe exploration feature, we compute the safety violation rates for every 500 episodes during training and summarize the results in Table \ref{table:safety_violation}. The "w/pre-trained" means we first trained a vanilla policy using nominal dynamics and used the pre-trained policy as the starting point for GP-CBF-RL. We can see from Table \ref{table:safety_violation}, that DOB-CBF-RL shows an overwhelming advantage over the GP-CBF-RL method. Without pre-training, GP-CBF-RL shows significant safety guarantee performance at the initial training stage. In "w/ pre-training" case, GP-CBF still doesn't demonstrate evenly matched performance as DOB-CBF while its violation rates have been significantly lowered by introducing a pretrained policy.
\begin{figure}[h]
\centering
\includegraphics[scale=0.44]{figs/est_error.pdf}
\includegraphics[scale=0.41]{figs/average_time.pdf}
\caption{(Left) Disturbance estimation error yielded by DOB and GP model during training. The estimation errors are computed at $1\times10^3$th, $1\times10^4$th, $1\times10^5$th, $3\times10^5$th, and $6\times10^5$th steps. Five trials were performed and the mean with the standard deviation is shown at each test step for DOB and GP model. The color box attached with the mean-variance bar denotes the worst and best estimation error at each shown step. Each color box in the background indicates the global worst estimation error of DOB and GP model. We consider each case whose estimation error is higher than 100$\%$ as a 100$\%$ estimation error case. (Right) Average computation time per 1000 steps. Solid lines with markers plot the average time per 1000 steps at $n$th training step, where $n=1000,...,2.5\times 10^4$.}\label{fig:quad_error_time
\end{figure}
\begin{table*}[htb]
\vspace{-3mm}
\begin{center}
\caption{Safety Violation Rate during Training for Quadrotor}\label{table:safety_violation}
\begin{tabular}{|c|c|c|c|c|}
\hline
Training Episode & 1$\sim$500& 501$\sim$1000& 1001$\sim$1500& 1501$\sim$2000\\
\hline
{DOB-CBF} & 15.8$\%$ & 2.6$\%$ & 0.2$\%$ & 0.0$\%$ \\
{GP-CBF} & 91.4$\%$ & 79.6$\%$ & 59.8$\%$ & 40.4$\%$ \\
{GP-CBF(w/ pre-training)} & 30.8$\%$ & 22.8$\%$ & 20.0$\%$ & 7.8$\%$ \\
\hline
\end{tabular}
\end{center}
\vspace{-6mm}
\end{table*}
\section{Conclusion and Future Works}
This paper presents an approach based on disturbance observer (DOB) control barrier functions (CBFs) for safe model-free reinforcement learning (RL). At the core of our proposed approach is a DOB-CBF, which further consists of a DOB that can estimate the pointwise value of the uncertainty with a pre-computable estimation error bound (EEB), and a quadratic programming (QP) module with a robust CBF condition dependent on the estimated uncertainty and the EEB, to generate safe actions by minimally modifying the (potentially unsafe) actions generated by the RL policy. Unlike existing safe RL approaches based on CBFs, which often rely on model learning of the uncertain dynamics, our approach completely removes the need for model learning and facilitates sample- and computationally-efficient policy learning. The results have been validated in simulated environments.
A relevant direction of future work is to include experimental validation of the proposed DOB-CBF-RL framework on a real robot, e.g., a 3D quadrotor, and extension of the framework to the model-based RL setting.
\section{Acknowledgments}
This work is supported by NSF under the RI grant $\#$2133656
\section{Introduction}
Reinforcement learning (RL) has demonstrated impressive performance in robotic control in recent years. Many real-world systems are subject to safety constraints.
As a result, safe RL has recently received a lot of attention, although there are different definitions of ``safety'' \cite{garcia2015comprehensive,brunke2022safe}. We limit our discussion to safe RL that aims to ensure satisfaction of {\it hard state constraints} all the time
during both training and deployment.
Among different safe RL paradigms, a commonly used one is to leverage {\it safety filters} (SFs) to constrain the actions of RL agents and modify them whenever necessary to ensure satisfaction of safety constraints. The advantages of this paradigm mainly lie in its flexibility, i.e., a safety filter can often work with many existing RL algorithms without (many) modifications to the RL algorithms. Along this line, researchers have proposed different safety filters based on shielding \cite{alshiekh2018safe}, control barrier functions (CBFs) \cite{cheng2019end, ohnishi2019barrier,SafembRL2022}, Hamilton-Jacobi reachability (HJR) \cite{fisac2018general-safety}, and model predictive safety certification (MPSC) \cite{wabersich2021probabilistic-safety}. Among these different SFs, the shielding SF \cite{alshiekh2018safe} only works for discrete state and action spaces.
All other SFs are model-based, and hinge on Gaussian process regression (GPR) to learn the uncertain dynamics together with quantifiable learned model error for robust safety assurance. When applying these SFs to model-free RL, the resulting safe RL framework will not be model-free anymore due to the involvement of model learning. More importantly, due to the reliance on model learning, when the learned model is poor due to insufficient data, existing model-based SFs will be overly conservative, preventing efficient exploration of RL agents. Additionally, it is well known that GPR is computationally demanding (standard GPR model training involves computing the inverse of an $N\times N$ covariance matrix, where $N$ is the number of data points). As a result, GPR is probably not scalable to high-dimensional systems.
\begin{figure}
\centering
\includegraphics[width=0.6\linewidth]{figs/DOB-RL.pdf}
\caption{Proposed safe RL framework via using DOB-CBF. At time step $t$, the RL agent action $u^{\text{RL}}_t$ potentially violates the predefined safety constraints. Hence, a DOB-CBF safe action filter will render a $u^{\text{safe}}_t$ based on $u^{\text{RL}}_t$, precomputed estimation error bound $\gamma$ and disturbance estimation $\hat{d}$. Then, $u^{\text{safe}}_t$ is applied to interact with the environment to enforce safety during and after the policy training.}
\label{fig:framework}
\vspace{-6mm}
\end{figure}
This paper presents a safe model-free RL approach using disturbance observer (DOB) based CBFs introduced in \cite{zhao2020aR-cbf}. As illustrated in Figure \ref{fig:framework}, our approach leverages a DOB to accurately estimate the value of the lumped disturbance at each time step with a pre-computable estimation error bound (EER). The estimated disturbance together with the EEB is incorporated into a quadratic programming (QP) module with robust CBF conditions that generates safe actions at each step by minimally modifying the RL actions.
Compared to existing CBF-based safe RL approaches, e.g., \cite{cheng2019end, ohnishi2019barrier,SafembRL2022}, our approach does not need model learning of the uncertain dynamics (although a nominal model is needed), facilitating real {\it model-free} RL. Additionally, it enables more efficient exploration and higher sample efficiency, thanks to the accurate estimation provided by the DOB, unlike GPR whose prediction performance can be quite poor due to insufficient data at the initial learning stage. Finally, it is much more computationally-efficient compared to existing approaches based on GPR. The efficacy of the proposed approach is demonstrated on a unicyle and a 2D quadrotor in simulations, in comparison with an existing method.
This article is organized as follows. Section \ref{preliminary} includes preliminaries related to DOBs, CBFs, RL. Section \ref{main_approach} presents the proposed safe RL framework, while Section \ref{simulation} includes the simulation results for verifying the proposed framework using a unicycle and a 2D quadrotor.
\section{Preliminary} \label{preliminary}
We consider a nonlinear control-affine system with uncertainties in the form of
\begin{equation}{\label{eq:dynamics}}
\dot{x}(t) = f(x(t)) + g(x(t))u(t) + d(x(t)),
\end{equation}
where $x(t) \in \mathcal{X} \subset \mathbb{R}^n$ denotes the state vector, $u(t) \in \mathcal{U} \subset \mathbb{R}^m$ is the input vector, $\mathcal{X}$ and $\mathcal{U}$ are compact sets, $ f: \mathbb{R}^n \to \mathbb{R}^n$ and $g: \mathbb{R}^n \to \mathbb{R}^m$ are known locally Lipschitz-continuous functions, and $d: \mathbb{R}^n \to \mathbb{R}^n$ is an unknown function that captures uncertain dynamics.
\begin{assumption}\label{assump:lipschitz-bound-d}(\cite{zhao2020aR-cbf})
There exist positive constants $l_d$ and $b_d$ such that for any $x,y\in \mathcal{X}$, the following inequalities hold:
\begin{align}
\|d(x)-d(y)\| & \leq l_d\|x-y\|, \\
\|d(0)\| & \leq b_d.
\end{align}
\end{assumption}
Moreover, the constants $l_d$ and $b_d$ are known.
\begin{remark} \cref{assump:lipschitz-bound-d} {\it does not assume} that the system states stay in $\mathcal{X}$ (and thus are bounded). We will leverage a DOB-CBF to ensure $x$ stays in $\mathcal{X}$ later.
\cref{assump:lipschitz-bound-d} merely indicates that the uncertain function $d(x)$ is {\it locally Lipschitz} continuous with a known {\it bound} on the Lipschitz constant {\it in the compact set $\mathcal{X}$} and is bounded by a known constant at the origin.
\end{remark}
\subsection{Reinforcement Learning}
Reinforcement learning aims to find the optimal policy $\pi^{*}$ in an environment which can be formulated as a Markov decision process (MDP). In this work, an MDP is defined by a tuple $(\mathcal{S}, \mathcal{A}, p, r)$, where state space $\mathcal{S}$ and action space $\mathcal{A}$ are continuous. Given the current state $s_{t}$, action $a_{t}$, and the probability of state transition $p: \mathcal{S} \times \mathcal{S} \times \mathcal{A} \to [0,\infty)$ represents the probability density of the succeeding state $s_{t+1}$. The environment provides a reward $r$ for each transition.
Soft actor-critic \cite{Tuomassac} is a state-of-the-art model-free RL algorithm that benefits policy training in two essential parts. SAC uses an off-policy formulation that reuses historical data to improve sample efficiency. Furthermore, it utilizes entropy maximization to improve the stability of training performance. In general, SAC aims to maximize an entropy objective which is formed as $\pi^*=\arg \max \sum_{t=0}^{T} \mathbb{E}_{\left(x_t, u_t^{R L}\right) \sim \rho_\pi}\left[r\left(x_t, u_t^{R L}\right)+\alpha \mathcal{H}\left(\pi\left(\cdot \mid x_t\right)\right)\right]$, where $\alpha$ is a positive parameter to determine the relative importance of the entropy term against the reward, $\mathcal{H}(\cdot)$ is the entropy term which incentivizes exploration, $\rho_\pi$ denotes the state distribution induced by the policy $\pi$, and $T$ is the termination time.
\subsection{Control Barrier Function}
The control barrier function in~\cite{ames2014control} is an online method to enforce the safety of the dynamical system. It instantly filters the unsafe part of control input from any baseline controller. Typically, control barrier functions consider non-disturbed (nominal) dynamics
\begin{equation}{\label{eq:nominal-dynamics}}
\dot{x}(t) = f(x(t)) + g(x(t))u(x(t)).
\end{equation}
A set $\mathcal{C}$ is forward invariant for (\ref{eq:nominal-dynamics}), if its solutions starting at any $x(t_0) \in \mathcal{C}$ lead to $x(t) \in \mathcal{C}$ for $\forall t \geq t_{0}$. Further, define a continuously differentiable function $h$ that satisfies $\mathcal{C} := \{x \in \mathbb{R}^n : h(x)\geq 0\}$. Nevertheless, in this work, we are looking for a method to make CBFs secure the system in a disturbed environment. Therefore, we utilize the control barrier functions to ensure system safety during policy training.
\begin{definition}{\label{def:rcbf}}(First-Order Control Barrier Function with Perturbed System Dynamics~\cite{zhao2020aR-cbf}).
Given a set $\mathcal{C}$ which is forward invariant for (\ref{eq:dynamics}), $h(x)$ is a valid robust control barrier function for (\ref{eq:dynamics}) if there exists an extended class $\mathcal{K}$ function\footnote{A function $\beta:(-b, a)\to (-\infty, \infty)$ is said to belong to extended class $\mathcal{K}$ for some $a,b > 0$ if it is strictly increasing and $\beta(0)=0$.} $\beta$ s.t. $\forall x \in \mathcal{C}$
\begin{equation}
\sup _{u \in \mathcal{U}}\left\{L_f h(x)+L_g h(x) u + h_{x}(x)d(x)\right\} \geq-\beta(h(x))\label{eq:rcbf},
\end{equation}
\end{definition}
where $L_f$ and $L_g$ are the Lie derivatives w.r.t. $x$ along $f$ and $g$, respectively, and $h_{x}$ denotes the partial derivative of $h(x)$ with respect to $x$. In addition to the first-order CBF, CBF with higher control input relative degree\footnote{The relative degree of a differentiable function $h: \mathbb{R}^n \to \mathbb{R}$ with respect to \ref{eq:dynamics} is the number of times we need to differentiate it along the \ref{eq:dynamics} and state $x$ until the control $u$ explicitly shows up.} as proposed by \cite{Tan2022HighOrderBF} and \cite{tan-high-order-cbf} are further considered.
\begin{assumption}\label{disturb-rel-degree}
The disturbance relative degree is equal to the relative degree of control input $u$.
\end{assumption}
We further define a sequence of functions $\phi_{i}: \mathbb{R}^n \to \mathbb{R}, i \in \{1,...,m\}$ as:
\begin{equation}{\label{eq:phi}}
\phi_{i}(x) = \dot{\phi}_{i-1}(x) + \beta_{i}(\phi_{i-1}(x)), \phi_{0} = h(x).
\end{equation}
Further, an associate sequence of sets can be defined as:
\begin{equation}{\label{eq:sets-c}}
\mathcal{C}_i=\left\{x \in \mathbb{R}^n: \phi_{i-1}(x) \geq 0\right\}, i \in\{1, \ldots, m\}.
\end{equation}
\begin{definition}{\label{def-horcbf}} (High Order Control Barrier Function with Perturbed System Dynamics (HOCBF)).
Consider a sequential function $\phi_{i}(x)$ in (\ref{eq:phi}) and a sequential set $\mathcal{C}_i, i \in \{1,...,m\}$ defined in (\ref{eq:sets-c}). A $m^{th}$ order differentiable function $h: \mathbb{R}^n \to \mathbb{R}$ is a high order robust control barrier function of relative degree m for (\ref{eq:dynamics}) if there exist extended differentiable class $\mathcal{K}$ functions $\beta_{i}, i \in \{1,...,m\}$ such that
\begin{equation}
\sup _{u \in U}\mathcal{L}_f^m h(x)+\mathcal{L}_g \mathcal{L}_f^{m-1} h(x) u+[\mathcal{L}_f^{m-1} h(x)]_{x} d(x)+O(h(x))+\beta_m\left(\phi_{m-1}(x)\right) \geq 0\label{eq:horcbf},
\end{equation}
\end{definition}
where $L^{m-1}_f$ is the $m-1$th partial Lie derivative w.r.t. $x$ along $f$, and $L^m_f$ and $L_g L^{m-1}_f$ are the Lie derivatives of $L^{m-1}_f$ w.r.t. $x$ along $f$ and $g$, respectively. In (\ref{eq:horcbf}), $O(\cdot)$ is given by $O(h(x))=\sum_{i=1}^{m-1} \mathcal{L}_f^i\left(\beta_{m-i} \circ \phi_{m-i-1}\right)(x), \forall x \in \mathcal{C}_{1}\cap ..., \cap \mathcal{C}_{m}$.
\begin{remark}
The true uncertainty $d$, in Definitions \ref{def:rcbf} and \ref{def-horcbf}, is not accessible in hardware applications. Therefore, it is impossible to evaluate whether a function obeys the constraints in (\ref{eq:rcbf}) or (\ref{eq:horcbf}).
\end{remark}
This issue is also discussed by \cite{zhao2020aR-cbf}. One way is to use a GP model to learn and estimate the disturbance $d$. Another direction is using the worst-case bound on the disturbance $d$ to derive a sufficient and provable condition for (\ref{eq:rcbf}) or (\ref{eq:horcbf}). The worst-case bound of first-order CBF has been proved by \cite{zhao2020aR-cbf}. We modified the worst-case bound in \cite{zhao2020aR-cbf} and extended the worst-case bound to the high-order CBF case in Section \ref{section-pc}
\subsection{Disturbance Observer (DOB)}
The piecewise-constant (PC) law in \cite{naira2010l1book-nh} has been demonstrated to work as an essential part of an adaptive controller for disturbance compensation and has shown impressive performance in many applications \cite{yikunRL1-ieee}, \cite{zhao2020robust}. The PC law typically contains two components, i.e., a state predictor that predicts the states of nominal dynamics (\ref{eq:nominal-dynamics}) and a piecewise-constant estimation law to estimate the uncertainty. For the disturbed system (\ref{eq:dynamics}), the state predictor can be formed as follows:
\begin{equation}{\label{state-predictor}}
\dot{\hat{x}}(t) = f(x) + g(x)u + \hat{d}(t) - a\Tilde{x},
\end{equation}
where $\Tilde{x} = \hat{x} - x$ denotes the prediction error, $a > 0$ is a constant, and $\hat{d}(t)$ is the estimated disturbance. For the sake of obtaining the estimation of $d(x)$, the piecewise-constant adaptive law is introduced, and the uncertainty estimation updates depend on
\begin{equation}{\label{eq:pc-law}}
\left\{\begin{aligned}
\hat{d}(t) &=\hat{d}(i T), \quad t \in[i T,(i+1) T), \\
\hat{d}(i T) &=-\frac{a}{e^{a T}-1} \tilde{x}(i T), i=0,1,...,
\end{aligned}\right.
\end{equation}
where $T$ is the sampling time of estimation.
Given the lumped uncertainty $d(x)$ is bounded as $\|d(x)\|\leq\theta$, the PC law error bound follows the succeeding definition.
\begin{lemma} (Estimation Error Bound \cite{zhao2020aR-cbf})\label{lemma:est_error_bound}
Given the system (\ref{eq:dynamics}), and the estimation law in (\ref{state-predictor}) and (\ref{eq:pc-law}), subject to Assumption \ref{assump:lipschitz-bound-d}, the estimation error can be bounded as
\begin{equation}
\begin{aligned}
\|\hat{d}(t)-d(x(t))\| &\leq \begin{cases}\theta, & \forall 0 \leq t<T, \\ \gamma(T), & \forall t \geq T,\end{cases} \\
& \lim _{T \rightarrow 0} \gamma(T)=0,\label{eq:error-bound}
\end{aligned}
\end{equation}
\end{lemma}
where $\gamma(T)$ denotes the error bounds for all $t \geq T$.
\section{Main Approach}\label{main_approach}
This section introduces a disturbance-observer-based high-order control barrier function framework for safe action generation with pre-defined and reducible error bounds. We prove that the uncertainty estimation could be utilized to formulate a revamped version of the high-order CBF in Definition \ref{def-horcbf}. Then, we propose the DOB-CBF-based safe RL scheme (DOB-CBF-RL) for ensuring safety of RL policy.
\subsection{High-order DOB-Based Control Barrier Function (DOB-CBF)} \label{section-pc}
Given the estimation error bound in Lemma \ref{lemma:est_error_bound}, we consider the worst-case bound on the uncertainty $d$. First, we develop the bound for $\|\hat{d}(t)\|$. In (\ref{eq:error-bound}), it is obvious that $\|\hat{d}(t)-d(x(t))\| \geq \|\hat{d}(t)\| - \|d(x(t))\|$. Given the disturbance bound $\|d(x(t))\|\leq \theta$ and the estimation error bound in (\ref{eq:error-bound}), we have $\|\hat{d}(t)\| \leq \theta + \gamma$ for any $t\geq T$. Hence, the worst-case bound on $d$ is straightforward to show that $[\mathcal{L}_f^{m-1} h(x)]_{x}d(x)\leq\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|\|d(x)\|\leq\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|\|d(x) + \hat{d}(t)- \hat{d}(t)\|\leq \|[\mathcal{L}_f^{m-1} h(x)]_{x}\|(\|d(x) - \hat{d}(t)\|+ \|\hat{d}(t)\|)\leq\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|(\theta +2\gamma(T))$. Therefore, the following lemma holds.
\begin{lemma}
A $m^{th}$ order differentiable function $h: \mathbb{R}^n \to \mathbb{R}$ is a high order robust control barrier function of relative degree m for (\ref{eq:dynamics}) if there exist extended class $\mathcal{K}$ functions $\beta_{i}, i \in \{1,...,m\}$ such that
\begin{equation}\label{worst-bound}
\sup _{u \in U}\mathcal{L}_f^m h(x)+\mathcal{L}_g \mathcal{L}_f^{m-1} h(x) u-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| (\theta+2\gamma(T))+O(h(x))+\beta_m\left(\phi_{m-1}(x)\right) \geq 0,
\end{equation}
for all $x \in \mathcal{C}_{1}\cap ..., \cap \mathcal{C}_{m}$.
\end{lemma}
It is obvious that if a control input $u$ is a solution for (\ref{worst-bound}), it also satisfies (\ref{eq:horcbf}). We next define
\vspace{-5mm}
\begin{equation}\label{cond1}
\mathcal{K}(t, x, u) \triangleq L^{m}_f h(x)+L_gL^{m-1}_f h(x) u+O(h(x))+[\mathcal{L}_f^{m-1} h(x)]_{x} \hat{d}(t)-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| \gamma(T).
\end{equation}
Then, the main theorem of the proposed approach is introduced as follows.
\begin{theorem}{\label{theorem1}}
Suppose the condition (\ref{worst-bound}) holds; then the condition
\begin{equation}
\sup _{u \in U} \mathcal{K}(t, x, u) \geq-\beta_m\left(\phi_{m-1}(x)\right){\label{condition-thm1}}
\end{equation}
is a sufficient condition for (\ref{eq:horcbf}), and a necessary condition for (\ref{eq:horcbf}) for any $t\geq T$ when $T \to 0$.
\end{theorem}
\begin{proof} We first prove that condition (\ref{condition-thm1}) is sufficient for (\ref{eq:horcbf}). Comparing (\ref{eq:horcbf}) and (\ref{condition-thm1}), it is only necessary to prove that $[\mathcal{L}_f^{m-1} h(x)]_{x}d(x)\geq[\mathcal{L}_f^{m-1} h(x)]_{x}\hat{d}(t)-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|\gamma(T)$ for any $t\geq T$. From (LHS) of preceding inequality, we have
$[\mathcal{L}_f^{m-1} h(x)]_{x}d(x) = \mathcal{L}_f^{m-1}(d(x) + \hat{d}(t) - \hat{d}(t))\\
\geq \mathcal{L}_f^{m-1}\hat{d}(t) - \|[\mathcal{L}_f^{m-1} h(x)]_{x}|\|d(x) - \hat{d}(t)\|\geq \mathcal{L}_f^{m-1}\hat{d}(t) - \|[\mathcal{L}_f^{m-1} h(x)]_{x}\|\gamma(T)$.
We next prove the necessity. When $T$ tends to $0$, $\gamma(T)\to 0$ according to (\ref{eq:error-bound}), and thus $\hat{d}(t)\to d(x)$ for any $t\geq T$, which indicates that (LHS) of (\ref{eq:horcbf}) is equal to the (LHS) of (\ref{condition-thm1}). Consequently, the necessity for any $t \geq T$, as $T\to 0$, is proved.
\end{proof}
We further discuss whether the condition (\ref{worst-bound}) is sufficient for condition (\ref{condition-thm1}) to hold. Comparing (\ref{worst-bound}) and (\ref{cond1}), we only need to show $[\mathcal{L}_f^{m-1} h(x)]_{x} \hat{d}(t)-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| \gamma(T) \geq -\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| (\theta+2\gamma(T))$ for any $t$. The foregoing inequality holds since
$[\mathcal{L}_f^{m-1} h(x)]_{x} \hat{d}(t)-\|[\mathcal{L}_f^{m-1} h(x)]_{x}\| \gamma(T) \geq -\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|(\|\hat{d}(t)\| +\gamma(T))\geq -\|[\mathcal{L}_f^{m-1} h(x)]_{x}\|(\theta + 2\gamma(T))$.
Consequently, we proved the condition (\ref{worst-bound}) is sufficient for condition (\ref{condition-thm1}) to hold.
\subsection{DOB-CBF-RL Safe Policy Training}
Considering the condition in (\ref{condition-thm1}) that depends on the uncertainty estimation $\hat{d}(t)$, the DOB-CBF-based QP can be defined as
\begin{equation}
\begin{aligned}{\label{eq:DOB-QP}}
&u_{\text{safe}}=\argmin _{(u, \epsilon)\in \mathbb{R}^{m+1}} \frac{1}{2}(u-u_{\text{RL}})^{T}P(u-u_{\text{RL}}) ~(\textbf{DOB-CBF-QP})\\
\text{s.t.} & ~\mathcal{K}(t, x, u) +\beta_m\left(\phi_{m-1}(x)\right) \geq 0, \\
& u \in \mathcal{U},
\end{aligned}
\end{equation}
where $u_{\text{RL}}$ is the action of RL policy and $u_{\text{safe}}$ is the final control input applied to the system (\ref{eq:dynamics}) during both policy training and policy deployment.
\begin{algorithm2e}
\caption{DOB-CBF based safe RL framework}\label{alg:1}
\SetKwInOut{Input}{Input}
\Input{Initial policy $\pi_\theta$, number of episodes $N$, number of steps per episode $T$, number of policy update $G$, estimation error bound $\gamma$, nominal dynamics $\dot{x} = f(x)+g(x)u$, disturbance $d$}
\For{$i=1,....,N$}{
\For{$t=1,...,T$}{
Obtain action $u^{\text{RL}}_t$ from policy $\pi_{\theta}$\\
Obtain disturbance estimation $\hat{d}_t$ from DOB\\
Obtain safe action $u^{\text{safe}}_t$ from DOB-CBF-QP, using $u^{\text{RL}}_t$, $\gamma$ and $\hat{d}_t$\\
Take action $u^{\text{safe}}_t$ in environment\\
Add transition $(x_t, u^{\text{safe}}_t, x_{t+1}, r_t)$ to reply buffer $\mathcal{D}$
}
\For{$j=1,...,G$}{
Sample batch $\mathcal{B}$ from $\mathcal{D}$\\
Update parameter $\theta$ using $\mathcal{B}$}
}
\end{algorithm2e}
Given the DOB-CBF-QP in (\ref{eq:DOB-QP}), we present the final DOB-CBF-RL framework in Algorithm \ref{alg:1}.
While the vanilla RL policy usually takes action based on current observed states and focuses on minimizing long-term costs. Therefore, adding a DOB-CBF component after the RL agent will provide a safe action $u_{\text{safe}}$ for the agent to interact with the environment. Then we add the tuple $(x_t, u^{\text{safe}}_t, x_{t+1}, r_t)$ to the reply buffer $\mathcal{D}$. Thus, besides ensuring safety exploration, the final RL policy will also take safe action without further help from the safety constraint component.
\section{Simulation}\label{simulation}
In this section, we used a unicycle path-searching task and a 2D quadrotor trajectory tracking task to validate the proposed method. The DOB-based method was further compared with the recent GP-based safe RL method (GP-CBF-RL) proposed by \cite{cheng2019end} and discussed the results in detail. The policy training was done on a local machine with an INTEL i9-9980XE CPU, an NVIDIA 3090Ti GPU, and 64GB DDR4 RAM.
\subsection{Unicycle}
A unicycle model was modified from \cite{SafembRL2022}. The state $x = [p_x, p_y, \theta]^T$, where $p_x$ and $p_y$ denote the robot position along the x-axis and y-axis, respectively, and $\theta$ is the counterclockwise angle between the positive direction of the x-axis and the head direction of the robot. The control inputs are the linear velocity $v$ and angular velocity $\omega$ of the system. The goal is to navigate the unicycle from the red dot to the yellow dot without colliding with any obstacles, as shown in Figure \ref{fig:uni_train_traj} (Right). The matched uncertainty $d_m= -0.1v$ was used to mimic the slippery ground that causes the unicycle to lose partial control efficiency. The equations of motion for the unicycle are as follows:
\begin{equation}{\label{eq:quad_dyn}}
\begin{aligned}
v_x &=\cos{\theta}(v + d_{m}), \\
v_y &=\sin\theta(v + d_{m}), \\
\dot{\theta} &=\omega.
\end{aligned}
\end{equation}
We train the DOB-CBF-RL policy and the GP-CBF-RL policy separately and define $h(x) = \frac{1}{2}(\|p_{obs}-\sqrt{p^2_x+p^2_y}\|^2-r_{obs}^2)$, where $p_{obs}$ denotes the location of obstacles, and $r_{obs}$ is the radius of the obstacle. The reward function, defined by $r = -(p_x - p_{x}^{tar})^2 - (p_y - p_{y}^{tar})^2$,where $[p_{x}^{tar}, p_{y}^{tar}]$, is the target location in xy-plane. The constants in Assumption \ref{assump:lipschitz-bound-d} are selected as $l_d=0.1\cos{\theta}$ and $b_d =0.1$. We can see from Figure \ref{fig:uni_train_traj} (Left) that the DOB-CBF-RL policy converges around the sixtieth episode. However, the GP-CBF-RL policy can only find an equally good policy after the ninetieth episode. Considering the use of two hundred episodes to train a policy, a thirty-episode gap is a considerable improvement in training efficiency. It is worth noting that compared with DOB-CBF-RL, there is more variation with the training performance across five trials for GP-CBF-RL. It indicates that DOB-CBF-RL can further improve the training stability by providing accurate disturbance estimation. Figure \ref{fig:uni_train_traj} (Right) compares the navigation performance. DOB-CBF-RL provides a more aggressive way to approach the target. In other words, GP-CBF-RL offers a more conservative trajectory and fails to reach the target, although the deviation is negligible. The safety violation rate for each 50 training episodes is given by Table \ref{table:safety_violation_uni}. It is noteworthy that DOB-CBF demonstrates zero-violation rates during the entire training process. Nevertheless, GP-CBF has a higher violation rate at the initial training stage. With the estimation accuracy of GP model increasing, the violation rate gradually decreases.
\begin{figure}[h]
\centering
\includegraphics[scale=0.44]{figs/uni_training.pdf}
\includegraphics[scale=0.43]{figs/uni_traj.pdf}
\caption{(Left) Unicycle training curves for DOB-CBF-RL and GP-CBF-RL. The solid lines and shaded areas denote the mean and standard deviation over five trials. And a two-episode window was applied to smoothen the curves. The cumulative reward is normalized. (Right) Navigation performance for DOB-CBF-RL policy and GP-CBF-RL policy trained in 200 episodes.}\label{fig:uni_train_traj
\end{figure}
\begin{table*}[htb]
\vspace{-3mm}
\begin{center}
\caption{Safety Violation Rate during Training for Unicycle}\label{table:safety_violation_uni}
\begin{tabular}{|c|c|c|c|c|}
\hline
Training Episode & 1$\sim$50 & 51$\sim$100 & 101$\sim$150 & 151$\sim$200\\
\hline
{DOB-CBF} & 0.0$\%$ & 0.0$\%$ & 0.0$\%$ & 0.0$\%$ \\
{GP-CBF} & 12.0$\%$ & 6.0$\%$ & 2.0$\%$ & 0.0$\%$ \\
\hline
\end{tabular}
\end{center}
\vspace{-8mm}
\end{table*}
\subsection{2D Quadrotor}
\begin{figure}[h]
\centering
\includegraphics[scale=0.43]{figs/quad_training.pdf}
\includegraphics[scale=0.43]{figs/quad_traj.pdf}
\caption{(Left) Quadrotor training curves for DOB-CBF-RL and GP-CBF-RL. The solid lines and shaded areas denote the mean and standard deviation over five trials. And a five-episode window was applied to smooth the curves. The cumulative reward is normalized. (Right) Trajectory tracking performance for DOB-CBF-RL policy trained in 2500 episodes and GP-CBF-RL policy trained in 5000 episodes.}\label{fig:quad_train_traj}
\end{figure}
The state of the quadrotor is $x = [p_x, v_x, p_z, v_z, \theta,\dot{\theta}]^T$, where $[p_x, p_z]$ and $[v_x,v_z]$ are the position and velocity of the quadrotor in the $xz$-plane, respectively, and $[\theta, \dot{\theta}]$ are the pitch angle, that is the angle between $x$ direction of the quadrotor body frame and the $x$ direction of the inertia frame, and its angular velocity, respectively. The control input of the quadrotor is $u=[u_1, u_2]^T$, which denotes the thrust force generated by each motor. The objective is to enable a quadrotor to track the reference trajectory while ensuring that the quadrotor is within the boundary defined by $h(x) = \frac{1}{2}(\|p_{bound}\|^2-(p^2_x + p^2_y))$, where $p_{bound}$ is the location of the boundary. In this setup, both the matched and unmatched uncertainties were considered; $d_{u_1} = -0.05u_1$ and $d_{u_2} = -0.05u_2$ are the matched uncertainties to mimic the rotational friction of motors, $d_{um}=[d_{um}^x,d_{um}^z]^T$ denotes the air resistance along each axis, and $d_{um}^x = 0.01v^2_x$ and $d_{um}^z = 0.01v^2_z$. The dynamics are given as follows:
\begin{equation}{\label{eq:quad_dyn}}
\begin{aligned}
a_x &=-\sin \theta\left(u_1+u_2+d_{u_1}+d_{u_2}\right) / m + d_{um}^x,\\
a_z &=\cos \theta\left(u_1+u_2+d_{u_1}+d_{u_2}\right) / m-g+ d_{um}^z, \\
\ddot{\theta} &=\left(u_2-u_1-d_{u_1}+d_{u_2}\right) d / I_{y y},
\end{aligned}
\end{equation}
where $a_x$ and $a_z$ are the acceleration of the quadrotor in xz-plane, $\ddot{\theta}$ is the angular acceleration, $g=9.81\text{m}/\text{s}^2$ is gravity acceleration, $m=0.027\text{kg}$ denotes the total mass of the quadrotor, $d=0.033~\text{m}$ is the effective moment arm, and $I_{yy}=1.4\times 10^{-5} \text{kg}\cdot\text{m}^2$ is the moment of inertia around $y$-axis. The reward function is given by
$r = -8[(p_x - p^{ref}_x)^2 + (p_z - p^{ref}_z)^2] - 3[(v_x - v^{ref}_x)^2 + (v_z - v^{ref}_z)^2] - 1.5[(\theta - \theta^{ref})^2 + (\dot{\theta} - \dot{\theta}^{ref})^2]$,
where $[p^{ref}_x, p^{ref}_y]$ and $[v^{ref}_x, v^{ref}_z]$ are the desired position and velocity in xz-plane, respectively. The constants in Assumption \ref{assump:lipschitz-bound-d} are chosen as $\l_d=0.2u_{max}+0.02v_{max}$ and $b_d=0.1$, where $u_{max}=2\text{N}$ is the max thrust of single motor and $v_{max}=5\text{m}/\text{s}$ is the max velocity in x and z directions. To achieve better tracking performance, the input of the RL policy is defined as
$(p_x, v_x, p_z, v_z, \theta, \dot{\theta}, p_x^{ref}, v_x^{ref}, p_z^{ref}, v_z^{ref}, \theta^{ref}, \dot{\theta}^{ref})$.
A comparison of two methods in Figure \ref{fig:quad_train_traj} (Left) shows that the DOB-CBF-RL method can significantly improve the training efficiency, allowing the SAC policy to converge in less than two-thousand episodes. In any case, the GP-CBF-RL method failed to find an equally good policy in 6000 episodes in most trials. One can see from Figure \ref{fig:quad_train_traj} (Right), there is no doubt that DOB-CBF-RL enables the agent to generate a more aggressive trajectory. Knowing the accurate disturbance estimation, the policy trained with DOB-CBF-RL pushes the agent to finish the task as perfectly as possible, while still enforces the safety of the quadrotor.
Figure \ref{fig:quad_error_time} (Left) shows the disturbance estimation result at different training steps. DOB shows a relatively stable and decent estimation performance starting from the beginning and consistently yields an estimation error that is smaller than 5$\%$, while the GP model gradually decreases the error and yields larger estimation error even at $6\times 10^5$ steps.
It is well known that GP model training involves computing a $N\times N$ covariance matrix $\Sigma$, where $N$ is the number of data points, which is computationally expensive when $N$ is large. Figure \ref{fig:quad_error_time} (Right) shows the average computation time per one thousand training steps, from which the computation time of GP-CBF-RL is at least about three times longer than the computation time of DOB-CBF-RL. To better validate the safe exploration feature, we compute the safety violation rates for every 500 episodes during training and summarize the results in Table \ref{table:safety_violation}. The "w/pre-trained" means we first trained a vanilla policy using nominal dynamics and used the pre-trained policy as the starting point for GP-CBF-RL. We can see from Table \ref{table:safety_violation}, that DOB-CBF-RL shows an overwhelming advantage over the GP-CBF-RL method. Without pre-training, GP-CBF-RL shows significant safety guarantee performance at the initial training stage. In "w/ pre-training" case, GP-CBF still doesn't demonstrate evenly matched performance as DOB-CBF while its violation rates have been significantly lowered by introducing a pretrained policy.
\begin{figure}[h]
\centering
\includegraphics[scale=0.44]{figs/est_error.pdf}
\includegraphics[scale=0.41]{figs/average_time.pdf}
\caption{(Left) Disturbance estimation error yielded by DOB and GP model during training. The estimation errors are computed at $1\times10^3$th, $1\times10^4$th, $1\times10^5$th, $3\times10^5$th, and $6\times10^5$th steps. Five trials were performed and the mean with the standard deviation is shown at each test step for DOB and GP model. The color box attached with the mean-variance bar denotes the worst and best estimation error at each shown step. Each color box in the background indicates the global worst estimation error of DOB and GP model. We consider each case whose estimation error is higher than 100$\%$ as a 100$\%$ estimation error case. (Right) Average computation time per 1000 steps. Solid lines with markers plot the average time per 1000 steps at $n$th training step, where $n=1000,...,2.5\times 10^4$.}\label{fig:quad_error_time
\end{figure}
\begin{table*}[htb]
\vspace{-3mm}
\begin{center}
\caption{Safety Violation Rate during Training for Quadrotor}\label{table:safety_violation}
\begin{tabular}{|c|c|c|c|c|}
\hline
Training Episode & 1$\sim$500& 501$\sim$1000& 1001$\sim$1500& 1501$\sim$2000\\
\hline
{DOB-CBF} & 15.8$\%$ & 2.6$\%$ & 0.2$\%$ & 0.0$\%$ \\
{GP-CBF} & 91.4$\%$ & 79.6$\%$ & 59.8$\%$ & 40.4$\%$ \\
{GP-CBF(w/ pre-training)} & 30.8$\%$ & 22.8$\%$ & 20.0$\%$ & 7.8$\%$ \\
\hline
\end{tabular}
\end{center}
\vspace{-6mm}
\end{table*}
\section{Conclusion and Future Works}
This paper presents an approach based on disturbance observer (DOB) control barrier functions (CBFs) for safe model-free reinforcement learning (RL). At the core of our proposed approach is a DOB-CBF, which further consists of a DOB that can estimate the pointwise value of the uncertainty with a pre-computable estimation error bound (EEB), and a quadratic programming (QP) module with a robust CBF condition dependent on the estimated uncertainty and the EEB, to generate safe actions by minimally modifying the (potentially unsafe) actions generated by the RL policy. Unlike existing safe RL approaches based on CBFs, which often rely on model learning of the uncertain dynamics, our approach completely removes the need for model learning and facilitates sample- and computationally-efficient policy learning. The results have been validated in simulated environments.
A relevant direction of future work is to include experimental validation of the proposed DOB-CBF-RL framework on a real robot, e.g., a 3D quadrotor, and extension of the framework to the model-based RL setting.
\section{Acknowledgments}
This work is supported by NSF under the RI grant $\#$2133656
| {'timestamp': '2022-12-01T02:21:28', 'yymm': '2211', 'arxiv_id': '2211.17250', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17250'} | arxiv |
\section{Introduction}\label{sec::intro}
Coordinating multiple agents that can communicate with each other to make decisions under uncertainty is a classical problem and has many different applications in computer science \citep{DBLP:books/mk/Lynch96}, game theory \citep{chakravarty_mitra_sarkar_2014} and machine learning \citep{DBLP:conf/nips/LanctotZGLTPSG17}.
We consider the multi-agent version of a multi-armed bandit problem which
is one of the most fundamental decision making problems under uncertainty.
In this problem, a learning agent needs to consider the exploration-exploitation trade-off, i.e. balancing the exploration of various actions in order to learn how much rewarding they are and selecting high-rewarding actions. In the multi-agent version of this problem, multiple agents collaborate with each other trying to maximize their individual cumulative rewards, and the challenge is to design efficient cooperative algorithms under communication constraints.
We consider the nonstochastic (adversarial) multi-armed bandit problem in a cooperative multi-agent setting, with $K\geq 2$ arms and $N\geq 1$ agents. In each time step, each agent selects an arm and then observes the incurred loss corresponding to its selected arm. The losses of arms are according to an arbitrary loss sequence, which is commonly referred to as the nonstochastic or adversarial setting. Each agent observes only the loss of the arm this agent selected in each time step. The agents are allowed to cooperate by exchanging messages, which is constrained by a communication graph $G$ such that any two agents can exchange a message directly between themselves only if they are neighbors in graph $G$. Each exchange of a message over an edge has delay of $d$ time steps. The goal of each agent is to minimize its cumulative loss over a time horizon of $T$ time steps. We study the objective of minimizing the individual regret of agents, i.e. the difference between the expected cumulative loss incurred by an agent and the cumulative loss of the best arm in hindsight. We also study the average regret of all agents.
The multi-agent multi-armed bandit problem formulation that we study captures many systems that use a network of learning agents. For example, in peer-to-peer recommender systems, the agents are users and the arms are products that can be recommended to users \citep{DBLP:journals/jcss/BaragliaDMR13}. The delay corresponds to the time it takes for a message to be transmitted between users. Note that in this application scenario, the number of products (i.e. arms) may be much larger than the number of users (i.e. agents).
\sloppy The collaborative multi-agent multi-armed bandit problem was studied, e.g., in \citet{DBLP:journals/jmlr/Cesa-BianchiGM19} and \citet{DBLP:conf/nips/Bar-OnM19}, where each edge has unit delay. Our setting is more general in allowing for arbitrary delay $d$ per edge. \citet{DBLP:journals/jmlr/Cesa-BianchiGM19} showed that when each agent selects arms according to a cooperative Exp3 algorithm (Exp3-Coop), the average regret is $O(\sqrt{(\alpha(G)/N +1/K)\log(K)KT})$ for large enough $T$, where $\alpha(G)$ is the independence number of graph $G$. \citet{DBLP:conf/nips/Bar-OnM19} have shown that individual regret of each agent $v$ is $O(\sqrt{(1/|\mathcal{N}(v)|+1/K)\log(K)KT})$ when $T\geq K^2 \log(K)$, where $\mathcal{N}(v)$ is the set of neighbors of agent $v$ and itself in graph $G$. This regret bound is shown to hold for an algorithm where some agents, referred to as center agents, select arms using the Exp3-Coop policy and other agents copy the actions of center agents. These bounds reveal the effect of collaboration on the learning and what graph properties effect the efficiency of learning. However, some fundamental questions still remain. For example, to the best of our knowledge, it is unknown from the previous literature what is the lower bound for this problem. Moreover, it is unknown whether better algorithms can be designed whose regret matches a lower bound under certain conditions.
In this work, we give a regret lower bound for any learning algorithm in which each agent can only communicate with their neighbors. We present a center-based algorithm whose regret upper bound matches the lower bound when the number of arms is large enough. We present an algorithm that has a regret upper bound with $\sqrt{d}$ dependence on the delay per edge, which is optimal. All our regret bounds are parametrized with the delay parameter $d$, which is unlike to \citet{DBLP:journals/jmlr/Cesa-BianchiGM19} and \citet{DBLP:conf/nips/Bar-OnM19} which considered only the special when $d=1$. In what follows we summarise our results in more details.
\subsection{Summary of our contributions}
We show that any algorithm has individual regret for each agent $v$ lower bounded as
$$
\Omega\left(\sqrt{\left(\frac{1}{|\mathcal{N}(v)|}+\frac{1}{K}\log(K)\right)KT}\right),
$$
when $T \geq K/|\mathcal{N}(v)|$. This implies the average regret lower bound $\Omega(\sqrt{(\delta(G)^2+\log(K)/K)KT})$, when $T \geq \delta(G)^2K$, where $\delta(G)=(1/N)\sum_{v\in \mathcal{V}}(1/\sqrt{|\mathcal{N}(v)|})$. Hence, there is a $\sqrt{\log(K)}$ factor gap between the previously known upper bounds and the lower bound.
We show an algorithm that guarantees individual regret for each agent $v$ to be
$$
O\left(\sqrt{\left(\frac{1}{|\mathcal{N}(v)|}+\frac{|\mathcal{N}(C(v))|}{K}\log(K)^2\right)KT}\right),
$$
whenever $K\geq \max_{v}|\mathcal{N}(v)|$ and $T \geq \Omega(K\max_{c\in \mathcal{C}} |\mathcal{N}(c)|)$, where $\mathcal{C}$ is the set of center agents and $C(v)$ is the nearest center agent to agent $v$. This regret bound improves the best known upper bound on individual regret when the number of arms is large enough relative to agents' degrees.
Moreover, we note that the algorithm has optimal regret up to a constant factor when when $|\mathcal{N}(C(v))||\mathcal{N}(v)|\log(K)^2/K = O(1)$, i.e. when the number of arms is large enough.
Our algorithm is based on using a cooperative Follow-the-Regularized-Leader (FTRL) policy with a Tsallis entropy regularizer. This is in contrast to \citet{DBLP:journals/jmlr/Cesa-BianchiGM19,DBLP:conf/nips/Bar-OnM19}, which both use a cooperative Exp3 policy.
Our regret analysis relies on a key new lemma that bounds the change of the action selection strategy of an agent under Tsallis entropy regularization. This result may be of independent interest.
We also present a decentralized follow-the-regularized-leader algorithm that has regret with optimal dependency on the delay parameter $d$, namely scaling as $\sqrt{d}$. This algorithm uses a hybrid regularizer, which combines an Exp3 type regularizer with a Tsallis entropy regularizer. This algorithm is decentralised with all agents applying the same strategy.
\subsection{Related work}
The multi-armed bandit problem in a multi-agent setting, where agents collaborate with each other subject to some communication constraints, has received considerable attention in recent years.
\citet{DBLP:journals/jcss/AwerbuchK08a} introduced the cooperative nonstochastic multi-armed bandit problem setting where communication is through a public channel (corresponding to a complete graph) and some agents may be dishonest.
\citet{DBLP:conf/cdc/KarPC11} considered a special collaboration network in which only one agent can observe the loss of the selected arm in each time step.
\citet{DBLP:conf/icml/SzorenyiBHOJK13} discussed two specific P2P networks in which at each time step, each agent can send messages to only two other agents.
\citet{DBLP:conf/alt/Cesa-BianchiCM20} studied an online learning problem where only a subset of agents play in each time step. They showed that an optimal average regret bound for this problem is $\Theta(\sqrt{\alpha(G)T})$ when the set of agents that play in each time step is chosen randomly, while $\Omega(T)$ bound holds when the set of agents can be chosen arbitrarily in each time step.
\citet{DBLP:journals/ton/KollaJG18}, \citet{DBLP:conf/cdc/LandgrenSL16, DBLP:conf/cdc/LandgrenSL16} and \citet{DBLP:conf/nips/Martinez-RubioK19} considered a setting in which communication is constrained by a communication graph such that any two agents can communicate \emph{instantly} if there is an edge connecting them.
The communication model considered in our paper was introduced by \citet{DBLP:journals/jmlr/Cesa-BianchiGM19}. Here, agents communicate via messages sent over edges of a fixed connected graph and sending a message over an edge incurs a delay of value $d$. \citet{DBLP:journals/jmlr/Cesa-BianchiGM19} considered the case when $d=1$ whereas in this paper, we consider $d\geq 1$.
They proposed an algorithm, referred to as Exp3-Coop, in which each agent constructs loss estimators for each arm using an importance-weighted estimator.
The Exp3-Coop algorithm has an upper bound of $O(\sqrt{(\alpha(G)/N + 1/K)\log(K)KT} + \log(T))$ on the average regret.
\citet{DBLP:conf/nips/Bar-OnM19} combines the idea of center-based communication from \citet{DBLP:journals/ton/KollaJG18} with the Exp3-Coop algorithm, showing that the center-based Exp3 algorithm has a regret upper bound of
$O(\sqrt{(1/|\mathcal{N}(v)|+1/K)\log(K)KT})$ for each individual agent when $d=1$. We show that a better regret bound can be guaranteed with respect to the scaling with the number of arms $K$.
Multi-armed bandits with delayed feedback have been studied extensively in the single-agent setting \citep{DBLP:conf/icml/JoulaniGS13, DBLP:conf/nips/ThuneCS19, DBLP:conf/icml/FlaspohlerOCMOO21}. Specifically,
\citet{DBLP:conf/aistats/ZimmertS20} considered a setting in which the agent has no prior knowledge about the delays and showed an optimal regret of $O(\sqrt{KT}+\sqrt{d\log(K)T})$ where $d$ is the average delay over $T$ time steps. We present, in the multi-agent setting, a distributed learning algorithm whose regret upper bound can also achieve this optimal $\sqrt{d}$ dependence on the delay per edge $d$.
We use the \emph{Tsallis entropy} family of regularizers proposed by \citet{tsallis1988possible}. \citet{DBLP:journals/jmlr/ZimmertS21} have shown that an online mirror descent algorithm with a Tsallis entropy regularizer achieves optimal regret for the single-agent bandit problem. We show a distributed learning algorithm for the multi-agent bandit setting, which uses a Tsallis entropy regularizer.
\subsection{Organization of the paper}
Section~\ref{sec::problem-formulation} provides problem formulation and definitions of notation.
Section~\ref{sec::algorithms-and-regret-upper-bounds} presents our two algorithms and their regret bounds. In Section~\ref{sec::regret-lower-bound}, we present a lower bound on individual regret of each agent. Section~\ref{sec::numerical-experiements} contains numerical results. Finally, conclusion remarks are given in Section~\ref{sec::conclusion}. Proofs of our results are available in the supplementary material.
\section{Problem formulation}
\label{sec::problem-formulation}
We consider a multi-armed bandit problem with a finite set $\mathcal{A}=\{1,\ldots, K\}$ of actions (arms) played by $N$ agents. The agents can communicate through a communication network $G = (\mathcal{V}, \mathcal{E})$
where $\mathcal{V}$ is the set of $N$ agents and $\mathcal{E}$ is the set of edges such that $(u,v)\in \mathcal{E}$ if, and only if, agent $u$ can send/receive messages to/from agent $v$. We denote the neighbors of the agent $v$ and itself by the set $\mathcal{N}(v) = \{u\in \mathcal{V}: (u, v)\in \mathcal{E}\}\cup\{v\}$.
Sending a message over edge $e\in \mathcal{E}$ incurs a delay of value $d_e \geq 0$ time steps. We consider the \emph{homogeneous} setting under which $d_e = d\geq 1$ for every edge $e\in E$.
Note that the delayed communication network model in \citet{DBLP:journals/jmlr/Cesa-BianchiGM19} and \citet{DBLP:conf/nips/Bar-OnM19} is restricted to the special case $d=1$.
At each time step $t = 1,2, \ldots, T$, each agent $v\in \mathcal{V}$ chooses an action $I_t(v)\in \mathcal{A}$ according to distribution $p_t^v$ over $\mathcal{A}$ and then observes the loss value, $\ell_t(I_t(v)) \in [0,1]$. Notice that the loss does not depend on the agent, but only on the time step and the chosen action. Hence, if two agents choose the same action at the same time step, they incur the same loss. We consider the \emph{nonstochastic setting} where the losses are determined by an oblivious adversary, meaning that the losses do not depend on the agent's realized actions.
At the end of each time step $t$, each agent $v\in \mathcal{V}$ sends a message $S_t(v)$ of size $b_t(v)$ information bits to all its neighbors and after this, each agent $v\in \mathcal{V}$ has messages $\cup_{u\in \mathcal{N}(v)}\{S_{s}(u): s+d = t\}$.
We assume that at each time step $t$, each agent $v$ can send to each of its neighbors a message $S_t(v)=\left\langle v, t, I_{t}(v), \ell_{t}\left(I_{t}(v)\right), p_{t}^{v}\right\rangle$, i.e. the agent id, the time step, the chosen arm id, the instant loss received and the instant action distribution. We denote with $b_t(v)$ the number of information bits to encode $S_t(v)$.
The total communication cost in each time step is $\sum_{v\in \mathcal{V}}\sum_{u:(u,v)\in \mathcal{E}}b_t(u)$ information bits.
The \emph{individual regret} of each agent $v$ is defined as the difference between its expected accumulated loss and the loss of the best action in hindsight, i.e.
$$
R_{T}^v=\mathbb{E}\left[\sum_{t=1}^{T} \ell_{t}\left(I_{t}(v)\right)\right]-\min _{i \in \mathcal{A}} \sum_{t=1}^{T} \ell_{t}(i).
$$
The \emph{average regret} of $N$ agents is defined as
$$
R_{T}=\frac{1}{N} \sum_{v \in \mathcal{V}} R_{T}^v.
$$
\paragraph{Additional notation}
We define $\mathcal{P}_{K-1}$ to be the $K-1$ simplex.
Let $\alpha(G)$ be the size of a maximal independent set of graph $G$, where the maximal independent set is the largest subset of nodes such that no two nodes in this set are connected by an edge.
\section{Algorithms and regret upper bounds}
\label{sec::algorithms-and-regret-upper-bounds}
In this section, we propose two collaborative multi-agent bandit algorithms, the center-based cooperative follow-the-regularized-leader (CFTRL) algorithm and the decentralized cooperative follow-the-regularized-leader (DFTRL) algorithm. The first algorithm has optimal regret up to a constant factor when the number of arms is large enough. The second algorith has optimal depence on the delay parameter $d$.
\subsection{A center-based cooperative follow-the-regularized-leader algorithm}
We consider an algorithm where some agents, referred to as \emph{centers}, run a FTRL algorithm, and each other agent copies the action selection distribution from its nearest center. The strategy based on using center agents was proposed in \citet{DBLP:conf/nips/Bar-OnM19}, where agents played the Exp3 strategy instead. These centre agents collaboratively update their strategies by exchanging messages with other agents, and each non-center agent copies the strategy of its nearest center agent. The center agents are selected such that they have a sufficiently large degree, which can be shown to reduce individual regret of center agents. Moreover, the center agents are selected such that each non-center agent is within a small distance to a center agent.
Let $\mathcal{C} \subseteq \mathcal{V}$ be the set of centers. The set of agents $\mathcal{V}$ is partitioned into disjoint components $\mathcal{V}_c$, $c\in \mathcal{C}$.
Each non-center agent $v$ belongs to a unique component. For each agent $v$, let $C(v)$ denote its center agent, $c=C(v)$ if and only if $v\in \mathcal{V}_{c}$.
Let $d(v)$ be the distance between a non-center agent $v$ and its center $C(v)$. The set of centers $\mathcal{C}$ and the partitioning $\{\mathcal{V}_c: c\in \mathcal{C}\}$ are computed according to Algorithms~3 and 4 in \citet{DBLP:conf/nips/Bar-OnM19}.
Let $\mathcal{J}_t(v) = \{I_t(v^\prime): v^\prime\in \mathcal{N}(v)\}$ be the set of actions chosen by agent $v$ or its neighbors at time step $t$.
Each center agent $c\in C$ runs a FTRL algorithm with the collaborative importance-weighted loss estimators observable up to time step $t$,
$$
\hat{L}^{c,obs}_t(i) = \sum_{s=1}^{t-1}\hat{\ell}^{c,obs}_s(i)
$$
and
$$
\hat{\ell}_{t}^{c,obs}(i)=
\left\{\begin{array}{cl}
\frac{\ell_{t-d}(i)}{q_{t-d}^c(i)} \mathbb{I}\left\{i\in\mathcal{J}_{t-d}(c)\right\} & \text { if } t> d \\
0 & \text { otherwise }
\end{array}\right.
$$
where
$$
q_t^c(i) = 1-\prod_{v \in \mathcal{N}(c)}\left(1-p_t^{v}(i)\right)
$$
is the \emph{neighborhood-aggregated importance weight}.
In each time step, the center agents update their action selection distributions according to the FTRL algorithm, i.e.
$$
p_t^c=\operatorname{argmin}_{p\in \mathcal{P}_{K-1}} \left\{ \left\langle p, \hat{L}_{t}^{c, obs}\right\rangle + F_t(p)\right\}.
$$
where $F_t(p)$ is the \emph{Tsallis entropy regularizer}
\citep{DBLP:journals/jmlr/ZimmertS21} with the learning rate $\eta(c)$,
\begin{equation}
\label{eq::tsallis-entropy}
F_t(p) = -2\sum_{i=1}^K\sqrt{p_i} / \eta(c).
\end{equation}
Each non-center agent $v\in \mathcal{V}\backslash C$ selects actions according to the uniform distribution until time step $t>d(v)d$.
Then the non-center agent copies the action selection distribution from its center, i.e.
$p^v_{t} = p^{C(v)}_{t-d(v)d}.$
The details of the CFTRL algorithm are described in Algorithm \ref{algo:CFTRL}.
\begin{algorithm}[t]
\caption{Center-based cooperative FTRL (CFTRL)}\label{algo:CFTRL}
\SetKwInOut{Init}{Initialization}
\SetKwInOut{Input}{Input}
\Input{Tsallis regularizer Eq.~(\ref{eq::tsallis-entropy}), learning rate $\eta(c)$ and the delay $d$.}
\Init{$\hat{L}_1^{c, obs}(i) = 0$ for all $i\in \mathcal{A}$ and $c\in C$, $p_1^v(i) = 1/K$ for all $i\in \mathcal{A}$ and $v\not\in C$.}
\For{each time step $t=1,2,\dots, T$}{
Each $c\in \mathcal{C}$ updates $p_t^c= \operatorname{argmin}_{p\in \mathcal{P}_{K-1}}\{ \langle p, \hat{L}_{t}^{c, obs}\rangle + F_t(p)\}
$\;
Each $c\in \mathcal{C}$ chooses $I_t(c)=i$ with probability $p_t^c(i)$ and receives the loss $\ell_t(I_t(c))$\;
Each $c\in \mathcal{C}$ sends the message $S_t(c) = \left\langle c, t, I_t(c), \ell_t(I_t(c)), p_t^c\right\rangle$ to all their neighbors\;
Each $c\in \mathcal{C}$ receives messages $\{S_{t-d}(v): v\in \mathcal{N}(c)\}$ and computes $\hat{L}_{t+1}^{c, obs}$\;
Each $v\in \mathcal{V}\setminus \mathcal{C}$ updates $p_{t}^v = p_{t-d(v)d}^{C(v)}$ when $t>d(v)d$ and $p_{t}^v = p_{1}^{v}$ otherwise\;
Each $v\in V\setminus \mathcal{C}$ chooses $I_t(v)=i$ with probability $p_t^v(i)$ and receives $\ell_t(I_t(v))$\;
Each $v\in \mathcal{V}\setminus \mathcal{C}$ sends $S_t(v) = \left\langle v, t, I_t(v), \ell_t(I_t(v)), p_t^v\right\rangle$ to all its neighbors.
}
\end{algorithm}
\subsubsection{Individual regret upper bound}
We show an individual regret upper bound for Algorithm~\ref{algo:CFTRL} in the following theorem.
\begin{theorem}\label{thm::CFTRL}
Assume that $K\geq \max_{v\in \mathcal{V}}|\mathcal{N}(v)|$ and $T\geq 36(d+1)^2K\max_{c}|\mathcal{N}(c)|$, and agents follow the CFTRL algorithm with each center agent $c\in \mathcal{C}$ using the learning rate $\eta(c) = \sqrt{|\mathcal{N}(c)| / (3T)}$. Then, the individual regret of each agent $v\in \mathcal{V}$ is bounded as
$$
R_T^v = O\left(\frac{1}{ \sqrt{|\mathcal{N}(v)|}} \sqrt{KT} + d\log(K)\sqrt{|\mathcal{N}(C(v))|T}\right).
$$
\end{theorem}
The proof of the theorem is provided in the supplementary material.
In the following, we provide a proof sketch. The proof relies on two key lemmas which are shown next.
\begin{lemma}
\label{lm:ftrl-coop:individual}
Assume that the delay of each edge is $d\geq 1$, then the individual regret of each center agent $v$ with the regularizer $F_t(p) = \sum_{i=1}^K f_t(p_i)$ satisfies
\begin{eqnarray*}
R_{T}^v & \leq & M + \frac{1}{2} \mathbb{E} \left[\sum_{t=1}^T \sum_{i\in \mathcal{A}} \frac{1}{q_t^v(i) f_t^{\prime\prime}(p_t^v(i))}\right] \\
&& + d \cdot \mathbb{E} \left[\sum_{t=1}^T \sum_{i\in \mathcal{A}} \frac{1}{f_t^{\prime\prime}(p_t^v(i))}\right]
\end{eqnarray*}
where
$$
M = \max_{x \in \mathcal{P}_{K-1}}-F_{1}(x)+\sum_{t=2}^{T} \max_{x \in \mathcal{P}_{K-1}}\left(F_{t-1}(x)-F_{t}(x)\right).
$$
\end{lemma}
\begin{lemma}
\label{lm:ftrl-tsallis:selection-prob}
For any $\delta>1$, assume that agent $v$ runs a FTRL algorithm
with Tsallis entropy (\ref{eq::tsallis-entropy}) and learning rate $\eta(v)\leq (1-1/\sqrt{\delta})/(\delta^{3d/2}\sqrt{K})$ and $K\geq 2$, then for all $t\geq 1$ and $i\in \mathcal{A}$
$$
(1-(1+\delta)\eta(v)\hat{\ell}_t^{v,obs}(i)) p_t^v(i) \leq p_{t+1}^v(i) \leq \delta p_{t}^v(i).
$$
\end{lemma}
The proofs of the two lemmas are provided in the supplementary material.
Similar property as in Lemma~\ref{lm:ftrl-tsallis:selection-prob} was known to hold for the Exp3 algorithm by a result in \citet{DBLP:journals/jmlr/Cesa-BianchiGM19}. To the best of our knowledge, this property was previously not known to hold for the FTRL algorithm with Tsallis entropy.
Lemma~\ref{lm:ftrl-coop:individual} bounds the individual regret by the sum of a constant, the regret due to the \emph{instant} bandit feedback, and the regret due to the \emph{delayed} full-information feedback, which is $O(\sqrt{KT/|\mathcal{N}(c)|})$.
Since the action selection distributions of non-center agents are copied from their centers in the past rounds, Lemma~\ref{lm:ftrl-tsallis:selection-prob} bounds the difference between action selection distributions of non-center agent $v$ and its center $C(v)$ in the same rounds when $T>d(v)d$.
Consequently, the difference between the individual regret of a non-center agent $v$ and its center $C(v)$ is bounded by $O(d(v)d \eta(C(v)) T) = O(d\log(K) \sqrt{|\mathcal{N}(C(v))|T})$.
\subsection{A decentralized cooperative follow-the-regularizer-leader algorithm}
Theorem~\ref{thm::CFTRL} provides a bound for individual regrets, which increases linearly in the edge-delay parameter $d$. This can be problematic when the delay in the communication network is large.
We show that the effect of delays on regret can be reduced by using a decentralized follow-the-regularized-leader (DFTRL) algorithm.
In the DFTRL algorithm, each agent runs a FTRL algorithm
with
a \emph{hybrid regularizer} $F_t(p)$ defined in \citet{DBLP:conf/aistats/ZimmertS20} as follows
\begin{equation}
\label{eq::hybrid-regularizer}
F_t(p) = \sum_{i=1}^{K} \left( \frac{- 2 \sqrt{p_{i}}}{\eta_t} + \frac{p_i \log(p_i)}{\zeta_t} \right)
\end{equation}
where $\eta_t$ and $\zeta_t$ are some non-increasing sequences.
As is shown in Theorem~4.1, there is a regret lower bound that consists of two parts: the first part is the regret lower bound of the multi-armed bandit problem and the second part is the regret lower bound of the bandit problem with full-information but delayed feedback \cite{DBLP:conf/icml/JoulaniGS13}.
The hybrid regularizer combines the Tsallis entropy regularizer with an optimal regularizer in the full-information setting, the negative entropy regularizer.
The learning rates of the two regularizers can be tuned separately to minimize the regret from the two parts.
The details of the DFTRL are described in Algorithm~\ref{algo:DFTRL}.
\begin{algorithm}[t]
\caption{Decentralized cooperative FTRL (DFTRL)}\label{algo:DFTRL}
\SetKwInOut{Init}{Initialization}
\SetKwInOut{Input}{Input}
\Input{Hybrid regularizer Eq.~(\ref{eq::hybrid-regularizer}), learning rates $\eta_t$, $\zeta_t$, and delay $d$.}
\Init{$\hat{L}_1^{v, obs}(i) = 0$ for all $i\in \mathcal{A}$ and $v\in \mathcal{V}$.}
\For{each time step $t=1,2,\dots, T$}{
Each $v\in \mathcal{V}$ updates $
p_t^v=\operatorname{argmin}_{p\in \mathcal{P}_{K-1}}\{\langle p, \hat{L}_{t}^{v, obs}\rangle + F_t(p)\}
$\;
Each $v\in \mathcal{V}$ chooses $I_t(v)=i$ with probability $p_t^v(i)$ and receives the loss $\ell_t(I_t(v))$\;
Each $v\in \mathcal{V}$ sends the message $S_t(v) = \left\langle v, t, I_t(v), \ell_t(I_t(v)), p_t^v\right\rangle$ to all their neighbors\;
Each $v\in \mathcal{V}$ receives messages $\{S_{t-d}(v^\prime): v^\prime\in \mathcal{N}(v)\}$ and computes $\hat{L}_{t+1}^{v, obs}$\;
}
\end{algorithm}
\subsubsection{Average regret upper bound}
We show a bound on the average regret for the DFTRL algorithm in the following theorem. The sequences $\eta_t$ and $\zeta_t$ are assumed to be set as
$$
\eta_t = (1/(1-1/e)) (\alpha(G)/ N + 1/K)^{-1/4} \sqrt{2/T}
$$
and
$$
\zeta_t = \sqrt{\log(K) / (dt)}.
$$
\begin{theorem}\label{thm::DFTRL}
Assume that each agent follows the DFTRL algorithm
and the delay of each edge is $d\geq 1$, then the average regret over $N$ agents is bounded as
$$
R_{T} = O\left( \left(\frac{\alpha(G)}{N} + \frac{1}{K}\right)^{1/4}\sqrt{KT} + \sqrt{d\log(K)T} \right).
$$
\end{theorem}
Proof of the theorem is provided in the supplementary material.
We note that the average regret scales as $\sqrt{d}$ which is better than linear scaling of the CFTRL algorithm.
For the special case when $d=1$, as in \citet{DBLP:journals/jmlr/Cesa-BianchiGM19},Theorem~\ref{thm::DFTRL}
shows that when the number of arms $K$ is large enough, then the DFTRL algorithm has an $O((\alpha(G)/N)^{1/4}\sqrt{KT})$ regret, which is better than $O((\alpha(G)/N)^{1/2}\sqrt{KT}\sqrt{\log(K)})$ of Exp3-Coop from \citet{DBLP:journals/jmlr/Cesa-BianchiGM19}. Specifically, this improvement holds when
$
K = \Omega(\exp(\sqrt{N/\alpha(G)})).
$
In what follows we provide a proof sketch of Theorem~\ref{thm::DFTRL}.
First we present a key lemma whose proof is provided in the supplementary material.
\begin{lemma}
\label{lm:ftrl-coop-independence}
For every agent $v\in \mathcal{A}$ and any probability distribution $p^v$ over $\mathcal{A}$, it holds
$$
\sum_{i\in \mathcal{A}}\sum_{v \in \mathcal{V}} \frac{p^v(i)^{\frac{3}{2}}}{q^v(i)} \leq
N\sqrt{\frac{1}{1-1/e}\left(\frac{\alpha(G)}{N}+\frac{1}{K}\right)K}
$$
where $q^v(i) = 1-\prod_{v^\prime \in \mathcal{N}(v)}(1-p^{v^\prime}(i))$.
\end{lemma}
Lemma~\ref{lm:ftrl-coop-independence} shows that the average regret from the FTRL algorithm with the hybrid regularizer with instant feedback is $O((\alpha(G)/N + 1/K)^{1/4}\sqrt{KT})$.
For the regularizer in Eq.~(\ref{eq::hybrid-regularizer}), the delay effect term is $O(\sqrt{dT\log(K)})$.
Lemma~\ref{lm:ftrl-coop:individual} bounds the average regret by the sum of two terms.
\section{Regret lower bounds}
\label{sec::regret-lower-bound}
We present lower bounds on individual regret $R_T^v$ for every agent $v\in \mathcal{V}$ and average regret $R_T$.
\begin{theorem} \label{thm:lower-2}
The worst-case individual regret of each agent $v\in \mathcal{V}$, $R_T^v$, is
$$
\Omega\left(\max\left\{ \min \left\{T, \frac{1}{\sqrt{|\mathcal{N}(v)|}}\sqrt{KT}\right\}, \sqrt{d \log(K)T}\right\} \right)
$$
and the worst-case average regret, $R_T$, is
$$
\Omega\left( \max\left\{ \min \left\{T, c_G\sqrt{KT}\right\}, \sqrt{d \log(K)T}\right\} \right)
$$
where $c_G = (1/N)\sum_{v\in \mathcal{V}}1/\sqrt{|\mathcal{N}(v)|}$.
\end{theorem}
The proof is provided in the supplementary material.
The lower bounds contain two parts. The first part is derived from the lower bounds in \citet{DBLP:conf/nips/Shamir14} for a class of online algorithms. The second part handles the effect of delays by showing that the individual regret of each agent cannot be smaller than the regret of a single agent with delayed full information.
We note that the individual regret of Algorithm~\ref{algo:CFTRL} is optimal with respect to scaling with the number of arms $K$ and the average regret of Algorithm~\ref{algo:DFTRL} is optimal with respect to scaling with delay $d$.
\section{Numerical experiments}
\label{sec::numerical-experiements}
In this section, we present results of numerical experiments whose goal is to compare performance of CFTRL and DFTRL algorithms with some state-of-the-art algorithms and demonstrate the tightness of our theoretical bounds. We consider the classic stochastic multi-armed bandit problem with agents communicating via different networks.
The stochastic multi-armed bandit problem is defined as follows: each arm $i$ is associated with a Bernoulli distribution with mean $\mu_i$ for $i=1,2,\dots, K$. The loss $\ell_t(i)$ from choosing arm $i$ at time step $t$ is sampled independently from the corresponding Bernoulli distribution.
In our experiments, we set $\mu_i = (1+8(i-1)/(K-1))/10$ so that $\mu_1, \dots, \mu_K$ is a linearly decreasing sequence.
Each problem instance is specified by a tuple $(K, G, d)$. The two baseline algorithms we choose are the center-based Exp3 algorithm in \citet{DBLP:conf/nips/Bar-OnM19} and the Exp3-Coop algorithm in \citet{DBLP:journals/jmlr/Cesa-BianchiGM19} whose regret upper bounds are suboptimal as discussed in the introduction.
The numerical results are for four experiments whose goals are as follows:
\begin{itemize}
\item the first experiment compares the performance of CFTRL, DFTRL and the baselines when the number of arms increases,
\item the second experiment validates the effect of the graph degree in the regret upper bound on CFTRL,
\item the third experiment validates the effect of the delay parameter on the regret upper bounds of CFTRL and DFTRL, and, finally,
\item the fourth experiment compares CFTRL and the center-based Exp3 algorithm on some sparse random graphs.
\end{itemize}
In summary, our numerical results validate theoretical results and demonstrate that CFTRL and DFTRL can achieve significant performance gains over some previously proposed algorithms.
The code for producing our experimental results is available online in the GitHub repository: \href{https://anonymous.4open.science/r/On-Regret-Optimal-Cooperative-Nonstochastic-Multi-armed-Bandits-4C76/}{[link]}.
\begin{figure}[t]
\centering
\includegraphics[width=.4\textwidth]{regret-20.pdf}
\includegraphics[width=.4\textwidth]{regret-30.pdf}
\includegraphics[width=.4\textwidth]{regret.pdf}
\caption{Average regret $R_T$ versus $T$ for different algorithms on a $2$-regular graph with $N=3$ agents and edge-delay $d=1$, and varied number of arms: (top) $K=20$ (middle) $K=30$, and (top) $K=40$. We used 10 independent simulation runs.
}
\label{fig:regret}
\end{figure}
\subsection{The effect of the number of arms}
In the first experiment, we evaluate the performance of CFTRL and DFTRL against the baselines on a $r$-regular graph (all nodes have the same degree of $r$). Note that in a regular graph, each agent has equal probability to be a center agent. For a $r$-regular graph, CFTRL has an individual regret upper bound of $O(\sqrt{(1/r)}\sqrt{KT})$ and DFTRL has an average regret upper bound of $O(\sqrt[4]{1-r/N}\sqrt{KT})$ when the number of arms $K$ is large enough according to our analysis.
We first demonstrate numerical results showing that CFTRL and DFTRL can achieve significant performance gains over the center-based Exp3 algorithm whose individual regret upper bound is $O(\sqrt{(1/r)\log(K)}\sqrt{KT})$ and the Exp3-Coop algorithm whose average regret upper bound is $O(\sqrt{(1-r/N)\log(K)}\sqrt{KT})$ when the number of arms $K$ is large enough.
Figure~\ref{fig:regret} shows the regret $R_T$ versus $T$ for different number of arms, namely $20$, $30$ and $40$. The results demonstrate that CFTRL and DFTRL achieve better regret than Exp3-COOP and center-based Exp3 when the number of arms is large enough.
\subsection{The effect of graph degree on CFTRL}
In the second experiment, we validate the scaling of the graph degree in the regret upper bound of CFTRL.
On the $r$-regular graph, CFTRL has a regret that scales as $O(1/\sqrt{r})$ according to Theorem~\ref{thm::CFTRL}.
We run CFTRL on the problem instances with fixed number of arms $K$, delay $d$ and increasing node degree $r$.
The results in Figure~\ref{fig:degree} shows that the averaged regret decreases as the graph degree increases and the rate of decrease is approximately $O(1/\sqrt{r})$.
\begin{figure}[t!]
\centering
\includegraphics[width=.4\textwidth]{degree.pdf}
\caption{Average regret of CFTRL versus graph degree $r$, for a $r$-regular graph with $N=6$ nodes, $K = 10$ and $d = 1$.}
\label{fig:degree}
\end{figure}
\subsection{The effect of delay on CFTRL and DFTRL}
\begin{figure}[t!]
\centering
\includegraphics[width=.4\textwidth]{delay.pdf}
\caption{Average regret of CFTRL and DFTRL versus the edge-delay $d$ on a star regular graph with $N = 20$ and $K = 3$.
}
\label{fig:delay}
\end{figure}
In the third experiment, we run CFTRL and DFTRL algorithms on a fixed star graph $G$ with a fixed number of arms $K$ and varied edge-delay $d$ . Figure~\ref{fig:delay} shows that the normalized regret of CFTRL is $R_T / \sqrt{d} = O(\sqrt{d})$ while the normalized regret of DFTRL is $R_T / \sqrt{d} = O(1)$. Hence, when the delay $d$ is large enough, CFTRL has a linearly increasing regret with respect to $d$ which is in contrast to the sub-linear increasing regret of DFTRL.
This is consistent with our theoretical analysis, which states that CFTRL has a regret upper bound of $O(d)$ and DFTRL has a regret upper bound of $O(\sqrt{d})$.
\subsection{The effect of graph sparsity}
In the fourth experiment, we validate that our CFTRL algorithm can outperform the center-based Exp3 algorithm on some random graphs.
We consider Erdős–Rényi random graphs of $N$ nodes with probability of an edge equal to $2\log(N)/N$. This condition ensures that the graph is connected
and
$|\mathcal{N}(v)| = O(\log(N)))$ for all $v\in \mathcal{V}$, almost surely \citep[Corollary 8.2]{blum_hopcroft_kannan_2020}.
This random graph allows us to evaluate performance of algorithms for a large sparse random graph. We fix $K$ and $d$ and vary the number of nodes $N$ and compare the performance of CFTRL and the center-based Exp3 algorithm on these graphs.
We fix $T$ to $1000$ time steps.
According to our analysis, CFTRL has a lower individual regret bound than the center-based Exp3 algorithm
when the number of arms is large enough relative to the number of agents.
The results in Figure~\ref{fig:erdos} indicate that CFTRL has at least as good performance as the center-based Exp3 algorithm when $K$ varies, and can have significantly better performance when the number of arms is large relative to the number of agents.
\begin{figure}
\centering
\includegraphics[width=.4\textwidth]{erdos_renyi.pdf}
\caption{Average regret $R_T$ versus the number of nodes $N$ for sparse Erdős–Rényi random graphs, for CFTRL and center-based Exp3 algorithms.}
\label{fig:erdos}
\end{figure}
\section{Conclusion}
\label{sec::conclusion}
We presented new results for the collaborative multi-agent nonstochastic multi-armed bandit with communication delays.
We showed a lower bound on the regret of each individual agent and proposed two algorithms (CFTRL and DFTRL) together with their regret upper bounds. CFTRL provides an optimal regret of each individual agent with respect to the scaling with the number of arms.
DFTRL has an optimal average regret with respect to the scaling with the edge-delay. Our numerical results validate our theoretical bounds and demonstrate that significant performance gains can be achieved by our two algorithms compared to state-of-the-art algorithms.
There are several open research questions for future research. The first question is to consider the existence of a decentralized algorithm which can provide $O((1/\sqrt{|\mathcal{N}(v)|})\sqrt{KT})$ individual regret for each agent $v$. It is unclear whether a center-based communication protocol is necessary to achieve this regret. The second question is to consider whether an algorithm exists with an optimal scaling with the number of arms and the edge-delay parameter. The third question is to understand the effect of edge-delay heterogeneity on individual regrets of agents.
\bibliographystyle{ACM-Reference-Format}
| {'timestamp': '2022-12-02T02:12:56', 'yymm': '2211', 'arxiv_id': '2211.17154', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17154'} | arxiv |
\section{Introduction}
Generative models for approximating complicated and high-dimensional probability distributions gained increasingly attention over the last years.
One subclass of generative models are normalizing flows \cite{DKB2014,RM2015}.
They are learned diffeomorphisms which push forward a complicated probability
distribution to a simple one. More precisely, we learn a diffeomorphism $\mathcal T$ such that a distribution $P_X$
can be approximately represented as $\mathcal T^{-1}_\#P_Z$ for a simple distribution $P_Z$.
Several architectures of normalizing flows were proposed in the literature including Glow \cite{KD2018}, real NVP \cite{DSB2017}, continuous normalizing flows \cite{CRBD2018,GCBSD2018,OFLR2021} and autoregressive flows \cite{CTA2019,DBMP2019,HKLC2018,PPM2017}.
In this paper, we particularly focus on residual flows \cite{BGCDJ2019,CBDJ2019}.
Here, the basic idea is that residual neural networks \cite{HZRS2016} are invertible as long as each subnetwork has
a Lipschitz constant smaller than one.
In \cite{HCTC2020}, the authors figure out a relation between residual flows and Monge maps in optimal transport problems.
For training residual flows, one needs to control the Lipschitz constant of the considered subnetworks.
Training neural networks with a prescribed Lipschitz constant was addressed in several papers \cite{GFPC2021,MKKY2018,PRTW2021,SGL2018}.
For example, the authors of \cite{MKKY2018} propose to rescale the transition matrices after each optimization step such that
the spectral norm is smaller or equal than one.
However, it is well known that enforcing a small Lipschitz constant within a neural network can lead
to limited expressiveness.
In this paper, we propose to overcome these limitations by using proximal neural networks (PNNs).
PNNs were introduced in \cite{HHNPSS2019,HNS2020} and are by construction averaged operators.
Using scaled PNNs as subnetworks, we prove that a residual neural network is invertible even if the scaled PNN has
a Lipschitz constant larger than one.
Further, we consider Bayesian inverse problems
$$
Y=F(X)+\eta,
$$
with an ill-posed forward operator $F$ and some noise $\eta$.
Here, we aim to reconstruct the posterior distributions $P_{X|Y=y}$ with using normalizing flows.
To this end, we apply a conditional generative model \cite{ALKRK2019,HHS2021,MO2014,SLY2015}.
For normalizing flows, this means that we aim to learn a mapping $\mathcal T(y,x)$ such that for any $y$ it holds
approximately $P_{X|Y=y}\approx \mathcal T(y,\cdot)^{-1}_\#P_Z$ for a simple distribution $P_Z$.
Further, we show how proximal residual flows can be used for conditional generative modeling by constructing
conditional proximal residual flows.
Finally, we demonstrate the power of (conditional) proximal residual flows by numerical examples. First, we use proximal residual flows
for sampling and density estimation of some complicated probability distributions
including adversarial toy examples and molecular structures.
Afterwards, we apply conditional proximal residual flows for reconstructing the posterior distribution in an
inverse problem of scatterometry and for certain mixture models.
The paper is organized as follows.
In Section~\ref{sec_iResPNNs}, we first revisit residual flows and proximal neural networks.
Afterwards we introduce proximal residual flows which combine both.
Then, we extend proximal residual flows to Bayesian inverse problems in Section~\ref{sec_conditional_iResPNNs}.
We demonstrate the performance of proximal residual flows in Section~\ref{sec_num}.
Conclusions are drawn in Section~\ref{sec_conc}.
\section{Proximal Residual Flows}\label{sec_iResPNNs}
Given i.i.d.~samples $x_1,...,x_N$ from an $n$-dimensional random variable $X$ with unknown distribution $P_X$, a normalizing
flow aims to learn a diffeomorphism $\mathcal T\colon\R^n\to\R^n$ such that
$
P_X\approx \mathcal T^{-1}_\# P_Z
$.
To this end, the diffeomorphism will be a neural network $\mathcal T_\theta$ with parameters $\theta$, which
is by construction invertible.
For the training, we consider the maximum likelihood loss, i.e., we minimize
$$
\mathcal L(\theta)=\sum_{i=1}^Np_{{\mathcal T_\theta}^{-1}_\#P_Z}(x_i).
$$
Note, that using the change of variables formula for probability density functions, we have that
$p_{{\mathcal T_\theta}^{-1}_\#P_Z}(x)$ can be computed by
$$
p_{{\mathcal T_\theta}^{-1}_\#P_Z}(x)=p_Z(\mathcal T_\theta(x))|\nabla \mathcal T_\theta(x)|.
$$
In this section, we propose a new architecture for normalizing flows based on residual flows \cite{CBDJ2019}
and proximal neural networks \cite{HHNPSS2019,HNS2020}.
\subsection{Residual Flows}\label{sec_iResNets}
Residual flows were introduced in \cite{BGCDJ2019,CBDJ2019}.
The basic idea is to consider residual neural networks, where each subnetwork is constraint to be
$c$-Lipschitz continuous for some $c<1$, i.e., we have $T=L_K\circ\cdots\circ L_1$, where each mapping $L_k$ has the form
\begin{align}
L\colon\R^n\to\R^n,\quad L(x)=x+g(x),\quad \Lip(g)<1.\label{eq_residual_layer}
\end{align}
Then, Banach's fix point theorem yields that $L$ is invertible and the inverse $L^{-1}(y)$ can be computed by the limit
of the iteration
$$
x^{(r+1)}=y-g(x^{(r)}),\quad x^{(0)}=y.
$$
For ensuring the Lipschitz continuity of $g$ during the training of residual flows,
the authors of \cite{BGCDJ2019,CBDJ2019} suggested to use spectral normalization \cite{GFPC2021,MKKY2018}.
Finally, to evaluate and differentiate $\log(|\nabla \mathcal T(x)|)$, we have to evaluate and differentiate $\log(|\nabla L(x)|)$
for each residual block $L$.
In small dimensions, this can be done by algorithmic differentiation, which is in high dimensions computationally intractable.
Here we can apply the following theorem is from \cite[Theorem 1, Theorem 2]{CBDJ2019} which is based on an expansion of $\nabla L$
into a Neumann series.
\begin{theorem}\label{thm_eval_logdet}
Let $Q$ be a random variable on $\Z_{>0}$ such that $P(Q=k)>0$ for all $k\in\Z_{>0}$ and define $p_k=P(Q\geq k)$.
Consider the function $L(x)=x+g(x)$, where $g\colon\R^n\to\R^n$ is differentiable and fulfills $\mathrm{Lip}(g)<1$.
Then, it holds
$$
\log(|\nabla L(x)|)=\E_{v\sim \mathcal N(0,I),q\sim P_Q}\left[\sum_{k=1}^q\frac{(-1)^{k+1}}{k}\frac{v^\tT(\nabla g(x))^k v}{p_k}\right]
$$
and
$$
\frac{\partial}{\partial \theta} \log(|\nabla L(x)|)=\E_{v\sim \mathcal N(0,I),q\sim P_Q}\left[\left(\sum_{k=0}^q\frac{(-1)^k}{p_k} v^\tT (\nabla g(x))^k\right)\frac{\partial (\nabla g(x))}{\partial \theta} v\right].
$$
\end{theorem}
\subsection{Proximal Neural Networks}\label{sec_PNNs}
Averaged operators and in particular proximity operators received increasingly attention in deep learning over the last years \cite{BPCPE2011,CP2011,GOY2017}.
For a proper, convex and lower semi-continuous function $f\colon\R^d\to\R\cup\{\infty\}$, the proximity operator of $f$ is given by
$$
\prox_{\lambda f}(x)=\argmin_{y\in\R^n}\{\tfrac{1}{2\lambda}\|x-y\|^2+f(y)\}.
$$
Proximity operators are in particular $\tfrac{1}{2}$-averaged operators, i.e.,
$$
\prox_{\lambda f}(x)=\tfrac12 x+\tfrac12 R(x),\quad\text{for some }R\text{ with } \Lip(R)\leq 1.
$$
In \cite{CP2020} the authors observed that most activation functions of neural networks are proximity operators.
They proved that an activation function $\sigma$ is a proximity operator with respect to some function $g$, which has $0$ as a
minimizer, if and only if $\sigma$ is $1$-Lipschitz continuous, monotone increasing and fulfills $\sigma(0)=0$.
They called the class of such activation functions \emph{stable activation functions}.
Using this result, Proximal Neural Networks (PNNs) were introduced in \cite{HHNPSS2019} as the concatenation of blocks of the form
$$
B(\cdot;T,b,\alpha)\coloneqq T^\tT\sigma_\alpha(T\cdot+b),
$$
where $b\in\R^d$, $T$ or $T^\tT$ is in the Stiefel manifold $\St(n,m)=\{T\in\R^{n,m}:T^\tT T=I\}$ and $\sigma_\alpha$ is a stable activation function which may depend on
some additional parameter $\alpha$.
It can be shown that $B$ is again a proximity operator of some proper, convex
and lower semi-continuous function, see \cite{HHNPSS2019}.
Now a PNN with $K$ layers is defined as
$$
\Phi(\cdot;u)=B_K(\cdot;T_K,b_K,\alpha_K)\circ\cdots\circ B_1(\cdot;T_1,b_1,\alpha_1),
$$
where $u=((T_k)_{k=1}^K,(b_k)_{k=1}^K,(\alpha_k)_{k=1}^K)$. Since $\Phi$ is the concatenation of $K$ $\tfrac12$-averaged operators,
we obtain that $\Phi$ is $K/(K+1)$-averaged.
From a numerical viewpoint, it was shown in \cite{HNS2020} that (scaled) PNNs show a comparable performance as usual convolutional
neural networks for denoising.\\
The training of PNNs is not straightforward due to the condition that $T$ or $T^\tT$ are contained in the Stiefel manifold.
The authors of \cite{HHNPSS2019,HNS2020,HS2020} propose a stochastic gradient descent on the manifold of the parameters,
the minimization of a penalized functional and a stochastic variant of the inertial PALM algorithm \cite{BST2014,PS2016}.
However, to ensure the invertibility of proximal residual flows, it is important that the constraint $T_k\in\St(n,m)$
is fulfilled during the full training procedure.
Therefore, we propose the following different training procedure.
Instead of training the matrices $T_k$ directly, we define $T_k=P_{\St(n,m)}(\tilde T_k)$, where $P_{\St(n,m)}$ denotes
the orthogonal projection onto the Stiefel manifold.
For dense matrices and convolutions with full filter length, this projection is given by the $U$-factor of the polar decomposition,
see \cite[Sec.~7.3, Sec.~7.4]{HJ2013},
and can be computed by the iteration
$$
Y_{n+1}=2Y_n(I+Y_n^\tT Y_n)^{-1},\quad Y_0=\tilde T_k.
$$
see \cite[Chap.~8]{H2008}.
Unfortunately, we are not aware of a similar iterative algorithm for convolutions with limited filter length.
Finally, we optimize the matrices $\tilde T_k$ instead of the matrices $T_k$.
In order to ensure numerical stability, we regularize the distance of $\tilde T_k$ to the Stiefel manifold by the
penalizer $\|\tilde T_k^\tT \tilde T_k-I\|_F^2$.
\subsection{Proximal Residual Flows}\label{sec_sub_iResPNNs}
Now, we propose proximal residual flows as the concatenation $T=L_K\circ\cdots\circ L_1$ of residual blocks $L_k$ of the form
\begin{equation}\label{eq_iResPNN_layer}
L_k(x)=x+\gamma_k \Phi_k(x),
\end{equation}
where $\gamma_k>0$ is some constant and $\Phi_k$ is a PNN.
The following proposition ensures the invertibility of $L_k$ and $T$.
\begin{proposition}\label{prop_invertible}
Let $\Phi$ be a $t$-averaged operator with $\tfrac12<t\leq 1$ and let $0<\gamma<\tfrac{1}{2t-1}$.
Then, the function $L(x)=x+\gamma\Phi(x)$ is invertible and the inverse $L^{-1}(y)$ is given by the limit of the sequence
\begin{align}
x^{(r+1)}=\frac1{1+\gamma-\gamma t} y-\frac{\gamma t}{1+\gamma -\gamma t} R(x^{(r)}),\quad\text{where}\quad R(x)\coloneqq\frac{1}{t}\Phi(x)-\frac{1-t}{t}x.\label{eq_FP_averaged}
\end{align}
Additionally, if $\Phi$ is $t$-averaged with $0\leq t\leq\tfrac12$, then the above statement is true for arbitrary $\gamma>0$.
\end{proposition}
Note that $t=1$ in the proposition exactly recovers the case considered in \cite{BGCDJ2019}.
\begin{proof}
Since $\Phi$ is $t$-averaged, we get $\Phi=(1-t) I+ t R$, where $R\coloneqq \tfrac1t \Phi-\tfrac{1-t}{t} I$ is $1$-Lipschitz continuous.
Further, note that $\gamma<\tfrac{1}{2t-1}$ is equivalent to $\frac{\gamma t}{1+\gamma-\gamma t}<1$.
Therefore, Banach's fix point theorem yields that the sequence $(x^{(r)})_r$ converges to the unique fix point $x$ of
$$
x=\frac1{1+\gamma-\gamma t} y-\frac{\gamma t}{1+\gamma -\gamma t} R(x)
$$
which is equivalent to $y=x+\tfrac{\gamma}{2}(I+R)(x)=x+\gamma\Phi$. In particular, $x$ is the unique solution of $L(x)=y$.
In the case $t\leq\tfrac12$, we have that $\frac{\gamma t}{1+\gamma-\gamma t}<1$ is true for any $\gamma>0$ such that the same argumentation applies.
\end{proof}
Using the proposition, we obtain, that $L_k$ from \eqref{eq_iResPNN_layer} is invertible, as long as $0<\gamma_k<\tfrac{\kappa+1}{\kappa-1}$,
where $\kappa$ is the number of layers of $\Phi_k$.
In contrast to residual flows, the subnetworks $\gamma_k\Phi_k$ of proximal residual flows may
have Lipschitz constants larger than $1$.
For instance, if $\kappa=3$, then the upper bound on the Lipschitz constant of the subnetwork is $2$ instead of $1$.
\begin{remark}\label{rem_reproduce}
Let $\Phi=B_K\circ\cdots\circ B_1\colon\R^n\to\R^n$ be a PNN with layers $B_i(x)=T_i^\tT\sigma(T_ix+b_i)$.
Then, by definition, it holds $B_k\circ\cdots\circ B_1(x)\in\R^n$ for all $k=1,...,K$.
In particular, each layer of the PNN has at most $n$ neurons, which possibly limits the expressiveness.
We overcome this issue with a small trick.
Let
$$
A=\frac{1}{\sqrt{p}}\left(\begin{array}{c}I\\\vdots\\I\end{array}\right)\in\St(pn,n)
$$
and let $\Phi\colon \R^{pn}\to\R^{pn}$ be $t$-averaged.
Then, a simple computation yields that also
$
\Psi=A^\tT\Phi(A\cdot)
$
is a $t$-averaged operator.
In particular, we can use a PNN with $pn$ neurons in each layer instead of a PNN with $n$ neurons in each layer,
which increases the expressiveness of the network a lot.
\end{remark}
For the evaluation of $\log(|\nabla \mathcal T(x)|)$, we adapt Theorem~\ref{thm_eval_logdet} for proximal residual flows.
\begin{corollary}\label{cor_logdet_PNN}
Let $Q$ be a random variable on $\Z_{>0}$ such that $P(Q=k)>0$ for all $k\in\Z_{>0}$ and define $p_k=P(Q\geq k)$.
Consider the function $L(x)=x+\gamma \Phi(x)$, where $\Phi\colon\R^n\to\R^n$ is differentiable and $t$-averaged for $t\in(\tfrac12,1]$ and $0<\gamma<\tfrac1{2t-1}$.
Then, it holds
$$
\log(|\nabla L(x)|)=\E_{v\sim \mathcal N(0,I),q\sim P_Q}\left[\sum_{k=1}^q\frac{(-1)^{k+1}}{k}\frac{v^\tT(\tfrac{\gamma t}{1+\gamma-\gamma t} \nabla R(x))^k v}{p_k}\right]+n\log(1+\gamma-\gamma t),
$$
where $R(x)=\frac{1}{t}\Phi(x)-\frac{1-t}{t}x$.
Further, we have
$$
\frac{\partial}{\partial \theta} \log(|\nabla L(x)|)=\E_{v\sim \mathcal N(0,I),q\sim P_Q}\left[\left(\sum_{k=0}^q\frac{(-1)^k}{p_k} v^\tT (\tfrac{\gamma t}{1+\gamma-\gamma t}\nabla R(x))^k\right)\frac{\partial (\tfrac{\gamma t}{1+\gamma-\gamma t}\nabla R(x))}{\partial \theta} v\right].
$$
Additionally, if $\Phi$ is $t$-averaged for $0\leq t\leq\tfrac12$, then the above statement holds true for any $\gamma>0$.
\end{corollary}
\begin{proof}
Since $\Phi$ is $t$-averaged, it holds $\Phi=(1-t)I+tR$, where $R=\tfrac1{t}\Phi-\tfrac{1-t}{t} I$ is $1$-Lipschitz continuous.
Thus, we have
$$
L=(1+\gamma-\gamma t)I+\gamma t R=(1+\gamma-\gamma t)(I+\tfrac{\gamma t}{1+\gamma-\gamma t}R),
$$
such that
$$
\log(|\nabla L(x)|)=\log(|\nabla (I+\tfrac{\gamma t}{1+\gamma-\gamma t}R)(x)|)+n\log(1+\gamma-\gamma t).
$$
Now, since $\tfrac{\gamma t}{1+\gamma-\gamma t}<1$, applying Theorem~\ref{thm_eval_logdet} with $g=\tfrac{\gamma t}{1+\gamma-\gamma t}R$
gives the assertion.
\end{proof}
In the special case, that the PNN $\Phi$ consists of only one layer, we can derive the log-determinant explicitly by the following
lemma.
\begin{lemma}
Let $\Phi(x)=T^\tT\sigma(Tx+b)$ for $T^\tT\in\St(n,m)$, $n\geq m$ and a differentiable activation function $\sigma\colon\R\to\R$. Then, the $\log$-determinant of the Jacobian of $L(x)=x+\gamma\Phi(x)$ is given by
$$
\log(|\nabla L(x)|)=\sum_{i=1}^m\log(1+\gamma\sigma_i'(Tx+b)),
$$
where $\sigma_i'(Tx+b)$ is the $i$th component of $\sigma'(Tx+b)$.
\end{lemma}
\begin{proof}
Let $\tilde T$ be a matrix, such that $S=(T^\tT|\tilde T^\tT)\in\R^{n\times n}$ is an orthogonal matrix. We have that
$$
\nabla\Phi(x)=T^\tT\sigma'(Tx+b)T, \quad \nabla L(x)=I_n+\gamma T^\tT\sigma'(Tx+b)T.
$$
Then, by orthogonality of $S$, it follows
$$
|\nabla L(x)|=|S^\tT||I_n+\gamma T^\tT\sigma'(Tx+b) T||S|=|I_n + \gamma (T S)^\tT\sigma'(Tx+b) (T S)|.
$$
Since $T^\tT\in\St(n,m)$, it holds by the definition of $S$ that $TS=(I_m|0)$ such that
$$
|\nabla L(x)|=\left|\left(\begin{array}{cc}I_m+\gamma \sigma'(Tx+b)&0\\0&I_{n-m}\end{array}\right)\right|=\prod_{i=1}^m 1+\gamma\sigma_i'(Tx+b).
$$
Taking the logarithm proves the statement.
\end{proof}
\section{Conditional Proximal Residual Flows}\label{sec_conditional_iResPNNs}
In the following, we consider for a random variable $X$ the inverse problem
\begin{align}\label{eq_inv_prob}
Y=F(X)+\eta,
\end{align}
where $F\colon\R^n\to\R^d$ is an ill-posed/ill-conditioned forward operator and $\eta$ is some noise.
Now, we aim to train a conditional normalizing flow model for reconstructing all posterior distributions $P_{X|Y=y}$, $y\in\R^d$.
More precisely, we want to learn a mapping $\mathcal T\colon\R^d\times\R^n\to\R^n$ such that $\mathcal T(y,\cdot)$
is invertible for all $y\in\R^d$ and
$$
P_{X|Y=y}=\mathcal T(y,\cdot)^{-1}_\#P_Z.
$$
For this purpose, $\mathcal T_\theta$ will be a neural network with parameters $\theta$. We learn $\mathcal T_\theta$
from i.i.d.~samples $(x_1,y_1),...,(x_N,y_N)$ of $(X,Y)$ using the maximum likelihood loss
$$
\mathcal L(\theta)=\sum_{i=1}^Np_{{\mathcal T_{\theta}(y_i,\cdot)^{-1}}_\#P_Z}(x_i)\approx\E_{y\sim P_Y}[\mathrm{KL}(P_{X|Y=y},P_{{\mathcal T_\theta(y,\cdot)^{-1}}_\#P_Z})]+\mathrm{const}.
$$
Note that for the real NVP architecture \cite{DSB2017}, such flows were considered in \cite{ALKRK2019,DSLM2021,HHS2021}.
For using proximal residual flows as conditional normalizing flows, we need the following lemma.
\begin{lemma}
Let $\Phi=(\Phi_1,\Phi_2)\colon\R^{d}\times\R^n\to\R^{d}\times\R^{n}$ be a $t$-averaged operator. Then, for any $y\in\R^d$, the operator $\Phi_2(y,\cdot)$ is $t$-averaged.
\end{lemma}
\begin{proof}
Since $\Phi$ is $t$-averaged, we have that $\Phi(y,x)=(1-t)(y,x)+tR(y,x)$ for some $1$-Lipschitz function $R=(R_1,R_2)\colon\R^n\times\R^d\to\R^n\times\R^d$. Now let $y\in\R^d$ be arbitrary fixed. Due to the Lipschitz continuity of $R$, it holds for $x_1,x_2\in\R^n$ that
$$
\|R(y,x_1)-R(y,x_2)\|\leq\|(y,x_1)-(y,x_2)\|=\|x_1-x_2\|.
$$
Thus, $R_2(\cdot,y)$ is $1$-Lipschitz continuous and we get by definition that
$$
\Phi_2(y,x)=(1-t)x+tR_2(y,x),
$$
such that $\Phi_2(y,\cdot)$ is a $t$-averaged operator.
\end{proof}
Now, we define a conditional proximal residual flows as a mapping $\mathcal T\colon\R^d\times\R^n\to\R^n$ given by $\mathcal T(\cdot,y)=L_K(\cdot,y)\circ\cdots\circ L_1(\cdot,y)$ with
\begin{equation}\label{eq_cprf_layer}
L_k(y,x)=x+\gamma_k\Phi_{k,2}(y,x),
\end{equation}
where $\Phi_k=(\Phi_{k,1},\Phi_{k,2})\colon \R^n\times\R^d\to\R^n\times\R^d$ is a PNN.
By definition, we have that $\mathcal T(y,\cdot)$ is a proximal residual flow for any fixed $y$ such that the invertibility result in
Proposition \ref{prop_invertible} applies.
\section{Numerical Examples}\label{sec_num}
In this section, we demonstrate the performance of proximal residual flows
by numerical examples. First, in Subsection~\ref{subsec_den} we apply proximal residual flows in an unconditional setting.
Afterwards, in Subsection~\ref{subsec_con}, we consider a conditional setting with Bayesian inverse problems.
In both cases, we compare our results with residual flows \cite{BGCDJ2019,CBDJ2019} and a variant of the real NVP architecture \cite{AKWR2018,DSB2017}.
Within all architectures we use activation normalization \cite{KD2018} after every invertible block.
For evaluating the quality of our results, we will use the following error measures.
\begin{itemize}
\item The \textbf{empirical Kullback Leibler divergence} of two probability measures $P$ and $Q$ on $[0,1]^d$ approximates $\mathrm{KL}(P,Q)$
based on samples. Given samples $x_1,...,x_N$ of $P$ and samples $y_1,...,y_M$ of $Q$, the empirical KL divergence of $P$ and
$Q$ on $[0,1]^d$ using a $d_1\times\ldots\times d_d$ grid is given by
$$
\sum_{i_1=0}^{d_1-1}\cdots\sum_{i_d=0}^{d_d-1} h_{i_1,...,i_d}\log\Big(\frac{h_{i_1,...,i_d}}{\tilde h_{i_1,...,i_d}}\Big),
$$
where $h$ and $\tilde h$ are the normalized histograms of $(x_i)_i$ and $(y_i)_i$, i.e., $h$ is defined by
$$
h_{i_1,...,i_d}=\frac{\#\{i:x_i\in[\tfrac{i_1}{d_1},\tfrac{i_1+1}{d_1}]\times\ldots\times[\tfrac{i_d}{d_d},\tfrac{i_d+1}{d_d}]\}}{N}
$$
and $\tilde h$ is defined analogously.
\item We evaluate the \textbf{empirical Wasserstein distance} of two probability measures $P$ and $Q$ by computing
$W_2\bigl(\frac1N\sum_{i=1}^N\delta_{x_i},\frac1N\sum_{i=1}^N\delta_{y_i}\bigr)$, where the $x_i$ are iid samples from $P$
and the $y_i$ are iid samples from $Q$.
\end{itemize}
All implementations are done in Python and Tensorflow.
We run them on a single NVIDIA GeForce GTX 2060 Super GPU with 8 GB memory.
For the training we use the Adam optimizer \cite{KB2015}.
The training parameters are given in Table~\ref{tab_details}.
We use fully connected PNNs
with three layers as subnetworks and evaluate the log-determinant exactly by backprobagation.
\begin{table}
\centering
\begin{tabular}{c|cccccccccc}
Method & $n$ & $d$ & $K$ & $p$ & $h$ & $\gamma$ & $b$ & $e$ & $s$ & $\tau$\\\hline
Toy examples & $2$ & - & $20$ & $64$ & $64$ & $1.99$ & $200$ & $20$ & $2000$ & $10^{-3}$\\
Alanine Dipeptide & $66$ & - & $20$ & $2$ & $100$ & $1.99$ & $200$ & $20$ & $2000$ & $10^{-3}$\\
Circle & $2$ & $1$ & $20$ & $64$ & $64$ & $1.99$ & $800$ & $20$ & $2000$ & $10^{-3}$ \\
Scatterometry & $3$ & $23$ & $20$ & $10$ & $128$ & $1.99$ & $1600$ & $20$ & $2000$ & $5\cdot 10^{-3}$\\
Mixture models & $50$ & $50$ & $20$ & $2$ & $128$ & $1.99$ & $200$ & $20$ & $2000$ & $5\cdot 10^{-3}$
\end{tabular}
\caption{Implementation details for the numerical experiments. The table contains for each experiment the dimension $n$,
the dimension $d$ of the condition, the number of residual blocks $K$, the parameter $p$ from Remark~\ref{rem_reproduce}, the hidden dimension $h$ within
the subnetwork, the parameter $\gamma$ in the equations \eqref{eq_iResPNN_layer} and \eqref{eq_cprf_layer}, the batch size $b$, the number of epochs $e$, the number of steps per epoch $s$ and the learning rate $\tau$.}
\label{tab_details}
\end{table}
\subsection{Unconditional Examples.}\label{subsec_den}
In the following, we apply proximal residual flows for density estimation, i.e., we are in the setting of Section~\ref{sec_iResPNNs}.
\paragraph{Toy Densities.}
\begin{figure}[t]
\centering
\begin{subfigure}[t]{0.23\textwidth}
\includegraphics[width=\textwidth]{imgs/modes_gt}
\end{subfigure}
\begin{subfigure}[t]{0.23\textwidth}
\includegraphics[width=\textwidth]{imgs/moons_gt}
\end{subfigure}
\begin{subfigure}[t]{0.23\textwidth}
\includegraphics[width=\textwidth]{imgs/circles_gt}
\end{subfigure}
\begin{subfigure}[t]{0.23\textwidth}
\includegraphics[width=\textwidth]{imgs/checkboard_gt}
\end{subfigure}
\begin{subfigure}[t]{0.23\textwidth}
\includegraphics[width=\textwidth]{imgs/modes_recon}
\end{subfigure}
\begin{subfigure}[t]{0.23\textwidth}
\includegraphics[width=\textwidth]{imgs/moons_recon}
\end{subfigure}
\begin{subfigure}[t]{0.23\textwidth}
\includegraphics[width=\textwidth]{imgs/circles_recon}
\end{subfigure}
\begin{subfigure}[t]{0.23\textwidth}
\includegraphics[width=\textwidth]{imgs/checkboard_recon}
\end{subfigure}
\caption{Reconstruction of toy densities. Top: Ground truth, Bottom: Reconstructions with proximal residual flows.}
\label{fig_toy}
\end{figure}
First, we train proximal residual flows onto some toy densities, namely 8 modes, two moons, two circles and checkboard.
Samples from the training data and the reconstruction with proximal residual flows are given in Figure~\ref{fig_toy}.
We observe that the proximal residual flow is able to learn all of the toy densities very well, even though
it was shown in \cite{HN2021} that a diffeomorphism, which pushes forward a unimodal distribution to a multimodal one must have a large
Lipschitz constant.
\paragraph{Alanine Dipeptide.}
Next, we evaluate proximal residual flows for an example from \cite{AMD2021,WKN2020}\footnote{For the data generation and evaluation of this example,
we use the code of \cite{WKN2020} available at \url{https://github.com/noegroup/stochastic_normalizing_flows}.}.
Here, we aim to estimate the density of molecular structures of alanine dipeptide molecules.
The structure of such molecules is described by an $66$-dimensional vector.
For evaluating the quality of the results, we follow \cite{WKN2020} and consider the marginal distribution onto the torsion angles, as introduced in \cite{NOKW2019}.
Afterwards, we consider the empirical Kullback Leibler divergence between these marginal distributions of the training data and the
reconstruction by the proximal residual flows based on samples.
We compare our results with a normalizing flow consisting of $20$ real NVP blocks with subnetworks consisting of $3$
fully connected layers and a hidden dimension of $128$ and a residual flows with $20$ residual blocks, where each subnetwork
has three hidden layers with $128$ neurons.
The results are given in Table~\ref{tab_molecules}.
We observe that the proximal residual flow yields better results than the large real NVP network and the residual flow.
\begin{table}
\centering
\scalebox{.9}{
\begin{tabular}{c|c|c|c|c|c}
Method& $\phi$ & $\gamma_1$ & $\psi$ & $\gamma_2$ & $\gamma_3$\\\hline
Real NVP & $0.12\pm 0.05$ & $0.14\pm 0.04$ & $0.06\pm 0.03$ & $0.04\pm 0.01$ & $0.07\pm 0.01$\\
Residual Flows & $0.12\pm 0.11$ & $0.24\pm 0.29$ & $0.10\pm 0.08$ & $0.06\pm 0.03$ & $0.07\pm 0.02$\\
Proximal Residual Flow & $0.05\pm 0.02$ & $0.06\pm 0.01$ & $0.03\pm 0.00$ & $0.05 \pm 0.01$ & $0.05\pm 0.01$
\end{tabular}
}
\caption{Empirical Kullback Leibler divergence between one-dimensional marginal distributions corresponding to the torsion angles $\phi$, $\gamma_1$, $\psi$, $\gamma_2$ and $\gamma_3$. The results are averaged
over five independent runs.}
\label{tab_molecules}
\end{table}
\subsection{Posterior Reconstruction}\label{subsec_con}
Now, we aim to find a conditional proximal residual flow for reconstructing the posterior distribution $P_{X|Y=y}$ for all $y\in\R^d$.
That is, we consider the setting from Section~\ref{sec_conditional_iResPNNs}.
\paragraph{Circle.}
\begin{figure}[t]
\centering
\begin{subfigure}[c]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_prior}
\end{subfigure}
\begin{subfigure}[c]{0.7\textwidth}
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final0/circ1_0}
\end{subfigure}\hfill
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final0/circ0_7}
\end{subfigure}\hfill
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final0/circ0_0}
\end{subfigure}\hfill
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final0/circ-0_7}
\end{subfigure}\hfill
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final0/circ-1_0}
\end{subfigure}
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final1/circ1_0}
\caption*{$y=1.0$}
\end{subfigure}\hfill
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final1/circ0_7}
\caption*{$y=0.7$}
\end{subfigure}\hfill
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final1/circ0_0}
\caption*{$y=0$}
\end{subfigure}\hfill
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final1/circ-0_7}
\caption*{$y=-0.7$}
\end{subfigure}\hfill
\begin{subfigure}[t]{0.2\textwidth}
\includegraphics[width=\textwidth]{imgs/circle_imgs_final1/circ-1_0}
\caption*{$y=-1.0$}
\end{subfigure}
\end{subfigure}
\caption{Left: Samples from the prior distribution of $X$ for the circle example.
Right: Histograms of samples from the reconstructed posterior distribution
$P_{X|Y=y}\approx \mathcal T(\cdot,y)^{-1}_\#P_Z$ for $y\in\{1,0.7,0,-0.7,-1\}$ within the circle example.
Top: first coordinate, Bottom: second coordinate.}
\label{fig_circle}
\end{figure}
First, we consider the inverse problem \eqref{eq_inv_prob} specified as follows.
Let the prior distribution $P_X$ be the convolution of uniform distribution on the unit circle in $\R^2$ with
the normal distribution $\epsilon\sim\N(0,0.1^2 I_2)$. Samples of $P_X$ are illustrated on the left of Figure~\ref{fig_circle}.
Further let the operator $F\colon\R^2\to\R$ be given by $y\coloneqq F(x_1,x_2)=x_1$ and define the noise distribution by $\eta\sim\mathcal N(0,0.02^2 I)$.
Now, we train a conditional proximal residual flow $\mathcal T(x,y)$ such that it holds approximately
$$
P_{X|Y=y}\approx \mathcal T(\cdot,y)^{-1}_\#P_Z
$$
The right side of Figure~\ref{fig_circle} shows histograms of samples from the reconstructed posterior distribution
$\mathcal T(\cdot,y)^{-1}_\#P_Z$ for $y\in\{1,0.7,0,-0.7,-1\}$.
As expected the estimation of $P_{X|Y=y}$ is unimodal for $y\in\{1,-1\}$ and bimodal for $y\in\{0.7,0,-0.7\}$.
\paragraph{Scatterometry.}
Next, we apply proximal residual flows to a Bayesian inverse problem in
scatterometry with
a nonlinear forward operator $F\colon\R^3\to\R^{23}$.
It describes the diffraction of monochromatic lights on line gratings
which is a non-destructive technique to determine the structures of photo masks.
For a detailed description, we refer to \cite{HGB2015,HGB2018}.
We use the code of \cite{HHS2021}\footnote{available at \url{https://github.com/PaulLyonel/conditionalSNF}.}
for the data generation, evaluation and the representation of the forward operator.
As no prior information about the parameters $x$ is given, we choose the prior distribution
$P_X$ to be the uniform distribution on $[-1,1]^3$.
Since we assume for normalizing flows that $P_X$ has a strictly positive density $p_X$,
we relax the probability density function of the uniform distribution
for $x=(x_1,x_2,x_3)\in\R^3$ by
$$
p_X(x)\coloneqq q(x_1)q(x_2)q(x_3), \quad q(x)\coloneqq \begin{cases}\frac{\alpha}{2\alpha+2}\exp(-\alpha(-1-x)),&$for $x<-1,\\
\frac{\alpha}{2\alpha+2},&$for $x\in[-1,1],\\\frac{\alpha}{2\alpha+2}\exp(-\alpha(x-1)),&$for $x>1,\end{cases}
$$
where $\alpha\gg 0$ is some constant.
Note that for large $\alpha$ and $x_i$ outside of $[-1,1]$ the function $q$ becomes small such that $p_X$
is small outside of $[-1,1]^3$.
In our numerical experiments, $\alpha$ is set to $\alpha=1000$.
We compare the proximal residual flow with the normalizing flow with real NVP architecture from \cite{HHS2021}
and with a residual flow of $20$ residual blocks, where each subnetwork
has three hidden layers with $128$ neurons.
As a quality measure, we use the empirical KL divergence of $P_{X|Y=y}$ and $\mathcal T(y,\cdot)^{-1}_\# P_Z$
for $100$ independent samples with $540000$ samples on a $75\times75\times75$ grid.
As a ground truth, we use samples from $P_{X|Y=y}$ which are generated by the Metropolis Hastings algorithm, see \cite{HHS2021}.
The average empirical KL divergences of the reconstructed posterior distributions over $100$ observations are given in Table~\ref{tab:scatter}.
The proximal residual flow gives the best reconstructions.
\begin{table}
\centering
\begin{tabular}{c|c|c|c}
&Real NVP&Residual Flows&Proximal Residual Flows\\\hline
KL & $0.773\pm 0.289$&$0.913\pm 0.407$&$0.637\pm0.263$
\end{tabular}
\caption{Average empirical KL divergence of the different reconstructions for the scatterometry example.}
\label{tab:scatter}
\end{table}
\paragraph{Mixture models.}
Next, we consider the Bayesian inverse problem \eqref{eq_inv_prob}, where the forward operator $F\colon\R^{50}\to\R^{50}$
is linear and given by the diagonal matrix $A\coloneqq 0.1\,\mathrm{diag}\bigl((\tfrac1n)_{n=1}^{50}\bigr)$.
Moreover, we add Gaussian noise with standard deviation $0.05$.
As prior distribution $P_X$, we choose a Gaussian mixture model with $5$ components, where we draw the means uniformly from $[-1,1]^{50}$
and set the covariances to $0.01^2\,I$.
Note that in this setting, the posterior distribution can be computed analytically, see \cite[Lem.~6.1]{HHS2021}.
We compare our results with a normalizing flow consisting of $20$ real NVP blocks with subnetworks consisting of $3$
fully connected layers and a hidden dimension of $128$ and a residual flow with $20$ residual blocks, where each subnetwork
has three hidden layers with $128$ neurons.
Since the evaluation of the empirical KL divergence is intractable in high dimensions, we use the empirical Wasserstein distance
as an error measure. The results are given in Table~\ref{tab:mix}.
We observe, that the proximal residual flows outperforms both comparing methods significantly.
\begin{table}
\centering
\begin{tabular}{c|c|c|c}
&Real NVP&Residual Flows&Proximal Residual Flows\\\hline
Wasserstein-$2$ distance &$2.122\pm 1.007$& $1.374\pm 0.050$&$1.028\pm 0.079$
\end{tabular}
\caption{Average Wasserstein-$2$ distance for the reconstructed posteriors to the ground truth over $100$ observations.}
\label{tab:mix}
\end{table}
\section{Conclusions}\label{sec_conc}
We introduced proximal residual flows, which improve the expressiveness of residual flows by the use of proximal neural networks.
In particular, we proved that proximal residual flows are invertible, even though the Lipschitz constant of the subnetworks
is larger than one.
Afterwards, we extended the framework of proximal residual flows to the problem of posterior reconstruction within Bayesian inverse
problems by using conditional generative modelling.
Finally, we demonstrated the performance of proximal residual flows by numerical examples.
This work can be extended in several directions.
First, it is an open question, how to generalize the training procedure in this paper to convolutional networks.
In particular, finding an efficient algorithm which computes the orthogonal projection onto the space of
orthogonal convolutions with limited filter length is left for future research.
Moreover, every invertible neural network architecture requires an exploding Lipschitz constant for reconstructing
multimodal \cite{HN2021,SDDD2022} or heavy tailed distributions \cite{JKYB2020}.
To overcome these topological constraints, the authors of \cite{AMD2021,HHS2021,MARD2022,WKN2020}
propose to combine normalizing flows with stochastic sampling methods.
Finally, we could improve the expressiveness of proximal residual flows by combining
them with other generative models, see e.g.~\cite{HHS2021generalized}.
\subsubsection*{Acknowledgements}
Funding by the German Research Foundation (DFG) within the project STE 571/15-1 is gratefully acknowledged.
\bibliographystyle{abbrv}
| {'timestamp': '2022-12-01T02:19:23', 'yymm': '2211', 'arxiv_id': '2211.17158', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17158'} | arxiv |
\section{Introduction}\label{sec:intro}
Semantics of various formalisms for knowledge representation can often be described by fixpoints of corresponding operators. For example, in many logics theories
of a set of formulas can be seen as fixpoints of the underlying consequence operator~\cite{tarski1936concept}. Likewise, in logic programming, default logic or formal
argumentation, all the major semantics can be formulated as different types of fixpoints of the same operator (see~\cite{denecker2000approximations}). Such operators are usually non-monotonic,
and so one cannot always be sure whether their fixpoints exist, and how they can be constructed.
In order to deal with this `illusive nature' of the fixpoints, Denecker, Marek and Truszczy{\'n}ski~\cite{denecker2000approximations} introduced a method for \emph{approximating\/}
each value $z$ of the underlying operator by a pair of elements $(x,y)$. These elements intuitively represent lower and upper bounds on $z$, and so a corresponding
\emph{approximation operator\/} for the original, non-monotonic operator, is constructed. If the approximating operator that is obtained is precision-monotonic, intuitively meaning
that more precise inputs of the operator give rise to more precise outputs, then by Tarski and Knaster's Fixpoint Theorem the approximating operator has fixpoints that can be constructively
computed, and which in turn approximate the fixpoints of the approximated operator, if such fixpoints exist.
The usefulness of the algebraic theory that underlies the computation process described above was demonstrated on several knowledge representation formalisms, such as propositional
logic programming~\cite{denecker2012approximation}, default logic~\cite{denecker2003uniform}, autoepistemic logic~\cite{denecker2003uniform}, abstract argumentation and abstract
dialectical frameworks~\cite{strass2013approximating}, hybrid MKNF~\cite{liu2022alternating}, the graph description language SCHACL~\cite{bogaerts2021fixpoint}, and active
integrity constraints~\cite{ai/BogaertsC18}, each one of which was shown to be an instantiation of this abstract theory of approximation. More precisely, it was shown that various
semantics of the formalisms mentioned above correspond to the various fixpoints defined in~\cite{denecker2000approximations}. This means that approximation fixpoint theory
(AFT, for short) captures the uniform principles underlying all these non-monotonic formalisms in a purely algebraic way.
Besides its unifying capabilities, AFT also allows for a straightforward definition of semantics for new formalisms. Indeed, one merely has to define an approximation of the
operator of interest, and AFT then automatically gives rise to a family of semantics with several desirable properties. This potential of AFT for a straightforward derivation
of semantics was demonstrated in e.g.\ logic programming, where it was used to define semantics for extensions of logic programs~\cite{antic2013hex,charalambidis2018approximation,pelov2007well}, in argumentation theory, where it was used to define semantics for weighted abstract dialectical
frameworks (ADFs,~\cite{bogaerts2019weighted}), in autoepistemic logic, where it was used for defining distributed variants that are suitable for studying access control
policies~\cite{vanhertum2016distributedautoepistemic}, and in second-order logic extended with non-monotone inductive definitions~\cite{dasseville2016compositional}.
Another benefit of AFT is that, due to its generality, it has proven useful to develop central concepts, such as strong equivalence~\cite{truszczynski2006strong},
groundedness~\cite{bogaerts2015grounded}, safe inductions~\cite{bogaerts2018safeInductions}, and stratification~\cite{vennekens2006splitting} for approximation operators in a purely algebraic way, which then allow to derive
results on these concepts for all the specific formalisms representable in AFT as straightforward corollaries.
So far, AFT has mainly been applied to \emph{deterministic\/} operators, i.e., operators which map single inputs to single outputs. This means that, while AFT is able to characterize
semantics for normal logic programs (i.e., programs consisting of rules with single atomic formulas as their head), \emph{disjunctive\/} logic programs~\cite{minker2002disjunctive}
(i.e., programs consisting of rules with disjunctions of atoms in their head) cannot be represented by it. The same holds for the representation of e.g.\ default logic versus disjunctive default
logic~\cite{Gelfond_et-al_PKRR_1991}, abstract argumentation versus set-based abstract argumentation~\cite{nielsen2006generalization} and the generalization of abstract dialectical
frameworks to~\emph{conditional\/} abstract dialectical frameworks~\cite{DBLP:conf/aaai/HeyninckTKRS22}.
Extending AFT to handle disjunctive information is therefore a desirable goal, as the latter has a central role in systems for knowledge representation and reasoning, and since
disjunctive reasoning capabilities provide an additional way of expressing uncertainty and indeterminism to many formalisms for non-monotonic reasoning. However, the introduction of disjunctive reasoning often increases the computational complexity of formalisms and thus extends their modeling capabilities~\cite{eiter1993complexity}.
Perhaps due to this additional expressiveness, the integration of non-deterministic reasoning with non-monotonic reasoning (NMR) has often proven non-trivial, as witnessed e.g.\
by the large body of literature on disjunctive logic programming~\cite{lobo1992foundations,minker2002disjunctive}. The implementation of non-deterministic reasoning in NMR
yielded the formulation of some (open) problems that are related to the combination of non-monotonic and disjunctive reasoning~\cite{beirlaen2017reasoning,beirlaen2018critical,bonevac2018defaulting}, or was restricted to limited semantics available for the core formalism, as is the case for
e.g.\ default logic~\cite{Gelfond_et-al_PKRR_1991}.
The goal of this work is to provide an adequate framework for modeling disjunctive reasoning in NMR. We do so by extending AFT to handle {\em non-deterministic operators\/}.
This idea was first introduced by Pelov and Truszczy{\'n}ski in~\cite{pelov2004semantics}, where some first results on two-valued semantics for disjunctive logic programs were
provided. In this paper, we further extend AFT for non-deterministic operators, which, among others, allows a generalization of the results of~\cite{pelov2004semantics} to the
three-valued case. In particular, we define several interesting classes of approximating fixpoints and show their existence, constructability and consistency where it is possible.
An application of this theory is demonstrated in the context of disjunctive logic programming. Furthermore, we show that our theory is a conservative generalization of the work
in~\cite{denecker2000approximations} of AFT for deterministic operators, in the sense that all the concepts introduced in this paper coincide with the deterministic counterparts when the operator at hand happens to be deterministic.
The outcome of this work is therefore a comprehensive study of semantics for non-monotonic formalisms incorporating non-determinism.
Its application is demonstrated in this paper in the context of disjunctive logic programming. Specifically, the paper contains the following contributions:
\begin{enumerate}
\item We define variants of both the \emph{Kripke-Kleene} and the \emph{stable/ well-founded} semantics, the \emph{interpretation} or \emph{fixpoint semantics\/} and \emph{state semantics\/}.
Interpretation semantics consist of single pairs of elements, and thus approximate of a single element. State semantics, on the other hand, consist of pairs of sets of elements, intuitively
viewed as a convex set, which approximates a set of elements.
\item We show that the Kripke-Kleene state and well-founded state (obtained as the least fixed point of the stable state operator) exist and are unique (Theorem \ref{theorem:ndso:fixpoint} and
Theorem~\ref{proposition:properties:of:well-founded:state}).
\item We show that the Kripke-Kleene state approximates any fixpoint of an approximation operator (Theorem~\ref{proposition:properties:of:well-founded:state}),
whereas the well-founded state approximates any stable fixpoint of an approximation operator (Theorem~\ref{proposition:properties:of:well-founded:state}).
In more detail, any fixpoint of an approximation operator respectively stable fixpoint of an approximation operator is an element of the convex set represented by the Kripke-Kleene state respectively the well-founded state.
\item We show that when restricting attention to deterministic operators, the theory reduces to deterministic AFT~\cite{denecker2000approximations} (Remark~\ref{remark:deterministic} and
Propositions~\ref{prop:deterministic:aft},~\ref{prop:KK-singletons} and~\ref{prop:stble:coincide:deterministic}).
\item We show that, just like in deterministic AFT, stable fixpoints are fixpoints that are minimal with respect to the truth order (Proposition \ref{prop:stable:is:minimal:fp}).
\item We demonstrate the usefulness of our abstract framework by showing how all the major semantics for disjunctive logic programming can be characterized as fixpoints
of an approximation operator for disjunctive logic programming. In more detail, the weakly supported models~\cite{brass1995characterizations} are characterized as
fixpoints of the operator ${\cal IC}_{\cal P}$ (Theorem~\ref{theo:correspondence:supported}), the stable models can be characterized as the stable fixpoints of
${\cal IC}_{\cal P}$ (Theorem~\ref{prop:stable:fixpoints:represent:stable:models}) and the well-founded semantics by Alc{\^a}ntara, Dam{\'a}sio and
Pereira~\cite{alcantara2005well} is strongly related to the well-founded state of ${\cal IC}_{\cal P}$ (Theorem~\ref{prop:well:founded:state:represents:alcantara:almost}).
\end{enumerate}
\paragraph*{Relation with previous work on non-deterministic approximation fixpoint theory}
This work extends and improves the work by Heyninck and Arieli \cite{DBLP:conf/kr/HeyninckA21}. %
The theory has been simplified on several accounts, among others since: (1)~we no longer require minimality of the elements of the range of a non-deterministic (approximation)
operator, which leads to a significant decrease in the number of lattice-constructions needed, (2)~the state operator is now more general and can
be defined on the basis of a non-deterministic approximation operator. Furthermore, intuitive explanations and illustrative examples are added throughout the paper.
As a by-product, the simplified framework allows us to identify and correct a faulty statement on the $\leq_i$-monotonicity
of the approximation operator for disjunctive logic programs, made by Heyninck and Arieli \cite{DBLP:conf/kr/HeyninckA21} (see Remark~\ref{remark:minimality:in:the:op}).
Both this paper and the work of Heyninck and Arieli~\cite{DBLP:conf/kr/HeyninckA21} were partially inspired by the work of Pelov and Truszczy{\'n}ski~\cite{pelov2004semantics} where,
to the best of our knowledge, the idea of a non-deterministic operator was first introduced in approximation fixpoint theory. Pelov and Truszczy{\'n}ski~\cite{pelov2004semantics} studied only two-valued semantics, whereas
we study the full range of semantics for AFT. Furthermore, Pelov and Truszczy{\'n}ski~\cite{pelov2004semantics} required minimality of the codomain of non-deterministic operators, which we do not require here.
\paragraph*{Outline of this paper}
This rest of this paper is organized as follows: In Section~\ref{sec:back:prelim} we recall the necessary background on disjunctive logic programming (Section~\ref{sec:LP})
and approximation fixpoint theory (Section~\ref{sec:AFT}). In Section~\ref{sec:nd:aft} we introduce non-deterministic operators and their approximation, and show some preliminary results
on approximations of non-deterministic operators. In Section~\ref{sec:theory:of:ndao} we %
study these non-deterministic approximation operators, showing their consistency and introducing and studying their fixpoint, Kripke-Kleene interpretation and the
Kripke-Kleene state semantics. In Section~\ref{sec:stable:semantics} we introduce and study the stable interpretation and state semantics, as well as the well-founded
state semantics. Related work is discussed in Section~\ref{sec:related:work}, followed by a conclusion in Section~\ref{sec:conc}.
\section{Background and Preliminaries}
\label{sec:back:prelim}
In this section, we recall the necessary basics of approximation fixpoint theory (AFT) for deterministic operators. We start with a brief survey on disjunctive logic
programming (DLP, Section~\ref{sec:LP}), which will serve to illustrate concepts and results of the general theory of non-deterministic AFT (Section~\ref{sec:AFT}).
\begin{remark}
Before proceeding, a note on notation: As we often have to move from the level of single elements to sets of elements, the paper is, by its nature, notationally heavy.
We tried to keep the notational burden as light as possible by staying consistent in our notation of different types of elements. For the readers convenience, we provide
already at this stage a summary of the notations of different types of sets (Table~\ref{tab:set-notations}), the preorders (Table~\ref{tab:orders}) and the operators (Table~\ref{tab:operators}) that are used in this paper.
\def\arraystretch{1,3}\tabcolsep=10pt
\begin{table}[htb]
\begin{tabular}{lll}
Elements & Notations & Example \\ \hline \hline
Elements of ${\cal L}$ & $x,y,\ldots$ & $x,y$\\
Sets of elements of ${\cal L}$ & $X,Y,\ldots$ & $\{x_1,y_1,x_2,y_2\}$ \\
Pairs of sets of elements of ${\cal L}$ & ${\bf X},{\bf Y},\ldots$ & $\{x_1,x_2,\ldots\}\times \{y_1,y_2,\ldots\}$\\
Sets of sets of elements of ${\cal L}$ & ${\cal X},{\cal Y},\ldots$ & $\{\{x_1,x_2\},\{x_1\}\}$
\end{tabular}
\caption{List of the notations of different types of sets used in this paper}
\label{tab:set-notations}
\end{table}
\begin{table}[htb]
\begin{tabular}{lll}
Preorder & Type & Definition \\ \hline \hline
\multicolumn{3}{c}{Element Orders} \\ \hline
$\leq$ & ${\cal L}$ & primitive \\
$\leq_i, \leq_t$ & ${\cal L}\times {\cal L}$ & bilattice orders (Definition~\ref{def:bilattice}) \\
$\leq_i$ & ${\cal L}^2\times {\cal L}^2$ & $(x_1,y_1) \leq_i (x_2,y_2)$ iff $x_1 \leq x_2$ and $y_1 \geq y_2$ \\
$\leq_t$ & ${\cal L}^2\times {\cal L}^2$ & $(x_1,y_1) \leq_t (x_2,y_2)$ iff $x_1 \leq x_2$ and $y_1 \leq y_2$ \\ \hline
\multicolumn{3}{c}{Set-based Orders} \\ \hline
$\preceq^S_L$ & $\wp({\cal L})\times \wp({\cal L})$ & $X \preceq^S_L Y$ iff for every $y\in Y$ there is an
$x\in X$ s.t.\ $x\leq y$\\
$\preceq^H_L$ & $\wp({\cal L})\times \wp({\cal L})$ & $X \preceq^H_L Y$ iff for every $x\in X$ there is an
$y\in Y$ s.t.\ $x\leq y$ \\
$\preceq^A_i$ & $\wp({\cal L})^2\times\wp({\cal L})^2$ & $(X_1,Y_1)\preceq_i^A (X_2,Y_2)$ iff $X_1\preceq^S_L X_2$ and $Y_2\preceq^H_L Y_1$\\
\end{tabular}
\caption{List of the preorders used in this paper.}
\label{tab:orders}
\end{table}
\begin{table}[htb]
\begin{tabular}{lclll}
Operator & Notation& Type & Definition \\ \hline \hline
Non-deterministic operator & $O$ & ${\cal L}\mapsto \wp({\cal L})$ & Definition \ref{def:non-deterministic-operator} \\
Non-deterministic approximation operator & ${\cal O}$ & ${\cal L}^2\mapsto \wp({\cal L})\times\wp({\cal L})$ & Definition \ref{def:ndao}\\
Non-deterministic state approx.\ operator & ${\cal O}'$& $\wp({\cal L}^2)\mapsto \wp({\cal L})\times\wp({\cal L})$ & Definition \ref{def:ndsao}\\ \hline
Stable operator & $S({\cal O})$ & ${\cal L}^2\mapsto \wp({\cal L})\times\wp({\cal L})$ & Definition \ref{def:stable:op}\\
\end{tabular}
\caption{List of the operators used in this paper.}
\label{tab:operators}
\end{table}
\end{remark}
\subsection{Disjunctive Logic Programming}
\label{sec:LP}
In what follows we consider a propositional\footnote{For simplicity we restrict ourselves to the propositional case.} language ${\mathfrak L}$,
whose atomic formulas are denote by $p,q,r$ (possibly indexed), and that contains the the propositional constants ${\sf T}$ (representing truth), ${\sf F}$ (falsity),
${\sf U}$ (unknown), and ${\sf C}$ (contradictory information). The connectives in ${\mathfrak L}$ include negation $\neg$, conjunction $\wedge$, disjunction $\vee$,
and implication $\leftarrow$. Formulas are denoted by $\phi$,$\psi$ (again, possibly indexed). Logic programs in ${\mathfrak L}$ may be divided to different kinds as follows:
\begin{itemize}
\item A (propositional) {\em disjunctive logic program\/} ${\cal P}$ in ${\mathfrak L}$ (a dlp, for short) is a finite set of rules of the form
$\bigvee_{i=1}^n p_i~\leftarrow~\psi$, where $\bigvee_{i=1}^n p_i$ (the rule's head) is a non-empty disjunction of atoms, and $\psi$ (the rule's body)
is a (propositional) formula.
\item A rule is called {\em normal\/}, if its body is a conjunction of literals (i.e., atomic formulas or negated atoms), and its head is atomic. A program
is {\em normal\/} if it consists only of normal rules; It is {\em positive\/} if there are no negations in the rules' bodies.
\item We call a rule \emph{disjunctively normal} if its body is a conjunction of literals (and its head is a non-empty disjunction of atoms).
A program is called {\em disjunctively normal\/}, if it consists of disjunctively normal rules.
\end{itemize}
The set of atoms occurring in a logic program $\mathcal{P}$ is denoted ${\cal A}_{\cal P}$. In what follows, we will often leave the reference to the language $\mathfrak{L}$
of ${\cal P}$ implicit.
\medskip
The primary algebraic structure for giving semantics to logic programs in our setting is the four-valued structure ${\cal FOUR}$, shown in Figure~\ref{fig:four}.
This structure was introduced by Belnap \cite{Be77a,Be77b} and later considered by Fitting~\cite{Fi91} and others in the context of logic programming. It is the simplest instance of a {\em bilattice\/} (Definition~\ref{def:bilattice}).\footnote{We refer to~\cite{Fi06,Fi20} for further details on bilattices and their applications in logic programming.}
\begin{figure}[hbt]
\begin{center}
\resizebox{0.4\textwidth}{!}{%
\begin{tikzpicture}[node distance=1cm, auto, >=latex, scale=0.5]
\node (a) {};
\node (b) [above of=a, yshift=3cm] {$\leq_i$};
\node (c) [right of=a, xshift=3cm] {$\leq_t$};
\draw[->] (a.center) -- (b);
\draw[->] (a.center) -- (c);
\tikzstyle{dot}= [circle, fill, minimum size=4pt,inner sep=0pt, outer sep=0pt]
\node (third) [dot,above right of=a, node distance=1.2cm, xshift=1cm, label=below:{${\sf U}$}] {};
\node (second) [dot,above left of=third, label=left:{{${\sf F}$}}] {};
\node (fourth) [dot,above right of=third, label=right:{${\sf T}$}] {};
\node (first) [dot, above right of= second,label=above:{{${\sf C}$}}] {};
\path[color=black] (second) edge (first);
\path[color=black] (third) edge (second);
\path[color=black] (fourth) edge (third);
\path[color=black] (first) edge (fourth);
\end{tikzpicture}}
\end{center}
\caption{A four-valued bilattice}
\label{fig:four}
\end{figure}
Each element of ${\cal FOUR}$ is associated with the propositional constant of ${\cal L}$ with the same notation. These elements are arranged in two lattice orders,
$\leq_t$ and $\leq_i$, intuitively representing differences in the amount of {\em truth\/} and {\em information\/} (respectively) that each element exhibits.
According to this interpretation, ${\sf T}$ (respectively, ${\sf F}$) exhibits maximal (respectively, minimal) truth, while ${\sf C}$ (respectively, ${\sf U}$) represents
`too much' (respectively, lack of) information. In what follows, we denote by $-$ the $\leq_t$-involution on ${\cal FOUR}$ (that is, $-{\sf F}={\sf T}$, $-{\sf T}={\sf F}$,
$-{\sf U}={\sf U}$ and $-{\sf C}={\sf C}$).
\medskip
A {\em four-valued interpretation} of a program ${\cal P}$ is a pair $(x,y)$, where $x \subseteq {\cal A}_{\cal P}$ is the set of the atoms that are assigned a value in
$\{{\sf T},{\sf C}\}$ and $y \subseteq {\cal A}_{\cal P}$ is the set of atoms assigned a value in $\{{\sf T},{\sf U}\}$.\footnote{Somewhat skipping ahead, the intuition
here is that $x$ (respectively, $y$) is a lower (respectively, an upper) approximation of the true atoms.}
Interpretations are compared by two order relations, corresponding to the two partial orders of ${\cal FOUR}$:
\begin{enumerate}
\item the \emph{information order\/} $\leq_i$, where $(x,y)\leq_i (w,z)$ iff $x\subseteq w$ and $z\subseteq y$, and
\item the \emph{truth order\/} $\leq_t$, where $(x,y)\leq_t (w,z)$ iff $x\subseteq w$ and $y\subseteq z$.
\end{enumerate}
The information order represents differences in the ``precisions'' of the interpretations. Thus, the components of higher values according to this order represent
tighter evaluations. The truth order represents increased `positive' evaluations. Truth assignments to complex formulas are then recursively defined as follows:
\begin{itemize}
\item $(x,y)(\jss{p})=
\begin{cases}
{\sf T} & \text{ if } \jss{p} \in x \text{ and } \jss{p} \in y, \\
{\sf U} & \text{ if } \jss{p} \not\in x \text{ and }\jss{p} \in y, \\
{\sf F} & \text{ if } \jss{p} \not\in x \text{ and } \jss{p} \not\in y, \\
{\sf C} & \text{ if } \jss{p} \in x \text{ and } \jss{p} \not\in y.
\end{cases}$ \smallskip
\item $(x,y)(\lnot \phi)=- (x,y)(\phi)$,
\item $(x,y)(\psi \land \phi)=lub_{\leq_t}\{(x,y)(\phi),(x,y)(\psi)\}$,
\item $(x,y)(\psi \lor \phi)= glb_{\leq_t}\{(x,y)(\phi),(x,y)(\psi)\}$.
\end{itemize}
A four-valued interpretation of the form $(x,x)$ may be associated with a {\em two-valued\/} (or {\em total\/}) interpretation $x$,
in which for an atom $p$, $x(p) = {\sf T}$ if $p \in x$ and $x(p) = {\sf F}$ otherwise. We say that $(x,y)$ is a {\em three-valued\/}
(or {\em consistent\/}) interpretation, if $x \subseteq y$. Note that in consistent interpretations there are no ${\sf C}$-assignments.
\medskip
We now consider semantics for dlp's. First, given a two-valued interpretation, an extension to dlp's of the immediate consequence operator for normal
programs \cite{EmdenK76} is defined as follows:
\begin{definition}%
\label{def:operator:disj:lp}
Given a dlp ${\cal P}$ and a two-valued interpretation $x$, we define:
\begin{itemize}
\item $\mathit{HD}_{\cal P}(x)=\{\Delta\mid \bigvee\!\Delta\leftarrow \psi \in{\cal P} \text{ and } (x,x)(\psi) = {\sf T}\}$.
\item $\mathit{IC}_{\cal P}(x)=\{y\subseteq \:\bigcup\!\mathit{HD}_{\cal P}(x) \mid \forall \Delta \in \mathit{HD}_{\cal P}(x), \ y \cap \Delta \neq \emptyset \}$.
\end{itemize}
\end{definition}
Thus, $\mathit{IC}_{\cal P}(x)$ consists of sets of atoms, each sets contains at least one representative from every disjuncts of a rule in ${\cal P}$ whose body is $x$-satisfied
(i.e, a representative from each set $\Delta \in\mathit{HD}_{\cal P}(x)$). In other words, $\mathit{IC}_{\cal P}(x)$ consists of the two-valued interpretations that validate all disjunctions
which are derivable from ${\cal P}$ given $x$. Denoting by $\wp({\cal S})$ the powerset of ${\cal S}$, $\mathit{IC}_{\cal P}$ is an operator on the lattice
$\tup{\wp({\cal A}_{\cal P}),\subseteq}$.\footnote{The operator $\mathit{IC}_{\cal P}$ is a generalization of the immediate consequence operator from \cite[Definition 3.3]{fernandez1995bottom},
where the minimal sets of atoms in $IC_{\cal P}(x)$ are considered. We will see below that this requirement of minimality is neither necessary nor desirable in the consequence operator.}
\begin{example}
\label{examp:IC-deterministic-case}
Consider the dlp ${\cal P}=\{p\lor q\leftarrow \}$. For any two-valued interpretation $x$,
$\mathit{HD}_{\cal P}(x)=\{\{p,q\}\}$, since $p\lor q\leftarrow \in {\cal P}$ and the body of this rule is an empty conjunction and therefore true under any interpretation.
Thus, $\mathit{IC}_{\cal P}(x)=\{\{p\},\{q\},\{p,q\}\}$ for any two-valued interpretation $x$. This intuitively reflects the fact that
either $p$ or $q$ has to be true to validate the head of $p\lor q\leftarrow$.
\end{example}
\smallskip
Other semantics for dlp's, this time based on three-valued interpretations, are defined next:
\begin{definition}
\label{def:3-val-sem-dlp}
Given a dlp ${\cal P}$ and a consistent interpretation $(x,y)$. We say that $(x,y)$ is:
\begin{itemize}
\item a \emph{(three--valued) model\/} of ${\cal P}$, if for every $\phi\leftarrow \psi \in {\cal P}$, $(x,y)(\phi)\geq_t (x,y)(\psi)$.
We denote by $mod({\cal P})$ the set of the three-valued models of ${\cal P}$.
\item a \emph{weakly supported model\/} of ${\cal P}$, if it is a model of ${\cal P}$ and for every $p \in y$,
there is a rule $\bigvee\!\Delta\leftarrow \phi\in {\cal P}$ such that $p\in\Delta$ and $(x,y)(\phi)\geq_t (x,y)(p)$.
\item a \emph{supported model\/} of ${\cal P}$, if it is a model of ${\cal P}$ and for every $p\in{\cal A}_{\cal P}$ such that $(x,y)(p)={\sf T} \ [(x,y)(p)={\sf U}]$, there is
$\bigvee\!\Delta\leftarrow \phi\in {\cal P}$ such that $p \in\Delta$ and $(x,y)(\phi)={\sf T} \ [(x,y)(p)={\sf U}]$ and $\Delta\cap x = \{p\} \ [\Delta\cap y=\{p\}]$.
\end{itemize}
\end{definition}
The intuition behind the notions above is the following. An interpretation is a model of ${\cal P}$, if for each rule in ${\cal P}$ there is at least one atom whose truth value is
$\leq_t$-greater or equal to the truth value of the rule's body. Thus, the truth values of the rules' heads in the models of ${\cal P}$ are $\leq_t$-greater or equal to the
truth values of the rules' bodies. Weakly supported models require that for every atom that is true (respectively undecided), we can find a rule in whose head this atom
occurs and for which the body is true (respectively undecided). In other words, every atom is supported by an ``activated'' rule. Supported models strengthen this requirement
by requiring that for every atom that is true (respectively undecided), there is an ``activated'' rule in whose head the atom under consideration is the \emph{only\/} true
(respectively undecided) atom.
The semantical notions of Definition~\ref{def:3-val-sem-dlp} are illustrated in Example~\ref{ex:semantic:notions} and Example~\ref{ex:semantic:notions-2} below.
\begin{remark}
Two-valued supported and weakly supported models are defined in~\cite{brass1995characterizations}. Their generalization to the 3-valued case is, to the best of our knowledge, novel.
An alternative but equivalent definition of a supported model $(x,y)$ is the following: $(x,y)$ is a model, and for every $p\in {\cal A}_{\cal P}$ such that $(x,y)(p)\neq {\sf F}$, there
is a rule $\bigvee\Delta\leftarrow \phi$ such that for every other $p'\in\Delta$, $(x,y)(\phi)\geq_t (x,y)(p) >_t (x,y)(p')$.
\end{remark}
Another common way of providing semantics to dlp's is by Gelfond-Lifschitz reduct~\cite{gelfond1991classical}:
\begin{definition}
\label{def:GL-reduct}
The GL-transformation $\frac{\cal P}{(x,y)}$ of a disjunctively normal dlp ${\cal P}$ with respect to a consistent interpretation $(x,y)$, is the positive
program obtained by replacing in every rule in ${\cal P}$ of the form
$$p_1\lor\ldots\lor p_n \leftarrow \bigwedge_{i=1}^m q_i\land \bigwedge_{j=1}^n \lnot r_j$$
any negated literal $\lnot r_i$ ($1\leq i\leq k$) by:
(1)~${\sf F}$ if $(x,y)(r_i)={\sf T}$, (2)~${\sf T}$ if $(x,y)(r_i)={\sf F}$, and (3)~${\sf U}$ if $(x,y)(r_i)={\sf U}$.
In other words, replacing $\lnot r_i$ by $(x,y)(\lnot r_i)$.
An interpretation $(x,y)$ is a {\em three-valued stable model\/} of ${\cal P}$ iff it is a $\leq_t$-minimal model of $\frac{{\cal P}}{(x,y)}$.\footnote
{\label{footnote:2-val mod} If $x=y$, $(x,y)$ is called a {\em two-valued\/} stable model of ${\cal P}$. For normal logic programs, the \emph{well-founded model\/}
is the $\leq_i$-minimal three-valued stable model, which is guaranteed to exist and be unique~\cite{przymusinski1990well,van1991well}.}
\end{definition}
\begin{example}
\label{ex:semantic:notions}
Consider the dlp ${\cal P} \ = \ \{p\leftarrow \lnot p; \quad q\leftarrow \lnot r;\quad r\leftarrow \lnot q;\quad q\lor r\leftarrow\}$.
\begin{itemize}
\item The following interpretations are the (consistent) models of ${\cal P}$:
\[
\begin{matrix}
(\{p,q,r\},\{p,q,r\}),&
(\{p,r\},\{p,r\}),&
(\{q,r\},\{q,r\}),&
(\{r\},\{p,r\}),&
(\{q\},\{p,q\}),
\smallskip \\
(\{r\},\{p,q,r\}),&
(\{q\},\{p,q,r\}),&
(\{p,r\},\{p,q,r\}),&
(\{p,q\},\{p,q,r\}).
\end{matrix}
\]
Notice that $(\emptyset,\{p,q,r\})$ is \emph{not} a model of ${\cal P}$, since $(\emptyset,\{p,q,r\})(q\lor r)={\sf U} <_t (\emptyset,\{p,q,r\})(\top)$\footnote{We use $\top$
to denote the empty body in the rule $q\lor r\leftarrow$. Notice that $(x,y)(\top)={\sf T}$ for any $x,y\subseteq {\cal A}_{\cal P}$.},
thus this interpretation is not a model of $q\lor r\leftarrow$.
\item The following interpretations are the weakly supported models of ${\cal P}$:
\[
\begin{matrix}
(\{q\},\{p,q\}), & (\{r\},\{p,r\}).
\end{matrix}
\]
\item These interpretations are also supported and stable models of ${\cal P}$. Indeed, note for instance that:
\[\frac{{\cal P}}{(\{q\},\{p,q\})} \ = \ \{p\leftarrow {\sf U}' \quad q\leftarrow {\sf T}; \quad r\leftarrow {\sf F}; \quad q\lor r\leftarrow\}.\]
The minimal (and, in this case also the unique) model of $\frac{{\cal P}}{(\{q\},\{p,q\})}$ is $(\{q\},\{p,q\})$ and thus this interpretation is stable.
\end{itemize}
\end{example}
\begin{example}
\label{ex:semantic:notions-2}
Consider the dlp ${\cal P} \ = \ \{p\lor q\leftarrow q\}.$
\begin{itemize}
\item Then the following interpretations are weakly supported models of ${\cal P}$:
\[
\begin{matrix}
(\emptyset,\emptyset),&
(\emptyset,\{q\}),&
(\{q\},\{q\}),&
(\emptyset,\{p,q\}),&
(\{q\},\{p,q\}),&
(\{p,q\},\{p,q\})
\end{matrix}\]
\item Of these interpretations, only the following are supported:
\[
\begin{matrix}
(\emptyset,\emptyset),&
(\emptyset,\{q\}),&
(\{q\},\{q\})
\end{matrix}\]
One can see that e.g.\ $(\{p,q\},\{p,q\})$ is \emph{not\/} weakly supported, as there is no rule for which $p$ is the only atom that is true and occurs in the head
(as also $q$ occurs in $p\lor q\leftarrow q$ and is true according to $(\{p,q\},\{p,q\})$).
\item The only stable model of ${\cal P}$ is $(\emptyset,\emptyset)$. This can be seen by observing that for any interpretation $(x,y)$ it holds that $\frac{\cal P}{(x,y)}={\cal P}$,
and that the minimal model of ${\cal P}$ is $(\emptyset,\emptyset)$.
\end{itemize}
\end{example}
\subsection{Approximation Fixpoint Theory}
\label{sec:AFT}
We now recall basic notions from approximation fixpoint theory (AFT), as described by Denecker, Marek and Truszczy{\'n}ski~\cite{denecker2000approximations}.
As we have already noted, AFT introduces constructive techniques for approximating the fixpoints of an operator $O$ over a lattice $L= \tup{{\cal L},\leq}$.
This is particularly useful when $O$ is non-monotonic (as is often the case in logic programming, default logic and abstract argumentation, and other disciplines
for non-monotonic reasoning in AI), in which case such operators are not guaranteed to even have a fixpoint, or a unique least fixpoint that can be constructively obtained.
AFT generalizes the principles for the construction of fixpoints to the non-monotonic setting, by working with \emph{approximations\/} of such operators on a {\em bilattice\/} \cite{AA96,Be77a,Be77b,Fi06,Fi20,Gi88}, constructed on the basis of $L$.
\begin{definition}
\label{def:bilattice}
Given a lattice $L = \tup{{\cal L},\leq}$, a {\em bilattice\/} is the structure $L^2 =\tup{{\cal L}^2,\leq_i,\leq_t}$, in which
${\cal L}^2 = {\cal L} \times {\cal L}$, and for every $x_1,y_1,x_2,y_2 \in {\cal L }$, \smallskip \\
$\bullet$ $(x_1,y_1) \leq_i (x_2,y_2)$ if $x_1 \leq x_2$ and $y_1 \geq y_2$, \smallskip \\
$\bullet$ $(x_1,y_1) \leq_t (x_2,y_2)$ if $x_1 \leq x_2$ and $y_1 \leq y_2$.\footnote{Recall that we use small letters to denote elements of lattice, capital letters to denote
sets of elements, and capital calligraphic letters to denote sets of sets of elements (Table~\ref{tab:set-notations}).}
\end{definition}
Bilattices of the form $L^2$ are used for defining operators that approximate operators on $L$.
An {\em approximating operator\/} ${\cal O}:{\cal L}^2\rightarrow {\cal L}^2$ of an operator $O:{\cal L}\rightarrow {\cal L}$ is an operator that maps every
approximation $(x,y)$ of an element $z$ to an approximation $(x',y')$ of another element $O(z)$, thus approximating the behavior of the approximated operator $O$.
Approximation operators may be viewed as combinations of two operators: $({\cal O}(.,.))_1$ and $({\cal O}(.,.))_2$ which calculate, respectively, a \emph{lower\/} and
an \emph{upper\/} bounds for the value of $O$ (where, as usual, $(x,y)_1$ respectively $(x,y)_2$ represents the first respectively second component of $(x,y)$).
To avoid clutter, we will also denote $({\cal O}(x,y))_1$ by ${\cal O}_l(x,y)$ and $({\cal O}(x,y))_2$ by ${\cal O}_u(x,y)$.
Two fundamental requirements on approximating operators are the following:
\begin{enumerate}
\item {\sl $\leq_i$-monotonicity:} the values of an approximating operator should be more precise as its arguments are more precise, and
\item {\sl exactness:} exact arguments are mapped
to exact values.
\end{enumerate}
These requirements result in the following definition:
\begin{definition}
\label{def:approx-notions}
Let $O:{\cal L}\rightarrow {\cal L}$ and ${\cal O}:{\cal L}^2\rightarrow {\cal L}^2$.
\begin{itemize}
\item ${\cal O}$ is {\em $\leq_i$-monotonic\/}, if when $(x_1,y_1)\leq_i(x_2,y_2)$, also ${\cal O}(x_1,y_1)\leq_i {\cal O}(x_2,y_2)$;
${\cal O}$ is \emph{approximating\/}, if it is $\leq_i$-monotonic and for any $x\in {\cal L}$, ${\cal O}_l(x,x) = {\cal O}_u(x,x)$.\footnote
{In some papers (e.g.,~\cite{denecker2000approximations}), an approximation operator is defined as a symmetric $\leq_i$-monotonic operator,
i.e.\ a $\leq_i$-monotonic operator s.t.\ for every $x,y\in {\cal L}$, ${\cal O}(x,y)=({\cal O}_l(x,y),{\cal O}_l(y,x))$ for some
${\cal O}_l:{\cal L}^2\rightarrow {\cal L}$. However, the weaker condition we take here (taken from \cite{denecker2002ultimate}) is actually
sufficient for most results on AFT. \label{footnote:symetry} }
\item ${\cal O}$ is an {\em approximation\/} of $O$, if it is $\leq_i$-monotonic and
${\cal O}$ \emph{extends} $O$, that is: ${\cal O}(x,x) = (O(x), O(x))$ (for every $x\in {\cal L}$).
\end{itemize}
\end{definition}
\begin{remark}
One can define an approximating operator ${\cal O}$ without having to specify which operator $O$
it approximates, and indeed it will often be convenient to study approximating operators without having to refer to the approximated operator.
However, one can easily obtain the operator $O$ that ${\cal O}$ approximates by
letting: $O(x) = {\cal O}_l(x,x)$.
\end{remark}
Another operator that has a central role in AFT and which is used for expressing the semantics of many non-monotonic formalisms is the
\emph{stable operator\/}, defined next.
\begin{definition}
\label{def:stable-op}
For a complete lattice $L = \tup{{\cal L},\leq}$, let ${\cal O}:{\cal L}^2 \rightarrow {\cal L}^2$ be an approximating operator.
We denote: ${\cal O}_{l}(\cdot,y) = \lambda x.{\cal O}_{l}(x,y)$ and ${\cal O}_{u}(x,\cdot) = \lambda y.{\cal O}_{u}(x,y)$,
i.e.: ${\cal O}_{l}(\cdot,y)(x) = {\cal O}_{l}(x,y)$ and ${\cal O}_{u}(x,\cdot)(y) = {\cal O}_{u}(x,y)$.
The \emph{stable operator for ${\cal O}$\/} is: $S({\cal O})(x,y)=(\mathit{lfp}({\cal O}_l(.,y)),\mathit{lfp}({\cal O}_u(x,.))$.
\end{definition}
Stable operators capture the idea of minimizing truth, since for any $\leq_i$-monotonic operator ${\cal O}$ on ${\cal L}^2$,
the fixpoints of the stable operator $S({\cal O})$ are $\leq_t$-minimal fixpoints of ${\cal O}$ \cite[Theorem~4]{denecker2000approximations}.
Altogether, the following semantic notions are obtained:
\begin{definition}
\label{def:AFT-operators}
Given a complete lattice $L = \tup{{\cal L},\leq}$, let ${\cal O}:{\cal L}^2 \rightarrow {\cal L}^2$ be an approximating operator. \jesse{Then:}
\begin{itemize}
\item $(x,y)$ is a \emph{Kripke-Kleene fixpoint\/} of ${\cal O}$ if $(x,y) =\lfp_{\leq_i}({\cal O}(x,y))$.
\item $(x,y)$ is a \emph{three-valued stable fixpoint\/} of ${\cal O}$ if $(x,y)= S({\cal O})(x,y) $.
\item $(x,x)$ is a \emph{two-valued stable fixpoints\/} of ${\cal O}$ if $(x,x)= S({\cal O})(x,x)$.
\item $(x,y)$ is the \emph{well-founded fixpoint\/} of ${\cal O}$ if it is the $\leq_i$-minimal (3-valued) stable fixpoint of ${\cal O}$.
\end{itemize}
\end{definition}
Denecker, Marek and Truszscy\'nski~\cite{denecker2000approximations} show that every approximation operator admits a unique $\leq_i$-minimal stable fixpoint.
Pelov, Denecker and Bruynooghe~\cite{pelov2007well} show that for normal logic programs, the fixpoints based on the four-valued immediate consequence operator
for a logic program give rise to the following correspondences: the three-valued stable models coincides with the three-valued semantics as defined by Przymusinski~\cite{przymusinski1990well},
the well-founded model coincides with the homonymous semantics~\cite{przymusinski1990well,van1991well}, and the two-valued stable models coincide with the two-valued
(or total) stable models of a logic program.
\begin{example}
For a normal logic program ${\cal P}$, an approximation of the operator $\mathit{IC}_{\cal P}$~\cite{pelov2007well} can be obtained by first constructing a lower bound operator
as follows:\footnote{Notice that the lattice under consideration is $\langle 2^{{\cal A}_{\cal P}},\subseteq\rangle$, i.e., elements of the lattice are \emph{sets\/} of atoms.\label{footnote:sets:as:elements}}
\[ {\cal IC}^l_{\cal P}(x,y)= \{p\in {\cal A}_{\cal P}\mid p\leftarrow \phi\in {\cal P}, (x,y)(\phi)\geq_t {\sf C}\} \]
and then defining:
\[ {\cal IC}_{\cal P}(x,y)= ({\cal IC}_{\cal P}^l(x,y),{\cal IC}_{\cal P}^l(y,x)) \]
Notice that the upper bound ${\cal IC}_{\cal P}^u(y,x)$ is defined as ${\cal IC}_{\cal P}^l(y,x)$, i.e.\ ${\cal IC}_{\cal P}$ is a \emph{symmetric\/} operator (see also
Footnote~\ref{footnote:symetry}). Pelov, Denecker and Bruynooghe~\cite{pelov2007well} have shown that this operator approximates $\mathit{IC}_{\cal P}$ for normal logic
programs ${\cal P}$.
We now illustrate the behaviour of this operator with the following logic program:
\[ {\cal P} \ = \ \{ p\leftarrow \lnot q; \quad q\leftarrow \lnot p; \quad r\leftarrow r\}. \]
$\mathit{IC}_{\cal P}$ is thus an operator over the lattice $\langle 2^{\{p,q,r\}},\subseteq\rangle$. Now,
\begin{itemize}
\item Concerning the approximation ${\cal IC}_{\cal P}$ of $\mathit{IC}_{\cal P}$, it holds, e.g., that:
\begin{itemize}
\item ${\cal IC}^l_{\cal P}(\emptyset,\{p,q,r\})= \emptyset \mbox{ as }(\emptyset,\{p,q,r\})(\lnot q)=(\emptyset,\{p,q,r\})(\lnot p)=(\emptyset,\{p,q,r\})(r)={\sf U}$.
\item ${\cal IC}^l_{\cal P}(\{p,q,r\},\emptyset)=\{p,q,r\} \mbox{ as }(\{p,q,r\},\emptyset)(\lnot q)=(\{p,q,r\},\emptyset)(\lnot p)=(\{p,q,r\},\emptyset)(r)={\sf C}$.
\end{itemize}
\item We now illustrate the stable operator.
\begin{itemize}
\item It holds that $\lfp({\cal IC}_{\cal P}(.,\{p\})=\{p\}$, and therefore $S({\cal IC}^l_{\cal P})(\{p\}) = \{p\}$.
\item By symmetry of ${\cal IC}_{\cal P}$, $(\{p\},\{p\})$ is a stable fixpoint of ${\cal IC}_{\cal P}$.
\item Likewise, it can be observed that $(\emptyset,\{p,q\})$ and $(\{q\},\{q\})$ are stable fixpoints of ${\cal IC}_{\cal P}$.
\item It follows that $(\emptyset,\{p,q\})$ is the well-founded fixpoint of ${\cal IC}_{\cal P}$.
\end{itemize}
\end{itemize}
We shall generalize this operator to the disjunctive case in Section~\ref{sec:nd:aft}.
\end{example}
\section{Non-Deterministic Operators and Approximations}
\label{sec:nd:aft}
In this section, we generalize approximation fixpoint theory to allow for non-deterministic operators. In Section~\ref{sec:non-deterministic:operators} we formally define
non-deterministic operators and the necessary order-theoretic background. In Section~\ref{sec:ndaos} we then define non-deterministic approximation operators and
show some basic results on these operators.
\subsection{Non-Deterministic Operators}\label{sec:non-deterministic:operators}
In order to characterize (two-valued) semantics for disjunctive logic programming, in~\cite{pelov2004semantics} Pelov and Truszczy{\'n}ski introduced
the notion of non-deterministic operators and accordingly extended AFT to non-deterministic AFT.
\begin{definition}%
\label{def:non-deterministic-operator}
A {\em non-deterministic operator on ${\cal L}$} is a function $O : {\cal L}\rightarrow \wp({\cal L}) \setminus \{\emptyset\}$.
\end{definition}
Intuitively, a non-deterministic operator assigns to every element $x$ of ${\cal L}$ a (nonempty) set of {\em choices\/} $O(x)=\{y_1,y_2,\ldots\}$ which can
be seen as equally plausible alternatives of the outcome warranted by $x$. Thus, non-deterministic operators allow for multiple options or choices in their output
(reflected by their co-domain being $\wp({\cal L})$). Just like deterministic operators, it is required that every element $x$ is mapped to at least one choice
(which might be the $\leq$-least element $\bot$, if it exists). As an example of non-determinism, consider an activated disjunctive rule $\bigvee\Delta\leftarrow \phi$
(i.e., a rule for which the body is true and its head is a disjunction), requiring that at least one among the disjuncts $\delta\in\Delta$ is true.
\begin{example}%
\label{example:operator:disj:lp}
The operator $\mathit{IC}_{\cal P}$ from Definition~\ref{def:operator:disj:lp} is a non-deterministic operator on the lattice $\tup{\wp({\cal A}_{\cal P}),\subseteq}$.
\end{example}
As the ranges of non-deterministic operators are {\em sets\/} of lattice elements, one needs a way to compare them. Next, we recall two such relations,
known as the {\em Smyth order\/}~\cite{smyth1976powerdomains} and the {\em Hoare order\/} (used in the context of DLP in several works (see,
e.g.,~\cite{alcantara2005well,fernandez1995bottom})).
\begin{definition}%
\label{def:Smith-preorder}
Let $L = \tup{{\cal L},\leq}$ be a lattice, and let $X,Y \in \wp({\cal L})$. Then:
\begin{itemize}
\item $X \preceq^S_L Y$ if for every $y\in Y$ there is an $x\in X$ such that $x\leq y$.
\item $X \preceq^H_L Y$ if for every $x\in X$ there is a $y\in Y$ such that $x\leq y$.
\end{itemize}
\end{definition}
Here, the sets of lattice elements $X$ and $Y$ represent values of a non-deterministic operator (i.e., these are non-deterministic states). Thus, according to the intuition described above,
each one is a set of {\em choices\/}. Accordingly, $\preceq^S_L$ means that for every choice $y$ in $Y$, there is a $\leq$-smaller choice $x$ in $X$. Likewise, $\preceq^H_L$ means
that for every choice $x$ in $X$, there is a $\leq$-greater choice $y$ in $Y$. In other words, $\preceq^H_L$ and $\preceq^S_L$ allow to compare non-deterministic states on the basis
of the $\leq$-relationship of their constituent elements in $L$. We will see below that $\preceq^S_L$ is well-suited to compare lower bounds, whereas $\preceq^H_L$ is well-suited
to compare upper bounds.
\begin{remark}
\label{rem:properties:of:smyth}
Both $\preceq^S_L$ and $\preceq^H_L$ are preorders (i.e., reflexive and transitive) on $\wp({\cal L})$.
\end{remark}
\subsection{Non-Deterministic Approximation Operators}
\label{sec:ndaos}
We now develop a notion of approximation of non-deterministic operators. Such an approximation generalizes the analogue approximation of deterministic operators explained in
Section~\ref{sec:AFT}. The benefits of such an approximation will be demonstrated in Sections~\ref{sec:theory:of:ndao} and~\ref{sec:stable:semantics}.
Before describing the formal details, we explain the intuition behind the approximation. Recall that, in deterministic AFT, an operator over $L$ is approximated by an
\emph{approximation operator\/} that specifies a lower bound and an upper bound of an approximated element. Thus, an approximation operator essentially consists
of two operators over $L$, the a lower bound operator ${\cal O}_l$ and the upper bound operator ${\cal O}_u$. We generalize this idea to the non-deterministic case.
As in deterministic AFT, a non-deterministic approximation operator can be seen as consisting of a non-deterministic lower bound operator and an non-deterministic upper
bound operator. A non-deterministic approximation ${\cal O}$ of a non-deterministic operator $O$, maps a pair $(x,y)$ (intuitively representing an approximation of a
single value $z$) to a pair of sets $X,Y\subseteq {\cal L}$ (intuitively representing sets of lower bounds $X$ and upper bounds $Y$ on the non-deterministic choices $O(z)$).
Thus, an approximation operator ${\cal O}$ is of the type ${\cal L}^2\rightarrow \wp({\cal L})\times\wp({\cal L})$.
As in the deterministic case, it is natural to assume two formal properties of the approximating operators (recall Definition~\ref{def:approx-notions}).
Below, we adjust the requirements in Definition~\ref{def:approx-notions} to the non-deterministic case, using the order relations in Definition~\ref{def:Smith-preorder}:
\begin{enumerate}
\item {\sl Exactness}: if $(x,y)$ is an approximation of $z$, every non-deterministic choice $z'\in O(z)$ should have at least one lower bound in
$x'\in {\cal O}_l(x,y)$ and at least one upper bound $y'\in {\cal O}_u(x,y)$. In other words, ${\cal O}_l(x,y)\preceq^S_L O(z)$
and $O(z)\preceq^H_L {\cal O}_u(x,y)$.
Informally, every choice in $O(z)$ is in between some lower bound and upper bound of ${\cal O}(x,y)$. In the extreme case where the h
argument is an exact pair $(x,x)$, this means that ${\cal O}(x,x)=O(x,x)\times O(x,x)$ and so, for an exact pair $(x,x)$, both the lower and upper bound operator
coincide with the approximated operator $O$. Thus, ${\cal O}(x,x)$ represents a single set of choices. We shall use this as a defining condition:
for exact pairs, the lower and upper bound coincide. Intuitively, exact inputs give rise to exact (but non-deterministic) outputs. We will call such an operator \emph{exact\xspace}.
\item {\sl Monotonicity}: just like in the deterministic case, a non-deterministic approximation operator should be expected to be monotonic w.r.t.\
the information ordering: more precise inputs give rise to more precise outputs. To make this notion formally precise, we need a way to compare the precision
of pairs of sets (interpreted as a set of lower bounds and a set of upper bounds). A set of lower bounds $X_1$ is more precise than a set of lower bounds
$X_2$ if, for every lower bound $x_1$ in the more precise set $X_1$, there is a less precise (i.e.\ $\leq$-smaller) lower bound $x_2$ in the less precise set $X_2$.
Thus: $X_2\preceq^S_L X_1$. Likewise, a set of upper bounds $Y_1$ is more precise than
a set of upper bounds $Y_2$ if, for every upper bound $y_1$ in the more precise set $Y_1$, there is a less precise (i.e.\ $\leq$-higher) upper bound $y_2$
in the less precise set $Y_2$. Thus: $Y_1\preceq^H_L Y_2$. Altogether, a pair of bounds $(X_1,Y_1)$ is more precise than a second pair of bounds $(X_2,Y_2)$
if the lower bounds are compared w.r.t.\ the Smyth-order $\preceq^S_L$ and the upper bounds are compared w.r.t.\ the Hoare-order $\preceq^H_L$.
This idea was defined by Alc\^antara, Dam\'asio and Moniz Pereira~\cite{alcantara2005well} on pairs of sets, and is generalized here to an algebraic setting:
\begin{definition}%
Given some $X_1,X_2,Y_1,Y_2\subseteq {\cal L}$, $X_1\times Y_1 \preceq^A_i X_2\times Y_2$ iff $X_1\preceq^S_L X_2$ and $Y_2\preceq^H_L Y_1$.
\end{definition}
\end{enumerate}
We are now ready to define a \emph{non-deterministic approximation operator\/}: it is an operator ${\cal O}:{\cal L}^2\rightarrow \wp({\cal L})\times \wp({\cal L}) $ assigning to every pair
$(x,y)$ a set of lower bounds and upper bounds, that is $\preceq^A_i$-monotonic for which exact inputs give rise to exact outputs. Formally:
\begin{definition}
\label{def:ndao}
Let $L=\tup{{\cal L},\leq}$ be a lattice. An operator ${\cal O}:{\cal L}^2\rightarrow \wp({\cal L}){\setminus\emptyset}\times \wp({\cal L}){\setminus\emptyset}$
is called a {\em non-deterministic approximating operator\/} (ndao, for short), if satisfies the following properties:
\begin{itemize}
\item ${\cal O}$ is $\preceq^A_i$-monotonic.
\item ${\cal O}$ is \emph{exact\xspace}, i.e., for every $x\in {\cal L}$, ${\cal O}(x,x)={\cal O}_l(x,x)\times {\cal O}_\jessen{l}(x,x)$.\footnote{Recall that we
denote by ${\cal O}_l$ the operator defined by ${\cal O}_l(x,y)={\cal O}(x,y)_1$, and likewise by ${\cal O}_u$ the operator defined by ${\cal O}_u(x,y)={\cal O}(x,y)_2$.}
\end{itemize}
\end{definition}
We also say that a ndao ${\cal O}$ is \emph{an approximation} of the non-deterministic operator, defined as $O(x)={\cal O}_l(x,x)$ (for every $x \in {\cal L}$)
\begin{remark}
\label{remark:deterministic}
We shall show below (Proposition~\ref{prop:deterministic:aft}) that Definition~\ref{def:ndao} extends Definition~\ref{def:approx-notions}: when an ndao is deterministic,
in the sense that ${\cal O}(x,y)$ is singleton for every $x,y\in {\cal L}$, an ndao reduces to an approximation operator.
\end{remark}
\begin{remark}
It is sometime useful to assume the following property of ndaos:
${\cal O}$ is {\em symmetric\/}, if ${\cal O}_l(x,y)={\cal O}_u(y,x)$ for any $x,y\subseteq {\cal L}$.(Or, equivalently, if ${\cal O}_u(x,y)={\cal O}_l(y,x)$ for every every
$x,y \in {\cal L}$). Notice that symmetric operators are exact\xspace.
Just like in deterministic AFT, the assumption of symmetry is \emph{not} essential and we do not assume it unless specific results require it (see also Foonote~\ref{footnote:symetry}).
\end{remark}
We now give an example of an ndao in the context of disjunctive logic programming.
The operator ${\cal IC}_{\cal P}$ is constructed on the basis of the operators $\mathcal{HD}_{\cal P}^l$ and $\mathcal{HD}_{\cal P}^u$, which intuitively constitute a lower bound and
and an upper bound on the activated heads. In more detail, $\mathcal{HD}_{\cal P}^l(x,y)$ contains all the heads of rules whose body is at least (according to $\geq_t$) contradictory, i.e.,
whose body is ${\sf T}$ or ${\sf C}$. Likewise, $\mathcal{HD}_{\cal P}^u(x,y)$ contains heads of rules whose body is at least (according to $\geq_t$)
undecided, i.e., whose body is ${\sf T}$ or ${\sf U}$. The lower (respectively upper) bounds are then constructed by taking all sets of atoms containing only atoms in at least one
of the heads in $\mathcal{HD}_{\cal P}^l(x,y)$ (respectively $\mathcal{HD}_{\cal P}^u(x,y)$), and containing at least one atom for every head in $\mathcal{HD}_{\cal P}^l(x,y)$ (respectively $\mathcal{HD}_{\cal P}^u(x,y)$).
\begin{definition}
\label{def:IC_P-ndo}
For a dlp ${\cal P}$ and an interpretation $(x,y)$, we define:
\begin{itemize}
\item $\mathcal{HD}^l_{\cal P}(x,y) = \{ \Delta \mid \bigvee\!\Delta \leftarrow \phi\in {\cal P}, (x,y)(\phi)\geq_t {\sf C}\}$,
\item $\mathcal{HD}^u_{\cal P}(x,y) = \{ \Delta \mid \bigvee\!\Delta \leftarrow \phi\in {\cal P}, (x,y)(\phi)\geq_t {\sf U}\}$,
\item ${\cal IC}^l_{\cal P}(x,y)=\{x_1\subseteq \bigcup\mathcal{HD}^l_{\cal P}(x,y) \mid \forall \Delta\in \mathcal{HD}^l_{\cal P}(x,y), \ x_1 \cap \Delta \neq \emptyset \}$,
\item ${\cal IC}^u_{\cal P}(x,y)=\{y_1\subseteq \bigcup\mathcal{HD}^u_{\cal P}(x,y) \mid \forall \Delta\in \mathcal{HD}^u_{\cal P}(x,y), \ y_1 \cap \Delta \neq \emptyset \}$,
\item ${\cal IC}_{\cal P}(x,y)=({\cal IC}^l_{\cal P}(x,y), {\cal IC}^u_{\cal P}(x,y))$.
\end{itemize}
\end{definition}
\begin{example}
\label{example:operator:disj:lp-2}
The operator ${\cal IC}_{\cal P}$ is an approximation of the non-deterministic operator
$IC_{\cal P}$ in Example~\ref{example:operator:disj:lp} (and Definition~\ref{def:operator:disj:lp}). Furthermore, as we show next, it is a symmetric operator.
\end{example}
\begin{proposition}
${\cal IC}_{\cal P}$ is a symmetric ndao that approximates $IC_{\cal P}$.
\end{proposition}
\begin{proof}
It is clear that for any $x\in {\cal L}$, $\mathcal{HD}_{\cal P}^l(x,x)=\mathcal{HD}_{\cal P}^{u}(x,x)=\mathit{HD}_{\cal P}(x,x)$ (as for any $\phi$, $(x,x)(\phi)\in \{{\sf T},{\sf F}\}$).
Thus, ${\cal IC}_{\cal P}$ approximates $IC_{\cal P}$ and is exact\xspace. We now show that it is $\preceq^A_i$-monotonic. For this, consider some
$(x_1,y_1)\leq_i (x_2,y_2)$. We show by induction on $\phi$ that if $(x_1,y_1)(\phi)\geq_t {\sf C}$ then $(x_2,y_2)(\phi)\geq_t {\sf C}$.
The base case is clear as $\phi\in x_1$ and $x_1\subseteq x_2$ implies $\phi\in x_2$. For the inductive case, notice that the cases for $\phi=\phi_1\land \phi_2$
and $\phi=\phi_1\lor \phi_2$ follow immediately from the inductive hypothesis.
Suppose now thar $\phi=\lnot \phi_1$. $(x_1,y_1)(\lnot \phi_1)\geq_t{\sf C}$ means that $\phi_1\not\in y_1$. Since $y_2\subseteq y_1$, also $\phi_1\not\in y_2$.
We now show $\preceq^A_i$-monotonicity, which follows immediately from $\mathcal{HD}_{\cal P}^l(x_1,y_1)\subseteq \mathcal{HD}_{\cal P}^l(x_2,y_2)$. To see the latter, suppose that
$\Delta\in \mathcal{HD}_{\cal P}^l(x_1,y_1)$, i.e.\ for some $\bigvee\Delta\leftarrow \phi$, $(x_1,y_1)(\phi)\geq_t {\sf C}$. Then $(x_2,y_2)(\phi)\geq_t{\sf C}$ and thus
$\Delta\in \mathcal{HD}_{\cal P}^l(x_2,y_2)$.
We finally show that ${\cal IC}_{\cal P}$ is symmetric. For this, we show the following lemma:
\begin{lemma}
\label{lemma:symmetry:of:ic}
For any $x,y\subseteq {\cal A}_{\cal P}$:
\begin{enumerate}
\item $(x,y)(\phi)= {\sf T}$ iff $(y,x)(\phi)= {\sf T}$,
\item $(x,y)(\phi)= {\sf F}$ iff $(y,x)(\phi)= {\sf F}$,
\item $(x,y)(\phi)= {\sf C}$ iff $(y,x)(\phi)= {\sf U}$.
\end{enumerate}
\end{lemma}
\begin{proof}
We show the third item, the first two items are shown similarly. We show this by induction on the structure of $\phi$. For the base case,
let $\phi \in {\cal A}_{\cal P}$. Then $(x,y)(\phi)={\sf C}$ iff $\phi\in x\setminus y$, and, since $(y,x)(\phi)= {\sf U}$ iff $\phi\in x\setminus y$, the base case is proven.
For the inductive case, notice that the cases where $\phi=\phi_1\lor \phi_2$ or $\phi=\phi_1\land \phi_2$ follow immediately from the inductive hypothesis.
Suppose that $\phi=\lnot \phi_1$. Since $(x,y)(\lnot\phi_1)={\sf C}$ iff $(x,y)(\phi_1)={\sf C}$, and $(y,x)(\lnot \phi_1)={\sf U}$ iff $(y,x)(\phi_1)={\sf U}$, we obtain
by the induction hypothesis that $(x,y)(\lnot\phi_1)={\sf C}$ iff $(y,x)(\lnot\phi_1)={\sf U}$.
\end{proof}
From Lemma~\ref{lemma:symmetry:of:ic} it follows that $\mathcal{HD}_{\cal P}^l(x,y)=\mathcal{HD}_{\cal P}^u(y,x)$ and thus ${\cal IC}_{\cal P}^l(x,y)={\cal IC}_{\cal P}^u(y,x)$.
\end{proof}
%
We now illustrate the operator ${\cal IC}_{\cal P}$ using two simple disjunctive logic program:
\begin{example}
\label{example:operator:disj:lp-2-b}
Consider the following dlp: ${\cal P}=\{ p\lor q\leftarrow\lnot q\}$.
\begin{description}
\item [] The corresponding operator ${\cal IC}^l_{\cal P}$ behaves as follows:
\begin{itemize}
\item For any interpretation $(x,y)$ for which $q\in x$, $\mathcal{HD}^l_{\cal P}(x,y)=\emptyset$ and thus ${\cal IC}^l_{\cal P}(x,y)=\{\emptyset\}$.
\item For any interpretation $(x,y)$ for which $q\not\in x$, $\mathit{HD}^l_{\cal P}(x,y)=\{\{p,q\}\}$ and thus ${\cal IC}^l_{\cal P}(x,y)=\{\{p\},\{q\},\{p,q\}\}$.
\end{itemize}
\item [] Since ${\cal IC}_{\cal P}^l(x,y)={\cal IC}_{\cal P}^u(y,x)$ (by Lemma~\ref{lemma:symmetry:of:ic}), this means that ${\cal IC}_{\cal P}$ behaves as follows:
\begin{itemize}
\item For any $(x,y)$ with $q\not\in x$ and $q\not\in y$, ${\cal IC}_{\cal P}(x,y)=\{\{p\},\{q\},\{p,q\}\}\times \{\{p\},\{q\},\{p,q\}\}$,
\item For any $(x,y)$ with $q\not\in x$ and $q\in y$, ${\cal IC}_{\cal P}(x,y)=\{\emptyset\}\times \{\{\{p\},\{q\},\{p,q\}\}$,
\item For any $(x,y)$ with $q\in x$ and $q\not\in y$, ${\cal IC}_{\cal P}(x,y)=\{\{p\},\{q\},\{p,q\}\}\times \{\emptyset\}$, and
\item For any $(x,y)$ with $q\not\in x$ and $q\in y$, ${\cal IC}_{\cal P}(x,y)=\{(\emptyset,\emptyset)\}$.
\end{itemize}
\end{description}
\end{example}
\begin{example} %
Consider the dlp from Example~\ref{ex:semantic:notions}. Then ${\cal IC}^l_{\cal P}$ behaves as follows (for arbitrary $y\subseteq {\cal A}_{\cal P}$):
\def\arraystretch{1,3}\tabcolsep=10pt
\begin{center}
\begin{tabular}{ll}
$x$& ${\cal IC}^l_{\cal P}(x,y)$ \\ \hline
$\emptyset$ & $\{\{p,q,r\}\}$
\\ $\{p\}$& $\{\{q,r\}\}$
\\ $\{q\}$& $\{\{p,q\},\{p,q,r\}\}$
\\ $\{r\}$& $\{\{p,r\},\{p,q,r\}\}$
\\ $\{p,q\}$& $\{\{q\},\{q,r\}\}$
\\ $\{p,r\}$& $\{\{r\},\{q,r\}\}$
\\ $\{q,r\}$& $\{\{p,q\},\{p,r\},\{p,q,r\}\}$
\\ $\{p,q,r\}$& $\{\{q\},\{r\},\{q,r\}\}$
\end{tabular}
\end{center}
Again, by the symmetry of ${\cal IC}_{\cal P}$, the behaviour of ${\cal IC}_{\cal P}$ can be easily derived on the basis of ${\cal IC}^l_{\cal P}$.
\end{example}
\begin{remark}
\label{remark:minimality:in:the:op}
In the literature (e.g., \cite{antic2013hex,pelov2004semantics}), similar non-deterministic four-valued operators have been defined to characterize
the semantics of disjunctive logic programs, inspired by deterministic approximation fixpoint theory. In some of these operators minimality of the
image of the operator was built-in. In our setting, this is defined as follows:
\begin{itemize}
\item ${\cal IC}^{m,l}_{\cal P}(x,y)=\min_\subseteq(\{v \mid \forall \Delta\in \mathcal{HD}^l_{\cal P}(x,y), \ v \cap \Delta \neq \emptyset \})$,\footnote{Recall that
$\min_\subseteq(X)=\{x\in X\mid \not\exists y\in X: y\subset x\}$.}
%
\item ${\cal IC}_{\cal P}^{m}(x,y)=({\cal IC}^{m,l}_{\cal P}(x,y), {\cal IC}^{m,l}_{\cal P}(y,x))$.
%
%
%
%
\end{itemize}
However, there are some issues with this approach, e.g., that the operator ${\cal IC}_{\cal P}$ is \emph{not} $\preceq^A_i$-monotonic. To see this, consider the
program ${\cal P}=\{a\lor b\leftarrow; \ \ a\leftarrow c\}$ and the two interpretations $(\emptyset,\{a,b,c\})$ and $(\emptyset,\{a,b\})$. Then we have:
\begin{itemize}
\item ${\cal IC}^{m,l}_{\cal P}(\emptyset,\{a,b,c\})=\{\{a\},\{b\}\}$ and ${\cal IC}^{m,l}_{\cal P}(\{a,b,c\},\emptyset)=\{\{a\}\}$
(the latter since $(\{a,b,c\},\emptyset)(c)={\sf C}$ and thus $\mathcal{HD}^l_{\cal P}(\{a,b,c\},\emptyset)=\{\{a,b\},\{a\}\}$).
\item ${\cal IC}^{m,l}_{\cal P}(\emptyset,\{a,b\})=\{\{a\},\{b\}\}$ and ${\cal IC}^{m,l}_{\cal P}(\{a,b\},\emptyset)=\{\{a\},\{b\}\}$
(the latter since $(\{a,b,c\},\emptyset)(c)={\sf F}$ and thus $\mathcal{HD}^l_{\cal P}(\{a,b\},\emptyset)=\{\{a,b\}\}$).
\end{itemize}
It follows that ${\cal IC}^{m,l}_{\cal P}(\{a,b\},\emptyset) \not\preceq^H_L {\cal IC}^{m,l}_{\cal P}(\{a,b,c\},\emptyset)$ i.e.,
$\{\{a\},\{b\}\} \not\preceq^H_L \{\{a\}\}$, since $\{b\} \not\subseteq \{a\}$. Hence,
${\cal IC}^{m,u}_{\cal P}(\emptyset,\{a,b\}) = {\cal IC}^{m,l}_{\cal P}(\{a,b\},\emptyset) \not\preceq^H_L
{\cal IC}^{m,l}_{\cal P}(\{a,b,c\},\emptyset) = {\cal IC}^{m,u}_{\cal P}(\emptyset,\{a,b,c\})$.
Thus, $(\emptyset,\{a,b,c\}) \leq_i (\emptyset,\{a,b\})$, yet ${\cal IC}^{m}_{\cal P}(\emptyset,\{a,b,c\}) \not\preceq^A_i {\cal IC}^{m}_{\cal P}(\emptyset,\{a,b\})$,
and so ${\cal IC}^{m}_{\cal P}$ is not $\preceq^A_i$-monotonic.
Note that this is a counter-example to a wrong claim made in~\cite[Example~2]{DBLP:conf/kr/HeyninckA21}, about ${\cal IC}^m_{\cal P}$ as defined above being a $\preceq^A_i$-monotonic operator.
In the work of Pelov and Truszczy{\'n}ski~\cite{pelov2004semantics}, and of Anti\'c, Eiter and Fink \cite{antic2013hex}, $\preceq^A_i$-monotonicity is not studied,
and only $\preceq^S_L$-monotonicity of the lower bound operator is shown and used (i.e., if $(x_1,y_1)\leq_i (x_2,y_2)$ then
${\cal IC}^{m,l}(x_1,y_1)\preceq^S_L {\cal IC}^{m,l}(x_2,y_2)$). Thus, the above counter-example does not invalidate this claim (i.e., this counter-example does not
show that ${\cal IC}^{m,l}$ is not $\preceq^S_L$-monotonic) .For two-valued stable semantics, this suffices, but as we shall see in what follows, when moving to three-
and four-valued semantics, full $\preceq^A_i$-monotonicity is needed.
Altogether, this example shows that requiring minimality in the non-deterministic approximation operator leads to undesirable behavior.
This is perhaps not surprising, as in deterministic approximation theory minimization is also not ensured by the operator itself, but by taking
the stable fixpoints of an operator. In our work, minimization is not demanded in the definitions of the operators, but rather is achieved in the
definitions of stable operators and fixpoints. And indeed, we will be able to show that this works well, as stable fixpoints will be shown to be
$\leq_t$-minimal fixpoints of an ndao (see Proposition~\ref{prop:stable:is:minimal:fp}).
\end{remark}
\begin{remark}
\label{rem:convex-set}
A pair of sets can alternatively be viewed as a {\em convex set\/}. A convex set is a set $X\subseteq {\cal L}$ that contains no ``holes'', i.e., for
any $x,y\in X$, if $x\leq z \leq y$ then also $z\in X$. We can then view a pair of sets as as a convex set by viewing the two sets as a lower and an
upper bound of a convex set. In that case, $\preceq^A_i$ reduces to comparing convex sets in terms of subset relations.
This representation will play an important role in what we call the \emph{state semantics\/} (see Section~\ref{sec:kripke:kleene:state}).
\end{remark}
\begin{remark}
A third way (in addition to those in the previous remarks) of viewing pairs of sets (which we conceived of as lower and upper bounds) is as set of pairs, i.e.,
a set of pairs of lower and upper bounds. This is, of course, done by taking all combinations of lower and upper bounds. Also in that case, the order $\preceq^A_i$
makes intuitive sense. In more detail, it boils down to comparing the resulting sets of pairs using $\leq_i$ and the Smyth-ordering.
\end{remark}
\begin{definition}
\label{def:S-i-order}
Given some ${\bf X},{\bf Y}\subseteq {\cal L}^2$, ${\bf X}\preceq^S_i{\bf Y}$ if for every $(y_1,y_2)\in{\bf Y}$, there is some $(x_1,x_2)\in{\bf X}$ s.t.\ $(x_1,x_2)\leq_i (y_1,y_2)$.
\end{definition}
Intuitively, if $(x_2,y_2)$ is more precise than $(x_1,y_1)$, then each interval in ${\cal O}(x_2,y_2)$ should be at least as precise as at least one interval in ${\cal O}(x_1,y_1)$.
In other words, on more precise inputs, the produced intervals become more precise than (some) interval produced on the less precise input.
Thus, whereas $\preceq^A_i$ allows for comparison of a set of lower bounds and a set of upper bounds, $\preceq^S_i$ allows for the comparison of two sets of pairs.
The order $\preceq^A_i$ over pairs of sets is equivalent to $\preceq^S_i$ over pairs obtained on the basis of a pair of sets:
\begin{lemma}
\label{prop:smyth:iff:alcantara}
Let some $X_1,X_2,Y_1,Y_2\subseteq {\cal L}$ be given. Then $(X_1, Y_1) \preceq^A_i (X_2, Y_2)$ iff $X_1\times Y_1 \preceq^S_i X_2\times Y_2$.
\end{lemma}
\begin{proof}
$[\Rightarrow]$: Suppose that $X_1\times Y_1 \preceq^A_i X_2\times Y_2$ and consider some $(x_2,y_2)\in X_2\times Y_2$. Since $X_1\times Y_1 \preceq^A_i X_2\times Y_2$,
there is some $x_1\in X_1$ s.t.\ $x_1\leq x_2$ and there is some $y_1\in Y_1$ s.t.\ $y_2\leq y_1$. Thus, there is
an $(x_1,y_1)\in X_1\times Y_1$ such that $(x_1,y_1)\leq_i (x_2,y_2)$, and so $X_1\times Y_1 \preceq^S_i X_2\times Y_2$.
\smallskip\noindent
$[\Leftarrow]$: Suppose that $X_1\times Y_1 \preceq^S_i X_2\times Y_2$ and consider some $y_2\in Y_2$. (The case for $x_1\in X_2$ is analogous). Then for every
$x\in X_2$, $(x,y_2)\in X_2\times Y_2$ and, since $X_1\times Y_1 \preceq^S_i X_2\times Y_2$, there is some $(x_1,y_1)\in X_1\times Y_1$ s.t.\ $(x_1,y_1)\leq_i (x,y_2)$,
which implies that $y_2\leq y_1$. Thus, there is some $y_1\in Y_1$ s.t.\ $y_2\leq y_1$, and so $Y_2\preceq^H_L Y_1$. The proof that $X_1\preceq^S_L X_2$ is
similar, and so $X_1\times Y_1 \preceq^A_i X_2\times Y_2$.
\end{proof}
By Lemma~\ref{prop:smyth:iff:alcantara} it immediately follows that an operator ${\cal L}^2\rightarrow \wp({\cal L})\times \wp({\cal L})$ is
$\preceq^A_i$-monotonic if and only if the corresponding operator ${\cal L}^2\rightarrow \wp({\cal L}^2)$ (obtained by taking the Cartesian product of the lower and
upper bound) is $\preceq^S_i$-monotonic.
Next, we show that when an ndao is deterministic, in the sense that ${\cal O}(x,y)$ is a singleton for every $x,y\in {\cal L}$, an ndao reduces to an approximation operator. In other words, our notion of an ndao is a faithful generalization of a deterministic approximation operator.
\begin{proposition}
\label{prop:deterministic:aft}
Let an ndao ${\cal O}:{\cal L}^2\rightarrow \wp({\cal L})\times \wp({\cal L})$ be given s.t.\ ${\cal O}(x,y)$ is a pair of singleton sets for every $x,y\in{\cal L}$. Then ${\cal O}^{\sf AFT}$
defined by ${\cal O}^{\sf AFT}(x,y)=(w,z)$ where ${\cal O}(x,y)=(\{w\},\{z\})$, is an approximation operator.
\end{proposition}
\begin{proof}
We have to show that ${\cal O}$ satisfies $\leq_i$-monotonicity and for every $x\in{\cal L}$, ${\cal O}^{\sf AFT}_l(x,x)={\cal O}^{\sf AFT}_u(x,x)$ (according to Definition \ref{def:approx-notions}).
We first show $\leq_i$-monotonicity. Suppose $(x_1,y_1)\leq_i (x_2,y_2)$. Then by $\preceq^A_i$-monotonicity of ${\cal O}$ and Lemma~\ref{prop:smyth:iff:alcantara}, ${\cal O}(x_1,y_1)\preceq^S_i {\cal O}(x_2,y_2)$. Thus, for every $(w_2,z_2)\in{\cal O}(x_2,y_2)$, there is some $(w_1,z_1)\in{\cal O}(x_1,y_1)$ such that $(w_1,z_1)\leq_i (w_2,z_2)$. Since both ${\cal O}(x_1,y_1)$ and ${\cal O}(x_2,y_2)$ are pairs of singleton sets, we obtain ${\cal O}(x_1,y_1)\leq_i {\cal O}(x_2,y_2)$.
For the second condition, notice that ${\cal O}_u(x,x)={\cal O}_l(x,x)$ in view of ${\cal O}$ being exact\xspace. This implies that ${\cal O}^{\sf AFT}(x,x)=({\cal O}^{\sf AFT}_u(x,x),{\cal O}^{\sf AFT}_l(x,x))$.
\end{proof}
The following lemma shows that an ndao is composed of a $\preceq^S_L$-monotonic lower-bound operator and a $\preceq^S_L$-anti-monotonic upper-bound operator:
\begin{lemma}
\label{lemma:mon:op:comp:of:mon:and:antimon}
An operator ${\cal O}:{\cal L}^2\rightarrow \wp({\cal L})\times \wp({\cal L})$
is $\preceq^A_i$-monotonic iff for every $x,y \in {\cal L}$, ${\cal O}_l(\cdot,y)$ is $\preceq^S_L$-monotonic, ${\cal O}_l(x,\cdot)$ is $\preceq^S_L$-anti monotonic, ${\cal O}_u(x,\cdot)$ is $\preceq^H_L$ monotonic and ${\cal O}_u(\cdot,y)$ is $\preceq^H_L$-anti monotonic.
\end{lemma}
\begin{proof}
$[\Rightarrow]$: We first show the $\preceq^S_L$-anti monotonicity of ${\cal O}_l(x,\cdot)$.
Consider some $y',y\in {\cal L}$ s.t.\ $y'\leq y$. Then $(x,y)\leq_i (x,y')$ and thus ${\cal O}(x,y)\preceq^A_i {\cal O}(x,y')$, which in particular means that ${\cal O}_l(x,y)\preceq^S_L {\cal O}_l(x,y')$.
We now show the case for ${\cal O}_u(x,.)$. Consider some $x,y',y\in {\cal L}$ s.t.\ $y'\leq y$. Then $(x,y)\leq_i (x,y')$ and thus ${\cal O}(x,y)\preceq^A_i {\cal O}(x,y')$. This means that ${\cal O}_u(x,y)\preceq^H_L {\cal O}_u(x,y')$.
$\preceq^S_L$ monotonicity of ${\cal O}_l(\cdot,y)$ and $\preceq^H_L$-monotonicity of ${\cal O}_u(\cdot,y)$ are shown similarly.
\smallskip\noindent$[\Leftarrow]$: Suppose that for every $x,y \in {\cal L}$, (1)~${\cal O}_l(\cdot,y)$ is $\preceq^S_L$-monotonic,
(2)~${\cal O}_l(x,\cdot)$ is $\preceq^S_L$-anti monotonic, (3)~${\cal O}_u(x,\cdot)$ is $\preceq^H_L$ monotonic, and
(4)~${\cal O}_u(\cdot,y)$ is $\preceq^H_L$-anti monotonic. Consider now some $x_1,x_2,y_1,y_2\in {\cal L}$ s.t.\ $x_1\leq x_2$ and $y_2\leq y_1$, i.e.\ $(x_1,y_1)\leq_i (x_2,y_2)$. With (1), ${\cal O}_l(x_1,y_2)\preceq^S_L {\cal O}_l(x_2,y_2)$. With (2), ${\cal O}_l(x_1,y_1)\preceq^S_L {\cal O}_l(x_1,y_2)$. With transitivity, ${\cal O}_l(x_1,y_1)\preceq^S_L {\cal O}_l(x_2,y_2)$. The case for the upper bound (namely, ${\cal O}_u(x_2,y_2)\preceq^H_L {\cal O}_u(x_1,y_1)$) is similar.
\end{proof}
\begin{remark}
\label{rem:mon-in-sym-operators}
By Lemma \ref{lemma:mon:op:comp:of:mon:and:antimon}, we see that that for a symmetric operator ${\cal O}$, ${\cal O}_l(\cdot,z)$ is both $\preceq^S_L$-monotonic and $\preceq^H_L$-monotonic, and ${\cal O}_l(z,\cdot)$ is both $\preceq^S_L$-anti monotonic and $\preceq^H_L$-anti monotonic. This follows immediately from the fact that since ${\cal O}$ is symmetric, ${\cal O}_l(x,y)={\cal O}_u(y,x)$ for any $x,y\in {\cal L}$.
\end{remark}
The last remark means that for symmetric operators, the $\preceq^A_i$-monotonicity reduces to a far simpler order, obtained by comparing both the lower and upper bounds as follows:
one set $X$ is smaller than another set $Y$, if for every $x\in X$ there is a $\leq$-larger element in $Y$, and for every
$y\in Y$ there is a $\leq$-smaller element in $X$.
It seems that the larger part of useful non-deterministic approximation operators are symmetric. However, there are also useful non-symmetric ndaos.
In the remainder of this section, we provide an example of a non-symmetric ndao that approximates $\mathit{IC}_{\cal P}$. This operator is inspired by the ultimate
semantics for normal (non-disjunctive) logic programs introduced by Denecker, Marek and Truszczy\'nski~\cite{denecker2002ultimate}. First, we recall the
ultimate semantics for normal (non-disjunctive) logic programs:
\begin{definition}%
\label{def:ultimate:operator:DMT}
Given a normal logic program ${\cal P}$, we define:\:\footnote{We use the abbreviation {\sf DMT} for Denecker, Marek and Truszczy{\'n}ski to denote this operator,
as to not overburden the use of ${\cal IC}^{\cal U}_{\cal P}$. Indeed, we will later see that the ultimate operator for non-disjunctive logic programs generalizes to an
ndao that is different from the ultimate operator ${\cal IC}^{\cal U}_{\cal P}$.}
\[{\cal IC}_{\cal P}^{{\sf DMT},l}(x,y)=\bigcap_{x\subseteq z\subseteq y} \{\alpha\mid \alpha\leftarrow \phi\in {\cal P} \mbox{ and }z(\phi)={\sf T} \},\]
\[{\cal IC}_{\cal P}^{{\sf DMT},u}(x,y)=\bigcup_{x\subseteq z\subseteq y} \{\alpha\mid \alpha\leftarrow \phi\in {\cal P} \mbox{ and }z(\phi)={\sf T}\}.\]
The {\em ultimate approximation operator\/} is then defined in~\cite{denecker2002ultimate} by:
\[{\cal IC}_{\cal P}^{{\sf DMT}}(x,y)=({\cal IC}_{\cal P}^{{\sf DMT},l}(x,y),\:{\cal IC}_{\cal P}^{{\sf DMT},u}(x,y)).\]
\end{definition}
To generalize this operator to an ndao, we proceed as follows: we start by generalizing the idea behind ${\cal IC}_{\cal P}^{{\sf DMT},l}$ to an operator gathering the heads
of rules that are true in every interpretation $z$ in the interval $[x,y]$:
\[{\cal HD}^{{\sf DMT},l}_{\cal P}(x,y)=\bigcap_{x\subseteq z\subseteq y} \mathit{HD}_{\cal P}(z).\]
The immediate consequence operator is then defined as usual, that is: by taking all interpretations that only contain atoms in ${\cal HD}^{{\sf DMT},l}_{\cal P}(x,y)$ and contain at least one member of every head $\Delta\in {\cal HD}^{{\sf DMT},l}_{\cal P}(x,y)$:
\[{\cal IC}_{\cal P}^{{\sf DMT},l}(x,y)=\{z\subseteq \bigcup{\cal HD}^{{\sf DMT},l}_{\cal P}(x,y) \mid \forall \Delta\in{\cal HD}^{{\sf DMT},l}_{\cal P}(x,y)\neq\emptyset: z\cap \Delta\neq \emptyset\}.\]
Notice that for a non-disjunctive program ${\cal P}$, $ {\cal HD}^{{\sf DMT},l}_{\cal P}(x,y)={\cal IC}_{\cal P}^{{\sf DMT},l}(x,y)={\cal IC}_{\cal P}^{{\sf DMT},l}(x,y)$.
The upper bound operator is constructed entirely analogously, but now the heads of rules with bodies that are true in at least one interpretation in $[x,y]$ are gathered:
\[{\cal HD}^{{\sf DMT},u}_{\cal P}(x,y)=\bigcup_{x\subseteq z\subseteq y} \mathit{HD}_{\cal P}(z)\}\]
${\cal IC}_{\cal P}^{{\sf DMT},u}$ is defined in an identical way to ${\cal IC}_{\cal P}^{{\sf DMT},l}$, by just replacing
${\cal HD}^{{\sf DMT},l}_{\cal P}(x,y)$ by ${\cal HD}^{{\sf DMT},u}_{\cal P}(x,y)$. Finally, the ${\sf DMT}$-ndao is defined as:
\[{\cal IC}_{\cal P}^{{\sf DMT}}(x,y)={\cal IC}_{\cal P}^{{\sf DMT},l}(x,y)\times {\cal IC}_{\cal P}^{{\sf DMT},u}(x,y).\]
We observe that ${\cal IC}_{\cal P}^{{\sf DMT}}$ is an ndao that approximates $IC_{\cal P}$:
\begin{proposition}
For any disjunctive logic program ${\cal P}$, ${\cal IC}_{\cal P}^{{\sf DMT}}$ is an ndao that approximates $IC_{\cal P}$.
\end{proposition}
\begin{proof}
It is clear that ${\cal IC}_{\cal P}^{{\sf DMT}}$ approximates $IC_{\cal P}$, as ${\cal HD}^{{\sf DMT},l}_{\cal P}(x,x)={\cal HD}^{{\sf DMT},u}_{\cal P}(x,x)=IC^{\sf DMT}_{\cal P}(x,x)$
for any $x\subseteq {\cal A}_{\cal P}$. We now show it is $\preceq^A_i$-monotonic. Consider some $x_1\subseteq x_2\subseteq y_2\subseteq y_1$.
We show that ${\cal HD}_{\cal P}^{{\sf DMT},l}(x_1,y_1)\subseteq {\cal HD}_{\cal P}^{{\sf DMT},l}(x_2,y_2)$ and
${\cal HD}_{\cal P}^{{\sf DMT},u}(x_2,y_2)\subseteq {\cal HD}_{\cal P}^{{\sf DMT},u}(x_1,y_1)$, which immediately implies that
${\cal HD}^{{\sf DMT},l}_{\cal P}(x_1,y_1)\preceq^S_L {\cal HD}^{{\sf DMT},l}_{\cal P}(x_2,y_2)$ and
${\cal HD}^{{\sf DMT},u}_{\cal P}(x_2,y_2)\preceq^H_L {\cal HD}^{{\sf DMT},u}_{\cal P}(x_1,y_1)$.
To see that ${\cal HD}_{\cal P}^{{\sf DMT},l}(x_1,y_1)\subseteq {\cal HD}_{\cal P}^{{\sf DMT},l}(x_2,y_2)$, consider some $\Delta\in {\cal HD}_{\cal P}^{{\sf DMT},l}(x_1,y_1)$.
Then for every $z\in [x_1,y_2]$, there is some $\bigvee\Delta\leftarrow \phi$ s.t.\ $z(\phi)={\sf T}$. Since $[x_2,y_2]\subseteq [x_1,y_1]$, also
$\Delta\in {\cal HD}_{\cal P}^{{\sf DMT},l}(x_2,y_2)$. The other claim is analogous.
\end{proof}
Notice that the operators ${\cal HD}^{{\sf DMT},l}_{\cal P}(x,y)$ and ${\cal HD}^{{\sf DMT},u}_{\cal P}(x,y)$ are only defined for consistent interpretations $(x,y)$,
and thus ${\cal IC}_{\cal P}^{\sf DMT}$ it is not a symmetric operator.
\begin{example}
Consider again the program ${\cal P}=\{p\lor q\leftarrow \lnot q\}$ from Example~\ref{example:operator:disj:lp-2-b}. Then:
\begin{description}
\item [] ${\cal IC}^{{\sf DMT},l}_{\cal P}$ behaves as follows:
\begin{itemize}
\item If $q\in y$ then ${\cal HD}^{{\sf DMT},l}_{\cal P}(x,y)=\emptyset$ and thus ${\cal IC}^{{\sf DMT},l}_{\cal P}(x,y)=\emptyset$.
\item If $q\not\in y$ then ${\cal HD}^{{\sf DMT},l}_{\cal P}(x,y)=\{\{p,q\}\}$ and thus ${\cal IC}^{{\sf DMT},l}_{\cal P}(x,y)=\{\{p\},\{q\},\{p,q\}\}$.
\end{itemize}
\item [] ${\cal IC}^{{\sf DMT},u}_{\cal P}$ behaves as follows:
\begin{itemize}
\item If $q\in x$ then ${\cal HD}^{{\sf DMT},u}_{\cal P}(x,y)=\emptyset$ and thus ${\cal IC}^{{\sf DMT},u}_{\cal P}(x,y)=\emptyset$.
\item If $q\not\in x$ then ${\cal HD}^{{\sf DMT},u}_{\cal P}(x,y)=\{\{p,q\}\}$ and thus ${\cal IC}^{{\sf DMT},u}_{\cal P}(x,y)=\{\{p\},\{q\},\{p,q\}\}$.
\end{itemize}
\end{description}
\end{example}
\section{Theory of Non-Deterministic AFT}
\label{sec:theory:of:ndao}
We now develop a general theory of approximation of non-deterministic operators. First, in Section~\ref{sec:ndao-consistency} we show
that the notion of consistency from deterministic AFT~\cite{denecker2000approximations}
can be generalized to the non-deterministic setting and holds for any ndao. Then, in Section~\ref{sec:kripke:kleene} we introduce fixpoint semantics for ndaos.
It is shown that in general such a semantics does not preserve the uniqueness or existence properties from the deterministic setting.
In Section~\ref{sec:kripke:kleene:state} we consider Kripke-Kleene states that do not have these shortcomings.
\subsection{Consistency of Approximations }
\label{sec:ndao-consistency}
Recall that a \emph{pair} $(x,y)$ is consistent if $x\leq y$, i.e.,\ if it approximates at least one element $z$ ($x\leq z\leq y$). Consistency of a deterministic approximating
\emph{operator\/} means that a consistent input, i.e.\ an input that approximates at least one element, gives rise to a consistent output, i.e.\ an output that approximates
at least one element. For deterministic operators, consistency of any approximating operator is guaranteed by Proposition~9 in~\cite{denecker2000approximations}.
This intuition is generalized straightforwardly to non-deterministic approximation operators by requiring that whenever the operator is applied to a consistent pair,
there is at least one lower bound which is smaller than at least one upper bound, i.e., there is at least one element approximated by the operator. Formally, this
comes down to the following definition:
\begin{definition}
Given a lattice $L=\tup{{\cal L},\leq}$ and an ndao ${\cal O}$ on ${\cal L}^2$, we say that
${\cal O}$ is \emph{consistent\/} if for every $x,y\in {\cal L}$ with $x\leq y$, there is some $(w,z)\in{\cal O}(x,y)$ with $w\leq z$.\footnote{To avoid clutter, we abuse
the notation and write $(w,z)\in {\cal O}(x,y)$ to denote that $w\in {\cal O}_l(x,y)$ and $z\in{\cal O}_u(x,y)$.}
\end{definition}
We now show the consistency of every ndao.
\begin{proposition}
\label{prop:weak:consistency}
Any ndao ${\cal O}$ is consistent.
\end{proposition}
\begin{proof}
Consider some $x,y\in {\cal L}$ s.t.\ $x\leq y$. Then clearly, $(x,y)\leq_i (x,x)$ and thus, with $\preceq^A_i$-monotonicity of ${\cal O}$ and Lemma~\ref{prop:smyth:iff:alcantara},
${\cal O}(x,y)\preceq^S_i{\cal O}(x,x)$. Since ${\cal O}(x,x)={\cal O}_l(x,x)\times{\cal O}_{u}(x,x)$ (in view of the exactness of ${\cal O}$), for any $w \in {\cal O}_l(x,x)$,
we have that $(w,w)\in {\cal O}(x,x)$. Thus, since ${\cal O}(x,y)\preceq^S_i{\cal O}(x,x)$, there is some $(z_1,z_2)\in {\cal O}(x,y)$ s.t.\ $(z_1,z_2)\leq_i (w,w)$, i.e.\ $z_1\leq w\leq z_2$.
\end{proof}
For symmetric operators, a stronger notion of consistency holds, namely for every $x\leq y$, it holds that: ${\cal O}_l(x,y)\preceq^S_L {\cal O}_u(x,y)$
and ${\cal O}_l(x,y)\preceq^H_L {\cal O}_u(x,y)$. Intuitively, this means that for \emph{every} upper bound we can find a lower bound below the upper bound
in question, and likewise, for every lower bound we can find an upper bound above the lower bound in question. Thus, in symmetric operators,
\emph{every\/} lower bound respectively upper bound approximates an element.
\begin{proposition}
Let a symmetric ndao ${\cal O}$ be given. Then for every $x\leq y$, ${\cal O}_l(x,y)\preceq^S_L {\cal O}_u(x,y)$ and ${\cal O}_l(x,y)\preceq^H_L {\cal O}_u(x,y)$.
\end{proposition}
\begin{proof}
Since $x\leq y$, it holds that $(x,y)\leq_i (x,x)$. Thus, ${\cal O}_l(x,y)\preceq^S_L {\cal O}_l(x,x)$ and (since ${\cal O}_u(x,y)={\cal O}_l(y,x)$),
${\cal O}_u(x,x)\preceq^S_L {\cal O}_u(x,y)$. Since ${\cal O}_l(x,x)={\cal O}_u(x,x)$, we obtain ${\cal O}_l(x,y)\preceq^S_L {\cal O}_u(x,y)$. The other case is similar.
\end{proof}
Notice that for non-symmetric operators, the above result might not hold, as we only know that ${\cal O}_l(x,y)\preceq^S_L {\cal O}_l(x,x)$ and
${\cal O}_u(x,x)\preceq^H_L {\cal O}_u(x,y)$. This is demonstrated by the following example:
\begin{example}
Consider an ndao ${\cal O}$ over ${\cal FOUR}$, defined as follows:
\[ \begin{tabular}{lccl}
\ & ${\cal O}_l(x,y)$ & ${\cal O}_u(x,y)$ \\ \hline
when $x=y$ & $\{{\sf T}\}$ & $\{{\sf T}\}$ \\
when $x\neq y$ & $\{{\sf F},{\sf T}\}$ & $\{{\sf T}\}$
\end{tabular} \]
It can be easily observed that ${\cal O}$ is a non-deterministic approximation operator: Exactness is clear, and, as $\{{\sf F},{\sf T}\}\preceq^S_L \{{\sf T}\}$,
$\preceq^A_i$-monotonicity is also immediate. However, for the consistent pair $({\sf U},{\sf T})$, ${\cal O}_l({\sf U},{\sf T})=\{{\sf F},{\sf T}\}\not\preceq^H_L
{\cal O}_u({\sf U},{\sf T})= \{{\sf T}\}$.
\end{example}
\subsection{Fixpoint Semantics and Kripke-Kleene Interpretations}
\label{sec:kripke:kleene}
As its name suggests, a primary goal of AFT is to provide fixpoints of operators and their approximations.
In the context of deterministic AFT, fixpoints of an approximation operator are approximations for which
applying the approximation operator to the lower and upper bound $(x,y)$ give rise to exactly the same upper and lower bound. Furthermore, Denecker, Marek and Truszscy\'nski~\cite{DMT07}
show that a unique $\leq_i$-least consistent fixpoint of an approximating operator ${\cal O}$ exists and can be constructed by iterating ${\cal O}$, starting from $(\bot,\top)$. This fixpoint
is termed the \emph{Kripke-Kleene\/} fixpoint. In this section, we look at fixpoint semantics for non-deterministic approximation operators, and show that existence and uniqueness of a
$\leq_i$-least consistent fixpoint of an ndao are not preserved in the non-deterministic setting. Nevertheless, we will show the usefulness of such fixpoints for, e.g., representing the weakly
supported semantics.
Recall that an ndao generates, on the basis of a lower bound $x$ and an upper bound $y$, a set of lower bounds $\{x_1,x_2,\ldots\}$ and a set of upper bounds $\{y_1,y_2,\ldots\}$. We can then generalize the notion of fixpoints of deterministic approximation operators by stating that $(x,y)$ is a fixpoint of the ndao ${\cal O}$ if the ``input'' lower bound $x$ and the ``input'' upper bound $y$ are among the ``output'' lower bounds respectively ``output'' upper bounds generated on the basis of $(x,y)$.
The idea underlying the Kripke-Kleene fixpoint as being minimally informative can then be directly taken over from the deterministic setting and imposed by definition.
Accordingly, we can define fixpoints, and Kripke-Kleene interpretations, of an ndao ${\cal O}$ as follows:
\begin{definition}
Given an ndao ${\cal O}$ over $L=\langle {\cal L},\leq \rangle$ and some $x,y\in{\cal L}$:
\begin{itemize}
\item $(x,y)$ is a \emph{fixpoint\/} of ${\cal O}$, if $(x,y)\in {\cal O}_l(x,y)\times {\cal O}_u(x,y)$ (or, somewhat abusing the of notation, if $(x,y)\in {\cal O}(x,y)$),
\item $(x,y)$ is a \emph{Kripke-Kleene interpretation\/} of ${\cal O}$, if it is $\leq_i$-minimal among the fixpoints of ${\cal O}$.
\end{itemize}
\end{definition}
Thus, Kripke-Kleene interpretations retain the type of Kripke-Kleene semantics in deterministic AFT, namely pairs of single elements $(x,y)$. Intuitively, these interpretations
represent approximations $(x,y)$ of elements such that, when making the `right choices' within the set ${\cal O}(x,y)$, ${\cal O}$ allows to derive exactly the same lower and upper bound.
The next example shows that uniqueness is no longer guaranteed in the non-deterministic case.
\begin{example}
\label{sec:application:to:dlp:ex}
Consider the dlp ${\cal P}=\{p\lor q\leftarrow\}$ from Example~\ref{examp:IC-deterministic-case}. There are {\em three\/} $\leq_i$-minimal consistent fixpoints
of ${\cal IC}_{\cal P}$(Definition~\ref{def:IC_P-ndo}): $(\{p\},\{p\})$, $(\{q\},\{q\})$ and $(\{p,q\},\{p,q\})$.
This is easy to verify as ${\cal IC}_{\cal P}(x,y)=\{\{p\},\{q\},\{p,q\}\}\times \{\{p\},\{q\},\{p,q\}\}$ for any $x,y\subseteq \{p,q\}$.
Also, this program has three weakly supported models: $\{p\}$, $\{q\}$ and $\{p,q\}$. We shall see in Theorem~\ref{theo:correspondence:supported} that this is no coincidence.
It is thus not surprising that there exists no $\leq_i$-minimal consistent fixpoint, as disjunctive logic programs allow for more than one ($\leq_i$-minimal) weakly supported model.
\end{example}
The following example shows that existence of a consistent fixpoint of an ndao is not guaranteed either:
\begin{example}
Since we are interested in a consistent fixpoint, it suffices to restrict our attention to the consistent pairs.
Consider an operator ${\cal O}$ over the billatice constructed on the powerset of $\{p,q\}$ and defined as follows:
\begin{eqnarray*}
{\cal O}(\emptyset,\{p,q\})&=&(\{\emptyset\},\{\{p\},\{q\}\})\\ %
{\cal O}(\{p\},\{p\})&=& (\{q\},\{q\})\\
{\cal O}(\{q\},\{q\})&=& (\{p\},\{p\})\\
{\cal O}(x,y) &=&(\{\{p\},\{q\}\}, \{\{p\},\{q\}\}) \quad \forall(x,y)\not\in \{(\{p\},\{p\}),(\{q\},\{q\})\}
\end{eqnarray*}
It is easily observed that ${\cal O}$ is $\leq_i$-monotonic. Since ${\cal O}_l(x,x)={\cal O}_u(x,x)$ for any $x\subseteq \{p,q\}$, it is also exact\xspace.
This operator can be visualized as follows:
\begin{center}
\begin{tikzpicture}[scale=0.85]
\tikzset{edge/.style = {->,> = latex'}}
\node[draw, scale=0.8] (empty) at (0,0) {$(\emptyset,\{p,q\})$};
\node[draw, scale=0.8] (a) at (-4.5,2) {$(\{p\},\{p,q\})$};
\node[draw, scale=0.8] (b) at (-1.5,2) {$(\{q\},\{p,q\})$};
\node[draw, scale=0.8] (na) at (1.5,2) {$(\emptyset,\{p\})$};
\node[draw, scale=0.8] (nb) at (4.5,2) {$(\emptyset,\{q\})$};
\node[draw, scale=0.8] (ab) at (-4.5,4) {$(\{p,q\},\{p,q\})$};
\node[draw, scale=0.8] (nab) at (-1.5,4) {$(\{p\},\{p\})$};
\node[draw, scale=0.8] (anb) at (1.5,4) {$(\{q\},\{q\})$};
\node[draw, scale=0.8] (nanb) at (4.5,4) {$(\emptyset,\emptyset)$};
\draw[edge, bend right=10, line width=0.5] (empty) to (na);
\draw[edge, bend right=10, line width=0.5] (empty) to (nb);
\draw[edge, line width=0.5] (na) to (anb);
\draw[edge, line width=0.5, bend left=10] (na) to (nab);
\draw[edge, line width=0.5, bend left=10] (nb) to (anb);
\draw[edge, line width=0.5] (nb) to (nab);
\draw[edge, line width=0.5] (a) to (anb);
\draw[edge, line width=0.5] (a) to (nab);
\draw[edge, line width=0.5, bend right=10] (b) to (anb);
\draw[edge, line width=0.5] (b) to (nab);
\draw[edge, line width=0.5] (nanb) to (anb);
\draw[edge, line width=0.5] (ab) to (nab);
\draw[edge, bend right, line width=0.5] (nanb) to (nab);
\draw[edge, bend left, line width=0.5] (ab) to (anb);
\draw[edge, line width=0.5] (anb) to (nab);
\draw[edge, line width=0.5] (nab) to (anb);
\draw[edge, -, dotted] (empty) to (nb);
\draw[edge,-, dotted] (empty) to (na);
\draw[edge,-, dotted] (empty) to (a);
\draw[edge,-, dotted] (empty) to (b);
\draw[edge,-, dotted] (a) to (ab);
\draw[edge,-, dotted] (a) to (nab);
\draw[edge,-, dotted] (b) to (ab);
\draw[edge,-, dotted] (b) to (anb);
\draw[edge,-, dotted] (na) to (nab);
\draw[edge,-, dotted] (na) to (nanb);
\draw[edge,-, dotted] (nb) to (nanb);
\draw[edge,-, dotted] (nb) to (anb);
\node[scale=0.8] (empty) at (current bounding box.south west) {
\begin{tabular}{l}
$\sampleline{->}$: application of ${\cal O}$.\\
$\sampleline{-,dotted}$: $\leq_i$.
\end{tabular}
};
\node[scale=0.8] (empty) at (current bounding box.south east) {
\phantom{\begin{tabular}{l}
$\sampleline{->}$: application of ${\cal O}$.\\
$\sampleline{-,dotted}$: $\leq_i$.
\end{tabular}}
};
\end{tikzpicture}
\end{center}
It can be verified that this operator is $\preceq^A_i$-monotonic, yet it admits no consistent fixpoint.
\end{example}
Although some properties of fixpoints of approximation operators do not carry over from the deterministic to the non-deterministic setting,
fixpoints of a non-deterministic operator ${\cal O}$ have been studied in the literature. The following theorem shows that
in the context of disjunctive logic programming, the fixpoints of the operator ${\cal IC}_{\cal P}$ characterize the weakly supported models of ${\cal P}$.
It thus provides a first representation of semantics of logic programs that are not covered by (fixpoints of) deterministic AFT.
\begin{theorem}
\label{theo:correspondence:supported}
Given a dlp ${\cal P}$ and a consistent interpretation $(x,y)\in (\wp({\cal A}_{\cal P}))^2$, it holds that $(x,y)$ is a weakly supported model of ${\cal P}$
iff $(x,y)\in {\cal IC}_{\cal P}(x,y)$.
\end{theorem}
\begin{proof}
\noindent
$[\Rightarrow]$ Suppose that $(x,y)$ is weakly supported.
We first show that for every $\Delta\in \mathcal{HD}^l_{\cal P}(x,y)$, $\Delta\cap x\neq \emptyset$.
Indeed, let $\Delta\in \mathcal{HD}^l_{\cal P}(x,y)$, i.e.\ $\bigvee\!\Delta\leftarrow \phi \in {\cal P}$ and $(x,y)(\phi)={\sf T}$ (notice that since $(x,y)$ is consistent, $(x,y)(\phi)\neq {\sf C}$).
Since $(x,y)$ is a model of ${\cal P}$, $(x,y)(\bigvee\!\Delta)\geq_t {\sf T}$, and so $\Delta\cap x\neq\emptyset$.
We now show that $y\cap \mathcal{HD}^u_{\cal P}(x,y)\neq\emptyset$. Suppose for this that $(y,x)(\phi)\in \{{\sf C},{\sf T}\}$ for some $\bigvee\!\Delta\leftarrow\phi\in{\cal P}$.
We first show the following lemma:
\begin{lemma}
\label{lemma:values:of:formulas:switch}
For any formula $\phi$ and any $x, y\subseteq {\cal A}_{\cal P}$, $(y,x)(\phi)\in \{{\sf T},{\sf C}\}$ implies that $(x,y)(\phi)\in \{{\sf T},{\sf U}\}$ and
$(y,x)(\phi)\in \{{\sf F},{\sf C}\}$ implies that $(x,y)(\phi)\in \{{\sf F},{\sf U}\}$.
\end{lemma}
\begin{proof}
We show this by induction on the structure of $\phi$.
For the base case, suppose that $\phi\in{\cal A}_{\cal P}$. If $(y,x)(\phi)\in \{{\sf T},{\sf C}\}$, then $\phi\in y$ and thus $(x,y)(\phi)\in \{{\sf T},{\sf U}\}$.
Likewise, $(y,x)(\phi)\in \{{\sf F},{\sf C}\}$ means that $\phi\not\in x$ and thus $(x,y)(\phi)\in \{{\sf F},{\sf U}\}$.
For the inductive case, suppose that the claim holds for $\phi$ and $\psi$. If $(y,x)(\lnot \phi)\in \{{\sf T},{\sf C}\}$, then
$(y,x)(\phi)\in \{{\sf F},{\sf C}\}$, and with the inductive hypothesis, $(x,y)(\phi)\in \{{\sf F},{\sf U}\}$, which implies that $(y,x)(\lnot \phi)\in \{{\sf T},{\sf U}\}$.
The other cases are similar.
\end{proof}
By Lemma~\ref{lemma:values:of:formulas:switch} and since $\Delta\in \mathcal{HD}^{u}_{\cal P}(x,y)$ implies there is some $\bigvee\!\Delta\leftarrow \phi\in{\cal P}$ with
$(y,x)(\phi)\in \{{\sf T},{\sf C}\}$, it follows that for every $\Delta\in \mathcal{HD}^{u}_{\cal P}(x,y)$, $\Delta\cap y\neq \emptyset$. %
It remains to be shown is that $x\subseteq \bigcup\mathcal{HD}^l_{\cal P}(x,y)$, and $y\subseteq \bigcup\mathcal{HD}^l_{\cal P}(y,x)=\bigcup\mathcal{HD}^u_{\cal P}(x,y)$,
which is immediate from the fact that since $(x,y)$ is weakly supported, for every atom that is true (respectively undecided) we can find a rule whose body is true
(respectively undecided) that has this atom in the head.
\medskip\noindent
$[\Leftarrow]$ Suppose that $(x,y)\in {\cal IC}_{\cal P}(x,y)$. We first show that $(x,y)$ is a model of ${\cal P}$. Indeed, suppose that for
$\bigvee\!\Delta\leftarrow\phi\in{\cal P}$, $(x,y)(\phi)={\sf T}$. Then $\Delta\in \mathcal{HD}_{\cal P}^l(x,y)$ and thus
(since $(x,y)\in {\cal IC}_{\cal P}(x,y)$),
$\Delta\cap x\neq \emptyset$, i.e., $(x,y)(\bigvee\!\Delta)={\sf T}$. The case for $(x,y)(\phi)={\sf U}$ is similar and the case for $(x,y)(\phi)={\sf F}$ is trivial.
We now show that $(x,y)$ is weakly supported.
Indeed, consider some $p\in x$, and suppose towards a contradiction that there is no $\bigvee\!\Delta\leftarrow\phi\in{\cal P}$ s.t.\
$(x,y)(\phi)={\sf T}$. But then $p\not\in \bigcup{\cal HD}^{l}_{\cal P}(x,y)$ and thus we have a contradiction to $x\subseteq \bigcup{\cal HD}^{l}_{\cal P}(x,y)$
(which we know since $x\in {\cal IC}_{\cal P}^l(x,y)$). The proof for $p\in y$ is similar.
\end{proof}
We now turn to the representation of supported models. As supported models allow for the truth of less atoms than the weakly supported models, one might conjecture
that supported models are the $\leq_t$-minimal fixpoints of ${\cal IC}_{\cal P}$, but this does not hold, not even for positive or normal programs:
\begin{example}
Take ${\cal P}=\{p\leftarrow r; \ r\leftarrow r\}$. Then $(\{p,r\},\{p,r\})$ and $(\emptyset,\emptyset)$ are both supported models of ${\cal P}$,
but $(\{p,r\},\{p,r\})$ is not $\leq_t$-minimal.
\end{example}
The supported models can actually be characterized as the fixpoints of ${\cal IC}_{\cal P}^m$ as defined in Remark~\ref{remark:minimality:in:the:op}.
We refer to~\cite{DBLP:conf/kr/HeyninckA21} for more details on how this can be done.
However, this operator is not $\preceq^A_i$-monotonic (as shown in Remark ~\ref{remark:minimality:in:the:op}).
Next, we show that supported models of a dlp ${\cal P}$ may also be characterized by the fixpoints of ${\cal IC}_{\cal P}$,
but this time together with $\subseteq$-minimization.
\begin{theorem}
Given a dlp ${\cal P}$ and a consistent interpretation $(x,y)\in \wp({\cal A}_{\cal P})^2$. Then $(x,y)$ is a supported model of ${\cal P}$
iff $x\in\min_{\subseteq}( {\cal IC}^l_{\cal P}(x,y))$ and $y\in\min_{\subseteq}( {\cal IC}^u_{\cal P}(x,y))$.
\end{theorem}
\begin{proof}
\noindent
$[\Rightarrow]$ Suppose that $(x,y)$ is a supported model of ${\cal P}$ and consider some $\Delta\in \mathcal{HD}^l_{\cal P}(x,y)$. Since $(x,y)$ is in particular weakly supported, by
Theorem~\ref{theo:correspondence:supported} it follows that $\Delta\cap x\neq \emptyset$.
We show that $x\in \min_\subseteq(\{ v\mid v\cap \Delta\neq\emptyset \text{ for every }\Delta\in\mathcal{HD}^l_{\cal P}(x,y)\}$.
Indeed, suppose towards a contradiction that there is some $x'\in \{ v\mid v\cap \Delta\neq\emptyset \text{ for every }\Delta\in\mathcal{HD}^l_{\cal P}(x,y)\}$ such that $x'\subsetneq x$.
Let $\alpha\in x\setminus x'$. Then, since $(x,y)$ is supported, there is a $\bigvee\!\Delta\leftarrow \phi \in {\cal P}$ such that $\Delta\cap x=\{\alpha\}$ and
$(x,y)(\phi)={\sf T}$. But then $x'\not \in {\cal IC}^l_{\cal P}(x,y)$, in a contradiction to our assumption that $x'\in \min_\subseteq({\cal IC}^l{\cal P}(x,y))$. Analogously, we can show that
$y\in \min_\subseteq(\{ v\mid v\cap \Delta\neq\emptyset \text{ for every }\Delta\in\mathcal{HD}^u_{\cal P}(x,y)\}$.
\smallskip\noindent $[\Leftarrow]$ Suppose that $x\in\min_{\subseteq}( {\cal IC}^l_{\cal P}(x,y))$ and $y\in\min_{\subseteq}( {\cal IC}^u_{\cal P}(x,y))$.
By Theorem~\ref{theo:correspondence:supported} it follows that $(x,y)$ is weakly supported and thus a model of ${\cal P}$.
We now show that $(x,y)$ is supported. Indeed, let $\alpha\in \Delta \cap x$. Suppose first that there is no $\bigvee\!\Delta\leftarrow\phi\in{\cal P}$ s.t.\
$(x,y)(\phi)={\sf T}$. Then $x\not\in min_{\subseteq}(\{v\mid v\cap \Delta\neq \emptyset\text{ for every }\Delta\in\mathcal{HD}^l_{\cal P}(x,y)\}$, since there is some
$x' \subseteq x\setminus \{\alpha\}$ such that $x' \in min_{\subseteq} (\{v\mid v\cap \Delta\neq \emptyset\text{ for every }\Delta\in\mathcal{HD}^l_{\cal P}(x,y)\}$.
Similarly for $(x,y)(\phi)={\sf U}$. The proof of the second condition in the definition of supported models is similar.
\end{proof}
To summarize the results in this section, we conclude that in contradistinction to deterministic AFT, a $\leq_i$-minimal fixpoint of an ndao is neither guaranteed to be
unique nor guaranteed to exist. Nevertheless, fixpoint semantics allow for an operator-based characterization of weakly supported and supported models of disjunctive logic programs.
In the next section we introduce the state semantics which is guaranteed to exist and be unique.
\subsection{Kripke-Kleene States}
\label{sec:kripke:kleene:state}
In the previous section, we saw that a (unique) $\leq_i$-minimal fixpoint of an ndao is not guaranteed to exist. This is perhaps not surprising, as the application of an ndao
to a pair $(x,y)$ gives rise to a set of lower and upper bounds instead of a single lower and a single upper bound. This means that the method for constructing a
$\leq_i$-minimal fixpoint of a deterministic approximation fixpoint operator ${\cal O}_{\sf det}$ over a complete lattice by iteratively constructing more and more precise
approximations by the converging sequence
\[(\bot,\top)\leq_i {\cal O}_{\sf det}(\bot,\top)\leq_i {\cal O}_{\sf det}^2(\bot,\top)\leq_i \ldots\]
(where $\bot$ and $\top$ respectively represent the minimal and the maximal lattice element)
is not well-defined, as an ndao ${\cal O}$ cannot be applied to the pair of sets ${\cal O}^i(\bot,\top)$. However, we can circumvent this deficit by looking at
operators which allow for pairs of sets in their input. Intuitively, we start with a set of lower bounds $\{x_1,x_2,\ldots\}$ and a set of upper bounds $\{y_1,y_2,\ldots\}$,
and construct a new, more precise set of lower respectively upper bounds on the basis of them. Thus, instead of approximating a single element $z$ by a
pair of elements $(x,y)$, we are now approximating a set of elements $\{z_1,z_2,\ldots\}$ by a pair of sets of elements $\{x_1,x_2,\ldots\}$ and $\{y_1,y_2,\ldots\}$.
An approximation of such a set of elements can then be seen as a {\em convex set\/} (Remarks~\ref{rem:convex-set}), bounded below by the lower bounds
$\{x_1,x_2,\ldots\}$ and bounded above by the upper bounds $\{y_1,y_2,\ldots\}$. We first recall some basic notions and notations concerning convex sets.
\subsubsection{Preliminaries on Convex Sets}
Recall from Remarks~\ref{rem:convex-set} that a convex set is a set without ``holes'', that is, a set $X$ such that if two elements $x$ and $y$ are in $X$, then also any
element between $x$ and $y$ is in $X$.
Such as set can be viewed as consisting of all elements in between lower bounds and an upper bounds. A convex set can be obtained by the upwards closure of their
lower bound and the downwards closure of their upper bound, as defined next:
\begin{definition}
Given a lattice $L=\langle {\cal L},\leq\rangle$ and an element $x\in {\cal L}$, then:
\begin{itemize}
\item the \emph{upwards closure\/} of $x$ is $\upclosure{x}:=\{y\in {\cal L}\mid x\leq y\}$.
\item the \emph{downwards closure\/} of $x$ is $\downclosure{x}:=\{y\in {\cal L}\mid x\geq y\}$.
\end{itemize}
We lift this to sets of elements $X\subseteq {\cal L}$ as follows:
\begin{itemize}
\item the \emph{upwards closure\/} of $X$ is $\upclosure{X}:=\bigcup_{x\in X}\upclosure{x}$,
\item the \emph{downwards closure\/} of $X$ is $\downclosure{X}:=\bigcup_{x\in X}\downclosure{x}$.
\end{itemize}
A set is \emph{upwards [downwards] closed\/}, if $X=\upclosure{X}[X=\downclosure{X}]$.
We denote the set of upwards closed (respectively downwards closed) subsets of $\mathcal{L}$ by $\wp_\uparrow({\cal L})$ (respectively $\wp_\downarrow({\cal L})$).
\end{definition}
It can be shown that every set of elements is $\preceq^S_L$-equivalent to its upwards closure and $\preceq^H_L$-equivalent to its downwards closure:
\begin{lemma}
\label{lem:S-H-equivalence}
Given a lattice $L=\langle {\cal L},\leq\rangle$ and a set $X\subseteq {\cal L}$, it holds that:
\begin{enumerate}
\item $\upclosure{X}\preceq^S_L X$ and $ X \preceq^S_L \upclosure{X}$, and
\item $\downclosure{X}\preceq^H_L X$ and $ X \preceq^H_L \downclosure{X}$.
\end{enumerate}
\end{lemma}
\begin{proof}
Item~1.\ Since $\upclosure{X}\supseteq X$, it immediately holds that $ \upclosure{X}\preceq^S_L X$. We now show $ X \preceq^S_L \upclosure{X}$.
Consider some $x\in \upclosure{X}$. This means there is some $y\in X$ s.t.\ $y\leq x$.
Item~2.\ Since $\downclosure{X}\supseteq X$, it immediately holds that $ X \preceq^H_L \downclosure{X}$.
We now show $ \downclosure{X}\preceq^H_L X$. Consider some $x\in \downclosure{X}$. By the definition of $\downclosure{X}$,
there is some $y\in {\cal X}$ s.t.\ $x\leq y$.
\end{proof}
The last lemma gives further motivation to using $\preceq^S_L$ for comparing lower bounds and
$\preceq^H_L$ for comparing upper bounds. Indeed, if $x\in X$ is a lower bound for $z$, then any $x\leq y$ is also a good candidate for being (or better, approximating) $z$,
and likewise, if $x\in X$ is an upper bound for $z$, then any $y\leq x$ is also a good candidate for being (or approximating) $z$.
Lemma~\ref{lem:S-H-equivalence} also means that we can restrict attention to upwards closed sets when using $\preceq^S_L$ and
to downwards closed sets when using $\preceq^H_L$, without losing any information.
The sets $\wp_\uparrow({\cal L})$ and $\wp_\downarrow({\cal L})$ admit greatest lower bounds under $\preceq^S_L$ and least upper bounds under $\preceq^H_L$
(respectively):
\begin{lemma}
Let $\mathcal{X}\subseteq \wp_\uparrow({\cal L})$ be given. Then $\bigcup{\cal X}$ is the greatest lower bound (under $\preceq^S_L$) of $\mathcal{X}$
and $\bigcap{\cal X}$ is the least upper bound (under $\preceq^S_L$) of $\mathcal{X}$.%
\footnote{Recall that we use small letters to denote elements of lattice, capital letters to denote sets of elements, and capital calligraphic letters to denote sets of sets of elements
(Table~\ref{tab:set-notations}).}
\end{lemma}
\begin{proof}
We show that $\bigcup{\cal X}$ is the greatest lower bound by showing the following claims:
\begin{itemize}
\item $\bigcup{\cal X}\in \wp_\uparrow({\cal L})$. To see this, consider some $x\in \bigcup{\cal X}$. Then there is some $X\in {\cal X}$ s.t.\ $x\in X$, and thus since
$X\in\wp_\uparrow({\cal L})$, every $y\in X$ s.t.\ $x \leq y$ is also in $X$, and therefore in $\bigcup{\cal X}$.
\item $\bigcup{\cal X}\preceq^S_L X$ for any $X\in {\cal X}$. This immediately follows from the fact that for any
$x\in X$, $x\in \bigcup{\cal X}$.
\item For any $Z\in \wp_\uparrow({\cal L})$ s.t.\ $Z\preceq^S_L X$ for every $X\in {\cal X}$, $Z\preceq^S_L \bigcup{\cal X}$. For this, consider some $Z\in \wp_\uparrow({\cal L})$ s.t.\ $Z\preceq^S_L X$ for every $X\in {\cal X}$ and consider some $x\in \bigcup{\cal X}$. Since $x\in X$ for some $X\in {\cal X}$, there is some $z\in Z$ s.t.\ $z\leq x$. Thus, for every $x\in \bigcup{\cal X}$, there is some $z\in Z$ s.t.\ $z\leq x$, which implies that $Z\preceq^S_L \bigcup{\cal X}$.
\end{itemize}
We show that $\bigcap{\cal X}$ is the least upper bound by showing the following claims:
\begin{itemize}
\item $\bigcap{\cal X}\in \wp_\uparrow({\cal L})$. To see this, consider some $x\in \bigcap{\cal X}$. Then for every $X\in {\cal X}$, it holds that $x\in X$, and thus since
$X\in\wp_\uparrow({\cal L})$, every $y\in X$ s.t.\ $x\leq y$ is also in $X$, and therefore (since this holds for every $X\in {\cal X}$), $y$ is also in $\bigcap{\cal X}$.
\item $X \preceq^S_L \bigcap{\cal X}$ for any $X\in {\cal X}$. This follows from the fact that for any $x\in \bigcap{\cal X}$, $x\in X$ for every $X\in{\cal X}$.
\item For any $Z\in \wp_\uparrow({\cal L})$ s.t.\ $X\preceq^S_L Z$ for every $X\in {\cal X}$, $ \bigcap{\cal X}\preceq^S_L Z$. For this, consider some $Z\in \wp_\uparrow({\cal L})$ s.t.\ $X\preceq^S_L Z$ for every $X\in {\cal X}$ and consider some $z\in Z$. Since $X\preceq^S_L Z$, there is some $x\in X$ s.t.\ $x\leq z$. Since $X$ is upwards closed, $z\in X$.
Notice that this holds for any $X\in {\cal X}$, and thus $z\in \bigcap{\cal X}$, which means that $Z\subseteq \bigcap{\cal X}$ and thus $ \bigcap{\cal X}\preceq^S_L Z$. \qedhere
\end{itemize}
\end{proof}
The next lemma is proven like the previous one.
\begin{lemma}
Let some $\mathcal{X}\subseteq \wp_\downarrow({\cal L})$ be given. Then $\bigcap{\cal X}$ is the greatest lower bound (under $\preceq^H_L$) of $\mathcal{X}$ and $\bigcup{\cal X}$ is the least upper bound (under $\preceq^H_L$) of $\mathcal{X}$.
\end{lemma}
By the last two lemmas, one can construct lower respectively upper bounds for sets of pairs of sets under $\preceq^A_i$:
\begin{corollary}
\label{fact:lub:and:glb:under:preceq}
Let some $\mathbfcal{Z} \subseteq \wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})$ be given. Then
$(\bigcup \{X\mid (X,Y)\in \mathbfcal{Z}\},\bigcup \{Y\mid (X,Y)\in \mathbfcal{Z}\})$ is the greatest lower bound of (under $\preceq^A_i$) of $\mathbfcal{Z}$
and $(\bigcap \{X\mid (X,Y)\in \mathcal{Z}\},\bigcap \{Y\mid (X,Y)\in \mathbfcal{Z}\})$ is the least upper bound of (under $\preceq^A_i$) of $\mathbfcal{Z}$.
\end{corollary}
\subsubsection{Non-deterministic State Operators and Their Fixpoints}
We can now introduce \emph{non-deterministic state approximation operators\/}\footnote{The use of the word \emph{state\/} comes from disjunctive logic programming,
where a set of interpretations is often called a state~\cite{minker2002disjunctive,seipel1998alternating}.} that generate a convex set on the basis of a convex set.
Thus, the type of a non-deterministic state approximation operator ${\cal O}'$ is
$\wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})\rightarrow \wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})$.
As outlined above, the idea is that a non-deterministic state approximation operator generates an approximation of a set of elements $\{z_1,z_2,\ldots\}$
on the basis of an approximation of a set of elements. Just like an ndao, we require information-monotonicity, i.e.\ more precise inputs give rise to more
precise outputs, and exactness, i.e., a convex set consisting of a single element as input gives rise to at least one element being both in the generated lower and upper bound.
\begin{definition}
\label{def:ndsao}
Let a lattice $L=\langle {\cal L},\leq\rangle$ be given. Then an operator ${\cal O}': \wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})\rightarrow \wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})$ is a \emph{non-deterministic state operator\/} (in short, ndso) if it satisfies the following properties:
\begin{itemize}
\item ${\cal O}'$ is $\preceq^A_i$-monotonic, and
\item ${\cal O}'$ is \emph{exact}, i.e.\ for every $x\in {\cal L}$, there is some $z\in{\cal L}$ such that $z\in {\cal O}'_l(z,z)\cap {\cal O}'_u(z,z)$.\footnote{Alternatively, with a slight abuse of the notations, $(z,z)\in{\cal O}'(\{x\}\times\{x\})$.}
\end{itemize}
An ndso \emph{approximates\/} a non-deterministic operator $O$ iff for any $x\in {\cal L}$, ${\cal O}'(\{(x,x)\})=\upclosure{O(x)}\times \downclosure{O(x)}$.
\end{definition}
\begin{remark}
\label{remark:ndso:from:ndao}
A non-deterministic state operator can be straightforwardly derived on the basis of an ndao as follows:
\[
{\cal O}'({\bf X})=
\bigcup_{(x,y)\in{\bf X}}\upclosure{{\cal O}_l(x,y)}\times
\bigcup_{(x,y)\in{\bf X}}\downclosure{{\cal O}_u(x,y)}
\]
In that case, we say ${\cal O}'$ is \emph{derived from ${\cal O}$}. If ${\cal O}$ approximates $O$, then so will ${\cal O}'$. Furthermore, ${\cal O}'$ is $\preceq^A_i$-monotonic.
In fact, the $\preceq^A_i$-monotonicity of ${\cal O}'$ is independent of the $\preceq^A_i$-monotonicity of ${\cal O}$, as we see in the following proposition:
\begin{proposition}
\label{lemma:O':is:alcantara:monotonic}
For any operator ${\cal O}:{\cal L}^2\rightarrow \wp({\cal L})^2$, it holds that
${\cal O}': \wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})\rightarrow \wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})$ is $\preceq^A_i$-monotonic.
\end{proposition}
\begin{proof}
Consider some $X,X',Y,Y'\subseteq {\cal L}$ s.t.\ $X\times Y\preceq^A_i X'\times Y'$, i.e.\ $X\preceq^S_L X'$ and $Y'\preceq^H_L Y$. We show that ${\cal O}'(X,Y) \preceq^A_i {\cal O}'(X',Y')$.
Consider first $z\in ({\cal O}'(X',Y'))_1$\footnote{Recall that we use $(X\times Y)_1$ to denote the first component of the pair $X\times Y$, i.e.\ $(X\times Y)_1:=X$.
Similarly for $(X\times Y)_2$.}. This means that there are some
$x'\in \upclosure{X'}$ and $y'\in \downclosure{Y'}$ s.t.\ $z\in \upclosure{({\cal O}(x',y'))_1}$. Since $X\preceq^S_L X'$ and $Y'\preceq^H_L Y$, there is some $x\in X$ s.t.\
$x\leq x'$ and some $y\in Y$ s.t.\ $y'\leq y$. Thus, $x'\in \upclosure{X}$ and $y'\in \downclosure{Y}$,
which means that $z\in ({\cal O}'(X,Y))_1$. The case for $({\cal O}'(X',Y'))_2$ is similar. We thus have shown that $({\cal O}'(X',Y'))_1 \subseteq({\cal O}'(X',Y'))_1$ and $({\cal O}'(X',Y'))_2 \subseteq({\cal O}'(X',Y'))_2$, which implies $({\cal O}'(X,Y))_1 \preceq^S_L({\cal O}'(X,Y))_1$ and $({\cal O}'(X',Y'))_2 \preceq^H_L({\cal O}'(X',Y'))_2$, and thus we obtain ${\cal O}'(X,Y) \preceq^A_i {\cal O}'(X',Y')$.
\end{proof}
Likewise, if one is given a ndso ${\cal O'}$, one can obtain an $\preceq^A_i$-monotonic operator ${\cal O}: {\cal L}^2\rightarrow\wp({\cal L}^2)$
by simply letting ${\cal O}(x,y)={\cal O}'(\{x\}\times\{y\})$. Such an operator is not guaranteed to be exact\xspace, though.
\end{remark}
\begin{example}
An ndso that approximates $\mathit{IC}_{\cal P}$ can be defined as follows:
\[{\cal IC}'_{\cal P}({\bf X})= \bigcup_{(x,y)\in{\bf X}}\upclosure{{\cal IC}^l_{\cal P}(x,y)} \ \ \times
\bigcup_{(x,y)\in{\bf X}}\downclosure{{\cal IC}^u_{\cal P}(x,y)} .\]
\end{example}
We show the following property of non-deterministic state operators:
\begin{lemma}
\label{prop:decomposition:of:ndao}
An operator ${\cal O}':\wp({\cal L})^2\rightarrow \wp({\cal L})^2$ is $\preceq^A_i$-monotonic iff for any $X\subseteq {\cal L}$,
${\cal O}'_l(\cdot,X)$ is $\preceq^S_L$-monotonic, ${\cal O}'_l(X,\cdot)$ is $\preceq^S_L$-anti monotonic, ${\cal O}'_u(X,\cdot)$ is $\preceq^H_L$-monotonic,
and ${\cal O}'_u(\cdot,X)$ is $\preceq^H_L$-anti monotonic. \
\end{lemma}
\begin{proof}
$[\Rightarrow]$: Suppose that ${\cal O}':\wp({\cal L})^2\rightarrow \wp({\cal L})^2$ is $\preceq^A_i$-monotonic and consider some
$X, Y_1,Y_2\subseteq {\cal L}$ s.t.\ $Y_1\preceq^S_L Y_2$. We first show that ${\cal O}'_l(Y_1,X)\preceq^S_L {\cal O}'(Y_2,X)$. For this, notice that $(Y_1,X)\preceq^A_i (Y_2,X)$
(because $Y_1\preceq^S_L Y_2$). Since ${\cal O}'$ is $\preceq^A_i$-monotonic,
${\cal O}'(Y_1,X)\preceq^A_i{\cal O}'(Y_2,X)$, which on its turn means that ${\cal O}'_l(Y_1,X)\preceq^S_L {\cal O}'_l(Y_2,X)$.
We now show that ${\cal O}'_u(X,.)$ is $\preceq^H_L$-monotonic. For this,
consider some $X, Y_1,Y_2\subseteq {\cal L}$ s.t.\ $Y_2\preceq^H_L Y_1$. Then $(X,Y_1)\preceq^A_i (X,Y_2)$ (since $X\preceq^S_L X$). With the $\preceq^A_i$-monotonicity
of ${\cal O}'$, ${\cal O}'(X,Y_1)\preceq^A_i {\cal O}'(X,Y_2)$, which implies that ${\cal O}'_u(X,Y_2)\preceq^H_L {\cal O}'_u(X,Y_1)$. Thus, $Y_2\preceq^H_L Y_1$ implies
${\cal O}'_u(X,Y_2)\preceq^H_L {\cal O}'_u(X,Y_1)$ and ${\cal O}'_u(X,.)$ is $\preceq^H_L$-monotonic (for any $X\subseteq {\cal L}$). The two other cases are similar.
\smallskip\noindent$[\Leftarrow]$: Suppose that for any $X\subseteq {\cal L}$, ${\cal O}'_l(\cdot,X)$ is $\preceq^S_L$-monotonic,
${\cal O}'_l(X,\cdot)$ is $\preceq^S_L$-anti monotonic, ${\cal O}'_u(X,\cdot)$ is $\preceq^H_L$-monotonic, and ${\cal O}'_u(\cdot,X)$ is $\preceq^H_L$-anti monotonic.
Consider some $X_1,X_2, Y_1,Y_2\subseteq {\cal L}$ s.t.\ $X_1\times Y_1\preceq^A_i X_2\times Y_2$. We first show that ${\cal O}'_l(X_1,Y_1)\preceq^S_L {\cal O}'_l(X_2,Y_2)$.
For this, notice that $Y_2\preceq^S_L Y_1$ and thus, with the $\preceq^S_L$-anti monotonicity of ${\cal O}'_l(X_1,\cdot)$,
${\cal O}'_l(X_1,Y_1)\preceq^S_L {\cal O}'_l(X_1,Y_2)$. Likewise, it can be shown that $ {\cal O}'_l(X_1,Y_2)\preceq^S_L {\cal O}'_l(X_2,Y_2)$
and sot ${\cal O}'_l(X_1,Y_1)\preceq^S_L{\cal O}'_l(X_2,Y_2)$. The proof for ${\cal O}'_u$ is analogous.
\end{proof}
We define consistency for an ndso analogously as for an ndao, namely:
\begin{definition}
An ndso ${\cal O}'$ is \emph{consistent} if for every $x,y\in {\cal L}$ s.t.\ $x\leq y$, there is a $w\in {\cal O}'_l(\{x\}\times \{y\})$ and $z\in {\cal O}'_u(\{x\}\times \{y\})$,
(or, slightly abusing notation, $(w,z)\in{\cal O}'(\{x\}\times \{y\})$, such that $w\leq z$.
\end{definition}
We note that for a consistent ndso ${\cal O}'$, for any $X, Y\subseteq {\cal L}$ for which $\upclosure{X} \cap \downclosure{Y}\neq \emptyset$, it holds that
$\upclosure{{\cal O}'_l(X\times Y)}\cap \downclosure{{\cal O}'_u(X\times Y)}\neq \emptyset$. Therefore, for any consistent ndso, a non-empty convex set
in the input (i.e.\ $\upclosure{X} \cap \downclosure{Y}\neq \emptyset$) gives rise to a non-empty convex set in the output
($\upclosure{{\cal O}'_l(X\times Y)}\cap \downclosure{{\cal O}'_u(X\times Y)}\neq \emptyset$).
The next proposition shows that exact\xspace state operators are consistent (cf.\ Proposition~\ref{prop:weak:consistency} for ndso's).
\begin{proposition}
\label{theorem:ndso:consistency}
Let ${\cal O}': \wp({\cal L})\times \wp({\cal L})\rightarrow \wp({\cal L})\times \wp({\cal L})$ be an ndso.
Then ${\cal O}'$ is consistent.
\end{proposition}
\begin{proof}
Suppose that ${\cal O}'$ is exact, i.e., for every $x\in {\cal L}$, and for some $z\in{\cal L}$, $z\in{\cal O}_l'(\{x\},\{x\})$ and $z\in{\cal O}_u'(\{x\},\{x\})$.
This means that there is some $z\in {\cal L}$ s.t.\ $z\in {\cal O}'_l(\{x\},\{x\})\cap {\cal O}'_u(\{x\},\{x\}$.
By Lemma~\ref{prop:decomposition:of:ndao}, ${\cal O}'_l(\{x\},\{y\})\preceq^S_L{\cal O}'_l(\{x\},\{x\})$ and ${\cal O}'_u(\{x\},\{x\})\preceq^H_L{\cal O}'_u(\{x\},\{y\})$.
Thus, there is some $w\in {\cal O}'_l(\{x\},\{y\})$ s.t.\ $w\leq z$ and there is some $w'\in {\cal O}'_u(\{x\},\{y\})$ s.t.\ $z\leq w'$. With transitivity of $\leq$, $w\leq w'$ and thus
(slightly abusing notation) there is a consistent pair $(w,w')\in {\cal O}'(x,y)$.
\end{proof}
Another useful property is the fact that the computation of ${\cal O}'(\upclosure{X}\times \downclosure{Y})$ can be simplified by computing ${\cal O}'(X\times Y)$:
\begin{lemma}
Let ${\cal O}':\wp({\cal L})\times \wp({\cal L})\rightarrow\wp({\cal L})\times \wp({\cal L})$ be a ndso.
Then for any $X,Y\subseteq {\cal L}$, ${\cal O}'(\upclosure{X} \times \downclosure{Y}) = {\cal O}'(X\times Y)$.
\end{lemma}
\begin{proof}
The $\supseteq$-direction is clear.
Suppose now that $w\in ({\cal O}'(\upclosure{X}\times \downclosure{Y}))_1$ and $z\in ({\cal O}'(\upclosure{X}\times \downclosure{Y}))_1$.
Then there are some $x\in \upclosure{X}$ and $y\in \downclosure{Y}$ s.t.\ $w\in \upclosure{{\cal O}_l(x,y)}$ and $z\in \downclosure{{\cal O}_u(x,y)}$.
Thus, there are some $x'\in X$ and some $y'\in Y$ s.t.\ $x'\leq x$ and $y\leq y'$. This implies that $(x',y')\leq_i(x,y)$ and with the $\preceq^A_i$-monotonicity of
${\cal O}$, we have ${\cal O}(x',y')\preceq^A_i{\cal O}(x,y)$. Thus, ${\cal O}_{l}(x',y')\preceq^S_L {\cal O}_{l}(x,y)$, which implies that
${\cal O}'_{l}(x',y')=\upclosure{{\cal O}_{l}(x',y')}\supseteq \upclosure{{\cal O}_{l}(x,y)}$. The case for the upper bound is analogous.
\end{proof}
We now show that an ndso admits a unique $\preceq^A_i$-minimal fixpoint:
\begin{theorem}
\label{theorem:ndso:fixpoint}
Let $L=\tup{{\cal L},\leq}$ be a complete lattice.
Every $\preceq^A_i$-monotonic operator ${\cal O}':\wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})\rightarrow \wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})$
admits a unique $\preceq^A_i$-minimal fixpoint that can be constructed by iterative application of ${\cal O}'$ to $(\bot,\top)$. If ${\cal O}'$ is exact\xspace, this fixpoint is consistent.
\end{theorem}
\begin{proof}
Let $L=\tup{{\cal L},\leq}$ be a complete lattice and let
${\cal O}':\wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})\rightarrow \wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})$ be a $\preceq^A_i$-monotonic operator. Then $\langle\wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L}), \preceq^A_i\rangle$ forms a lattice (in view of
Corollary~\ref{fact:lub:and:glb:under:preceq} and since $\preceq^A_i$ is a reflexive, transitive and anti-symmetric order over $\wp_\uparrow({\cal L})\times \wp_\downarrow({\cal L})$). We can apply Knaster and Tarski's fixpoint theorem to show that the set of fixed-points of ${\cal O}'$ forms a complete lattice, and thus
the $\preceq^A_i$-monotonic operator ${\cal O}'$ admits a unique $\preceq^A_i$-minimal fixpoint. Consistency follows from Proposition~\ref{theorem:ndso:consistency}.
\end{proof}
We call the $\preceq^A_i$-minimal fixpoint of ${\cal O}'$ that is guaranteed by Theorem~\ref{theorem:ndso:fixpoint} the \emph{Kripke-Kleene state of ${\cal O}'$\/},
and denote it by ${\sf KK}({\cal O}')$. Some examples of Kripke-Kleene state for logic programs can be found in Examples~\ref{examp:state-KK-1} and~\ref{examp:state-KK-2}
below.
For the Kripke-Kleene state of an ndso that is derived from an ndao ${\cal O}$, we can show the following additional results:
\begin{proposition}
\label{prop:KK-states-properties}
Let $L=\tup{{\cal L},\leq}$ be a complete lattice.
Given an ndso ${\cal O}'$ derived from an ndao ${\cal O}$, we have the following:
\begin{itemize}
\item For any fixpoint $(x,y)$ of ${\cal O}$, ${\sf KK}({\cal O}')\preceq^A_i (x,y)$,
\item ${\sf KK}({\cal O}')$ contains at least one consistent pair.
\item If ${\cal O}'$ approximates a non-deterministic operator $O$,
then for any $x\in {\cal L}$ s.t.\ $x\in O(x)$, it holds that ${\sf KK}({\cal O}')\preceq^A_i (x,x)$.
\end{itemize}
\end{proposition}
\begin{proof}
We first show two lemmas:
\begin{lemma}
\label{fact:O:as:precise:as:O'}
For any $x,y\in {\cal L}$, ${\cal O}'(x,y)\preceq^A_i {\cal O}(x,y)$.
\end{lemma}
\begin{proof}
Since ${\cal O}'(x,y)=\upclosure{{\cal O}_l(x,y)}\times \downclosure{{\cal O}_u(x,y)}$, for every $w\in {\cal O}_l(x,y)$, there is some $w'\in \upclosure{{\cal O}_l(x,y)}$ s.t.\
$w'\leq w$ and for every $z\in {\cal O}_u(x,y)$ there is some $z'\in \downclosure{{\cal O}_u(x,y)}$ s.t.\ $z\leq z'$ (namely, $w$ and $z$ themselves).
Thus, ${\cal O}'_l(x,y) \preceq^S_L {\cal O}_l(x,y)$ and ${\cal O}_u(x,y) \preceq^H_L {\cal O}'_u(x,y)$, so the lemma is obtained.
\end{proof}
\begin{lemma}
\label{fact:element:more:precise:than:set}
For any $X,Y\subseteq \wp({\cal L})$, $x\in X$ and $y\in Y$, $X\times Y\preceq^A_i \{x\}\times\{y\}$.
\end{lemma}
\begin{proof}
Clearly, there are some $x'\in X$ and $y'\in Y$ (namely $x'=x$ and $y'=y$) s.t.\ $x'\leq x$ and $y\leq y'$.
\end{proof}
The proof of Proposition~\ref{prop:KK-states-properties} now continues as follows:
For the first item, by Proposition~\ref{theorem:ndso:fixpoint}, we have that ${\sf K}({\cal O}')=({\cal O}')^\alpha(\bot,\top)$ for some ordinal $\alpha$. Furthermore, $(\bot,\top)\leq_i (x,y)$.
By the $\preceq^A_i$-monotonicity of ${\cal O}$, ${\cal O}'(\bot,\top)\preceq^A_i {\cal O}'(\{(x,y)\})$. By Lemma~\ref{fact:O:as:precise:as:O'}, ${\cal O}'(\{(x,y)\})\preceq^A_i {\cal O}(x,y)$,
and by Lemma~\ref{fact:element:more:precise:than:set} and since $(x,y)\in{\cal O}(x,y)$, ${\cal O}'(\bot,\top)\preceq^A_i (x,y)$. We can repeat this process until we reach the ordinal
$\alpha$, and thus $({\cal O}')^\alpha(\bot,\top)={\sf KK}({\cal O}')\preceq^A_i (x,y)$.
The second item is an immediate consequence of Proposition~\ref{theorem:ndso:consistency}.
The proof of the last item is similar to that of the first item.
\end{proof}
Next, we show that for deterministic operators, the Kripke-Kleene state coincides with the Kripke-Kleene fixpoint:
\begin{proposition}
\label{prop:KK-singletons}
Let ${\cal O}:{\cal L}^2\rightarrow \wp({\cal L})^2$ be an ndao s.t.\ ${\cal O}(x,y)$ is a pair of singleton sets for every $x,y\in{\cal L}$, let be ${\cal O}^{\sf AFT}$
defined by ${\cal O}^{\sf AFT}(x,y)=(w,z)$ where ${\cal O}(x,y)=(\{w\},\{z\})$ and let the Kripke-Kleene fixpoint of ${\cal O}^{\sf AFT}$ be given by $(x^{\sf kk},y^{\sf kk})$.
Then ${\sf KK}({\cal O}')=\upclosure{x^{\sf kk}}\times \downclosure{y^{\sf kk}}$, where ${\cal O}'$ is obtained from ${\cal O}$ as described in Remark~\ref{remark:ndso:from:ndao}.
\end{proposition}
\begin{proof}
By Proposition~\ref{prop:deterministic:aft}, ${\cal O}^{\sf AFT}$ is an approximation operator, and thus admits a Kripke-Kleene fixpoint.
For every $x,y\in {\cal L}$, it holds that
\[{\cal O}'(x,y)=\upclosure{\{{\cal O}^{\sf AFT}_l(x,y)\}}\times \downclosure{\{{\cal O}^{\sf AFT}_u(x,y)\}}.\]
Notice furthermore that for any $x,y\in {\cal L}$, if $x'\in \upclosure{x}$ and $y'\in \downclosure{y}$, ${\cal O}(x,y)\preceq_i {\cal O}(x',y')$,
and so ${\cal O}_l(x,y)\preceq^S_L{\cal O}_l(x',y')$, i.e., for every $w'\in {\cal O}_l(x',y')$ there is a $w\in {\cal O}_l(x,y)$ s.t.\ $w\leq w'$. Thus,
${\cal O}_l(x',y')\subseteq \upclosure{{\cal O}_l(x,y)}$ (and similarly for the upper bound: ${\cal O}_u(x',y') \supseteq {\cal O}_u(x,y)$).
This means that for any ordinal $\alpha$,
\[{\cal O}'^\alpha(\bot,\top)=\upclosure{\{({\cal O}^{\sf AFT}_l)^\alpha(\bot,\top)\}}\times \downclosure{\{({\cal O}^{\sf AFT}_u)^\alpha(\bot,\top)\}}.\]
A simple inductive argument then shows the proposition, as ${\sf KK}({\cal O}')={\cal O}'^\alpha(\bot,\top)$ for the smallest ordinal $\alpha$ under which a fixpoint is reached,
and $(x^{\sf KK},y^{\sf KK})=({\cal O}^{\sf AFT})^\alpha(\bot,\top)$ for the smallest ordinal $\alpha$ under which a fixpoint is reached.
\end{proof}
From Proposition \ref{prop:KK-singletons}, we immediately obtain the following corollary in the context of disjunctive logic programs:
\begin{corollary}
Given a dlp ${\cal P}$, ${\sf KK}({\cal IC}_{\cal P})\preceq_i^A (x,y)$ for every weakly supported model $(x,y)$ of ${\cal P}$.
\end{corollary}
Intuitively, the convex set represented by ${\sf KK}({\cal IC}_{\cal P})$ contains every weakly supported model of ${\cal P}$.
We now show some examples for computing Kripke-Kleene states of dlps:
\begin{example}
\label{examp:state-KK-1}
Let ${\cal P}=\{p\lor q\leftarrow\}$. We calculate ${\sf KK}({\cal IC}_{\cal P})$ as follows:
\begin{itemize}
\item ${\cal IC}'_{\cal P}(\emptyset,\{p,q\})= \upclosure{\{ \{p\},\{q\},\{p,q\}\}} \times \downclosure{\{\{p\},\{q\},\{p,q\}\}}$.\footnote{Even though this is in principle
redundant, we added $\{p,q\}$ to the first component for clarity.} This can be seen by observing that ${\cal IC}^l_{\cal P}(\emptyset,\{p,q\})=\{ \{p\},\{q\},\{p,q\}\}$ and
${\cal IC}^l_{\cal P}(\emptyset,\{p,q\})=\{\{p\},\{q\},\{p,q\}\}$.
\item ${\cal IC}'_{\cal P}( \upclosure{\{ \{p\},\{q\},\{p,q\}\}}\times \downclosure{\{\{p\},\{q\},\{p,q\}\}})=\upclosure{\{ \{p\},\{q\},\{p,q\}\}}\times \downclosure{\{\{p\},\{q\},\{p,q\}\}}$
(This can be seen by observing that ${\cal IC}^z_{\cal P}(x,y)= \{\{p\},\{q\},\{p,q\}\}$ for any $z\in \{l,u\}$ and any $x,y\subseteq \{p,q\}$). Thus, a fixpoint is reached.
\end{itemize}
The Kripke-Kleene state in this case thus corresponds to the convex set $\{\{p\},\{q\},\{p,q\}\}$.
\end{example}
\begin{example}
\label{examp:state-KK-2}
Let ${\cal P}=\{p\lor q\leftarrow; \ \ r\lor s\leftarrow \lnot q\}$. We calculate ${\sf KK}({\cal IC}_{\cal P})$ as follows:
\begin{itemize}
\item ${\cal IC}'_{\cal P}(\emptyset,\{p,q,r,s\})= \upclosure{\{ \{p\},\{q\}\}}\times\downclosure{\{\{p,r\},\{p,s\},\{q,r\}\{q,r\}\}}$. We obtain this by observing that
${\cal IC}^l_{\cal P}(\emptyset,\{p,q,r,s\})=\{ \{p\},\{q\}\}$ and ${\cal IC}^u_{\cal P}(\emptyset,\{p,q,r,s\})=\{\{p,r\},\{p,s\},\{q,r\}\{q,r\}\}$.
\item ${\cal IC}'_{\cal P}(\upclosure{\{ \{p\},\{q\}\}}\times \downclosure{\{\{p,r\},\{p,s\},\{q,r\}\{q,r\}\}})=\upclosure{\{ \{p\},\{q\}\}}\times\downclosure{ \{\{p,r\},\{p,s\},\{q,r\}\{q,r\}\}}$
and thus a fixpoint is reached. \smallskip \\
(It should be noticed that in the second step of the iteration, two more precise upper bounds are obtained as well: in view of $(\{p\},\{p,r\})(\lnot q)=(\{p\},\{p,s\})(\lnot q)={\sf T}$,
$\upclosure{{\cal IC}_{\cal P}(\{p\},\{p,r\})}=\upclosure{{\cal IC}_{\cal P}(\{p\},\{p,s\})}=\{\{p,r\},\{p,s\},\{q,r\},\{q,s\}\}\uparrow$, but this lower bound becomes ``nulified''
since e.g.\ $\upclosure{{\cal IC}_{\cal P}(\{q\},\{q,r\})}$ contains $\upclosure{\{p\}}$.)
\end{itemize}
The Kripke-Kleene fixpoint that is reached is represented by the convex set \[\{\{p\},\{q\},\{p,r\},\{p,s\},\{q,r\},\{q,s\}\}.\] Intuitively, the meaning of this Kripke-Kleene state is that
every two-valued (stable) model of this program (if they exist), are in this convex set. This is indeed the case, as the stable models of this program are $\{p,r\}$, $\{p,s\}$ and $\{q\}$.
This example thus illustrates how the Kripke-Kleene state is an approximation of the semantics of disjunctive logic programs. This has as a benefit it is guaranteed to uniquely exist
and be constructively computed.
\end{example}
To summarize the results in this section, we have shown the following:
There are two ways to generalize the Kripke-Kleene semantics from deterministic AFT to a non-deterministic setting: one can keep the type the same, resulting in
\emph{Kripke-Kleene interpretations\/} or simply fixpoints of an ndao. We have shown that such fixpoints of ${\cal IC}_{\cal P}$ correspond to weakly supported models.
Uniqueness and existence are not guaranteed. This is solved by the alternative generalization of Kripke-Kleene semantics from deterministic AFT, by
\emph{Kripke-Kleene state\/}, which is a set of interpretations instead of a single interpretation. Existence, uniqueness, and consistency for exact ndso's are
guaranteed for these states, and, moreover, for deterministic operators the two Kripke-Kleene fixpoints coincide.
\section{Stable Semantics}
\label{sec:stable:semantics}
In this section, the stable semantics from deterministic AFT is generalized to the non-deterministic setting. In Section~\ref{subsec:stable:interpretation:sem},
we first introduce and study the stable operator and the corresponding stable interpretation semantics. Then, in Section~\ref{subsec:well-foundedstate} we study the
well-founded state semantics. In Section~\ref{sec:well-founded:alcantara}, we show the usefulness of the well-founded state semantics by relating it to
the well-founded semantics with disjunction~\cite{alcantara2005well} for disjunctive logic programming.
\subsection{Stable Interpretation Semantics}
\label{subsec:stable:interpretation:sem}
In deterministic AFT, the idea behind the stable operator is to find fixpoints that are minimal w.r.t.\ the truth order by constructing a new lower bound and upper bound on the basis
of the current upper respectively lower bound. In more detail, given the current upper bound $y$, we look for the $\leq$-least fixpoint of ${\cal O}(.,y)$ (which is guaranteed to exist for
a deterministic approximation fixpoint operator ${\cal O}$ and coincides with the greatest lower bound of fixpoints of ${\cal O}(.,y)$). Thus, informally ,we look for the smallest lower bound
s.t.\ the operator ${\cal O}$ lets us derive nothing more and nothing less when assuming $y$ as an upper bound.
Instead of generating a single lower and a single upper bound, an ndao generates a set of lower bounds $\{x_1,x_2,\ldots\}$ and a set of upper bounds $\{y_1,y_2,\ldots\}$ on the basis of
a lower and upper bound $(x,y)$. We can again look for a (not necessarily unique) smallest lower bound that an ndao allows us to derive in view of a given upper bound $y$ by looking for
$\leq$-minimal fixpoints of ${\cal O}(.,y)$. We will see below that only under certain assumptions on the ndao such a fixpoint is guaranteed to exist. Furthermore, other properties of the
stable operator and fixpoints, such as $\preceq^A_i$-montonicity, the existence of stable fixpoints and the $\leq_t$-minimality of stable fixpoints, do not generalize or only generalize under
certain assumptions from the deterministic setting. Nevertheless, the fixpoint and state semantics based on this construction are useful in general, as they can e.g.\ characterize the stable semantics
for disjunctive logic programs and the \emph{well-founded semantics with disjunction} by Alc{\^a}ntara, Dam{\'a}sio and Pereira~\cite{alcantara2005well}, and for positive programs it is the set of
minimal models (Proposition~\ref{prop:positive:programs:state}.
This section is organized as follows. We first define stable non-deterministic operators. Then, we study their properties, mainly by looking at how properties from the deterministic
setting can be generalized. We first show that non-deterministic stable operators and their fixpoints faithfully generalize the corresponding deterministic notions
(see Proposition~\ref{prop:stble:coincide:deterministic} and Corollary~\ref{corol:stle:fixpoints:coincide:deterministic}). Next, we study conditions under which the stable operator is
well-defined (culminating in Propositions~\ref{proposition:downward:closed:then:fp}). Thereafter, we show that stable operators are not guaranteed to be $\preceq^A_i$-monotonic
(Example~\ref{ex:stable:not:exist}), and that stable fixpoints are not guaranteed to exist (Example~\ref{ex:stable:not:exist}). Finally, we shows that, under certain
conditions, stable fixpoints are $\leq_t$-minimal fixpoints of an ndao (Proposition~\ref{prop:stable:is:minimal:fp}). This general study of stable operators and their fixpoints is followed by
an illustration of their usefulness, where it is shown that (partial) stable interpretations of disjunctive logic programs are stable fixpoints of ${\cal IC}_{\cal P}$
(Proposition~\ref{prop:stable:fixpoints:represent:stable:models}).
\begin{definition}
\label{def:stable:op}
Let ${\cal O}:{\cal L}^2\rightarrow\wp({\cal L})\times \wp({\cal L})$ be an ndao. We define:
\begin{itemize}
\item The \emph{complete lower stable operator\/}: (for any $y\in {\cal L}$)
\[C({\cal O}_l)(y) \ = \ \{x \in {\cal L}\mid x\in {\cal O}_l(x,y) \mbox{ and }\lnot \exists x'< x: x'\in {\cal O}_l(x',y)\}. \]
\item The \emph{complete upper stable operator\/}: (for any $x\in {\cal L}$)
\[C({\cal O}_u)(x) \ = \ \{y \in {\cal L}\mid y\in {\cal O}_u(x,y) \mbox{ and }\lnot \exists y'<y: y' \in {\cal O}_u(x,y')\}. \]
\item The \emph{stable operator\/}: $S({\cal O})(x,y)=C({\cal O}_l)(y)\times C({\cal O}_u)(x)$
\item A \emph{stable fixpoint\/} of ${\cal O}$ is any $(x,y)\in{\cal L}^2$ such that $(x,y)\in S({\cal O})(x,y)$.\footnote{Notice that we slightly abuse notation and write $(x,y)\in S({\cal O})(x,y)$
to abbreviate $x\in (S({\cal O})(x,y))_1$ and $y\in ( S({\cal O})(x,y))_2$, i.e.\ $x$ is a lower bound generated by $ S({\cal O})(x,y)$ and $y$ is an upper bound generated by $ S({\cal O})(x,y)$.}
\end{itemize}
\end{definition}
\begin{example}
\label{ex:IC-stable:operator}
Consider the dlp ${\cal P}=\{p\lor q\leftarrow\}$ from Example~\ref{examp:IC-deterministic-case}. It holds that for any $x,y\subseteq \{p,q\}$, ${\cal IC}_{\cal P}^l(x,y)=\{\{p\},\{q\},\{p,q\}\}$
and thus $C({\cal IC}^l_{\cal P}(y))=\{\{p\},\{q\}\}$. It thus follows that $(\{p\},\{p\})$ and $(\{q\},\{q\})$ are the stable fixpoints of ${\cal IC}_{\cal P}$.
\end{example}
The complete operator based on ${\cal IC}_{\cal P}$ produces the minimal models of the reducts w.r.t.\ the input. Before showing this, we first recall that the \emph{two-valued models\/}
of a positive program ${\cal P}$ are the sets $x\subseteq {\cal A}_{\cal P}$ s.t.\ for every $\bigvee\Delta\leftarrow \phi \in {\cal P}$, $(x,x)(\phi)={\sf T}$ implies $x\cap \Delta\neq\emptyset$
(Footnote~\ref{footnote:2-val mod}). In wht follows, we denote the set of two-valued models ${\cal P}$ by $mod_2({\cal P})$.
\begin{proposition}
\label{lemma:stable:ic:is:reduct}
Consider a dlp ${\cal P}$ and some $y\subseteq {\cal A}_{\cal P}$. Then $C({\cal IC}_{\cal P})(y)=\min_\subseteq(mod_2(\frac{{\cal P}}{y}))$.
\end{proposition}
\begin{proof}
We first show that $x\in {\cal IC}^l_{\cal P}(x,y)$ implies $x\in mod_2(\frac{{\cal P}}{y})$. Indeed, suppose that $x\in {\cal IC}^l_{\cal P}(x,y)$ and consider some
$\bigvee\Delta\leftarrow \bigwedge_{i=1}^n\alpha_i \land \bigwedge_{j=1}^m \lnot \beta_j$. If $\beta_j\in y$ for some $j=1,\ldots,m$, then $(x,y)(\lnot \beta_j)\in \{{\sf U},{\sf F}\}$
and thus we can ignore this rule.
Suppose then that $\beta_j\not\in y$ for $j=1,\ldots,m$. Suppose now that $(x,y)(\alpha_i)\in \{{\sf T},{\sf C}\}$ for $i=1,\ldots,n$, i.e.,
$\alpha_i\in x$ for $i=1,\ldots,n$. Then $\Delta\in \mathcal{HD}^l_{\cal P}(x,y)$ and thus, since $x\in {\cal IC}^l_{\cal P}(x,y)$, $x\cap \Delta\neq\emptyset$.
We now show that $x\in mod_2(\frac{{\cal P}}{y})$ implies that $x\in {\cal IC}^l_{\cal P}(x,y)$. Indeed, consider some rule of the form
$\bigvee\Delta\leftarrow \bigwedge_{i=1}^n\alpha_i \in \frac{{\cal P}}{y}$, i.e.\ there is some
$\bigvee\Delta\leftarrow \bigwedge_{i=1}^n\alpha_i \land \bigwedge_{j=1}^m \lnot \beta_j\in {\cal P}$ s.t.\ $\beta_j\not\in y$ for $j=1,\ldots,m$.
If $\alpha_i\not\in x$ for some $i=1,\ldots,n$ then we can safely ignore the rule. Suppose thus that $\alpha_i\in x$ for some $i=1,\ldots,n$.
Then $(x,y)(\alpha_i)\in \{{\sf T},{\sf C}\}$ for $i=1,\ldots,n$ and $(x,y)(\beta_j)\in \{{\sf T},{\sf C}\}$
for $j=1,\ldots,m$ and thus, as $x\in mod_2(\frac{{\cal P}}{y})$, $x\cap \Delta \neq\emptyset$. Thus, we have shown that for every $\Delta\in \mathcal{HD}^l_{\cal P}(x,y)$,
$\Delta\cap x\neq\emptyset$. Thus, $x\in {\cal IC}^l_{\cal P}(x,y)$.
We now show that $x\in \lfp({\cal IC}^l_{\cal P}(.,y))$ implies $x\in \min_\subseteq(mod_2(\frac{{\cal P}}{y}))$. Indeed, suppose $x\in \lfp({\cal IC}^l_{\cal P}(.,y))$.
Since this means that $x\in {\cal IC}^l_{\cal P}(x,y)$, with the first item, $x\in mod_2(\frac{{\cal P}}{y})$. Suppose towards a contradiction there is some $x'\subset x$ s.t.\
$x'\in mod_2(\frac{{\cal P}}{y})$. Then with the second item, $x'\in {\cal IC}^l_{\cal P}(x',y)$, contradicting $x\in \lfp({\cal IC}^l_{\cal P}(.,y))$.
The proof that $x\in \min_\subseteq(mod_2(\frac{{\cal P}}{y}))$ implies $x\in \lfp({\cal IC}^l_{\cal P}(.,y))$ is analogous.
\end{proof}
\begin{remark}
Notice that we did \emph{not} define the complete stable operator as the glb of fixpoints of ${\cal O}_l(.,x)$. Indeed, this leads to several problems. First, the glb of fixpoints of
${\cal O}_l(\cdot,x)$ might itself not be a fixpoint of ${\cal O}_l(.,x)$ (since we cannot apply Tarski-Knaster fixpoint theorem to the operator ${\cal O}_l(.,x):{\cal L}\rightarrow \wp({\cal L})$).
Secondly, and more importantly, taking the glb might lead to a loss of information. Consider e.g.\ the program $\{p\lor q\leftarrow\}$. Then ${\cal IC}_{\cal P}(.,x)$ has three fixpoints
(for any $x\subseteq \{p,q\}$), namely $\{p\}$, $\{q\}$ and $\{p,q\}$. If we take the glb, however, we obtain $\emptyset$. This would be counter-intuitive, since we clearly should be
more interested in the more informative $\{p\}$ and $\{q\}$, which represent two possible choices to be made in view of $p\lor q\leftarrow$.
\end{remark}
\begin{remark}
\label{remark:complete:might:not:exist}
Notice that since ${\cal O}(.,x)$ maps from ${\cal L}$ to $ \wp({\cal L})$, i.e., it is not a function or a deterministic operator,
we cannot use Tarski-Knaster fixpoint theorem to guarantee the existence of fixpoint of ${\cal O}(.,x)$, i.e., $C({\cal O})$ is not guaranteed to be non-empty.
Indeed, as a case in point, consider the following example:
\begin{example}
\label{ex:infinite:complete}
Consider the lattice $L=\langle\mathbb{Z}\cup\{\infty,-\infty\},\leq\rangle$ where $\leq$ is defined as usual. Consider the operator ${\cal O}_l(x,y)$ defined by ${\cal O}_l(x,y)=\{x\}$ for
any $x,y\in \mathbb{Z}$, and ${\cal O}_l(x,y)=\mathbb{Z}$ for any $x\in \{\infty,-\infty\}$ and any $y\in \mathbb{Z}$.\footnote{Notice that for this example, the value of ${\cal O}_l(x,y)$
for $y\in \{\infty,-\infty\}$ is not significant.} It can be verified that this operator is $\preceq^S_L$-monotonic. Furthermore, for any $y\in\mathbb{Z}$, every $x\in \mathbb{Z}$ is a fixed point
of ${\cal O}_l(.,y)$ (as $\{x\}={\cal O}_l(x,y)$). Since $\mathbb{Z}$ has no $\leq$-minimal element, $C({\cal O})(y)=\emptyset$ for every $y\in \mathbb{Z}$.
\end{example}
\end{remark}
In what follows (see Definition \ref{def:downwards:closed}), we will delineate a condition that guarantees that the complete lower and upper stable operator is non-empty.
Next, we show that in {\em finite\/} bilattices (in which greatest lower bounds coincide with the minimum),
the definitions of complete stable operators coincide with those for deterministic AFT:
\begin{proposition}
\label{prop:stble:coincide:deterministic}
Let ${\cal O}:{\cal L}^2\rightarrow \wp({\cal L})\times\wp({\cal L})$ be a ndao over a finite, complete lattice ${\cal L}$, where ${\cal O}(x,y)$ is a pair of singleton
sets for every $x,y\in{\cal L}$. Let ${\cal O}^{\sf AFT}$ be the deterministic approximation operator defined by ${\cal O}^{\sf AFT}(x,y)=(w,z)$ where ${\cal O}(x,y)=(\{w\},\{z\})$.\footnote{Recall also
Proposition~\ref{prop:deterministic:aft}.} Then $C({\cal O}_l)(y)=\{ C({\cal O}^{\sf AFT}_l)(y)\}$, and $C({\cal O}_u)(x)=\{ C({\cal O}^{\sf AFT}_u)(x)\}$ for every $x,y\in{\cal L}$.\footnote
{Notice that since ${\cal O}^{\sf AFT}$ is a deterministic approximation operator, $C({\cal O}^{\sf AFT}_l)(y)$ and $C({\cal O}^{\sf AFT}_u)(y)$ are taken as in Definition~\ref{def:stable-op}.}
\end{proposition}
\begin{proof}
By Proposition \ref{prop:deterministic:aft} ${\cal O}^{\sf AFT}$ is a deterministic approximation operator.
The equalities in the proposition are immediate since for finite lattices, $\{x\in {\cal L}\mid x\in {\cal O}_l(x,y) \mbox{ and }\lnot \exists x'<y: x'\in {\cal O}_l(x',y)\} =
glb_{\leq}\{ x\in {\cal L}\mid x\in {\cal O}_l(x,y)\}$.
\end{proof}
\begin{remark}
For approximation operators over infinite bilattices, the coincidence in Proposition~\ref {prop:stble:coincide:deterministic} cannot be guaranteed.
The reason is that the minimum taken in the non-deterministic complete operators $C({\cal O}^u)$ (and $C({\cal O}^l)$) might not coincide with the
glb taken in the deterministic complete operators $C({\cal O}^{\sf AFT}_l)(y)$ and $C({\cal O}^{\sf AFT}_u)(y)$. A case in point is the following example:
\begin{example}
Consider a lattice $L=\langle \{\bot,\top\}\cup\{x_i\mid i\in\mathbb{N}\},\leq\rangle$ where $\bot< x_i < \top$ for every $i\in\mathbb{N}$.
Consider the operator ${\cal O}$ defined as follows:
\begin{itemize}
\item ${\cal O}_l(x_i,y)={\cal O}_u(y,x_i)=x_i$ for any $y\in \{\bot,\top\}\cup\{x_i\mid i\in\mathbb{N}\}$ and $i\in\mathbb{N}$,
\item ${\cal O}_l(\bot,x_i)={\cal O}_u(x_i,\bot) = x_i$ for any $i\in\mathbb{N}$,
\item ${\cal O}_l(x,\top)={\cal O}_u(\top,x)=\top$ for any $x\in \{\top\}\cup\{x_i\mid i\in\mathbb{N}\}$, and
\item ${\cal O}_l(\bot,\top)=\{\bot\}$.
\end{itemize}
Then $C({\cal O}_l)(x_i)=\{x_i\mid i \in\mathbb{N}\}$, whereas $C({\cal O}^{\sf AFT}_l)(x_i)=glb_{\leq}\{x_i\mid i \in\mathbb{N}\}=\bot$ for any $i\in\mathbb{N}$.
\end{example}
\end{remark}
Thus, in view of Proposition~\ref{prop:stble:coincide:deterministic}, for finite lattices the notion of stable fixpoint is not changed in the non-deterministic case:
\begin{corollary}
\label{corol:stle:fixpoints:coincide:deterministic}
Let ${\cal O}:{\cal L}^2\rightarrow \wp({\cal L})^2$ be a ndao over a finite, complete lattice ${\cal L}$, where ${\cal O}(x,y)$ is a pair of singleton
sets for every $x,y\in{\cal L}$. Let ${\cal O}^{\sf AFT}$ be defined by ${\cal O}^{\sf AFT}(x,y)=(w,z)$ where ${\cal O}(x,y)=(\{w\},\{z\})$. Then $(x,y)$ is a stable fixpoint of ${\cal O}$
according to Definition~\ref{def:stable:op} iff $(x,y)$ is a stable fixpoint of ${\cal O}^{\sf AFT}$ according to Definition~\ref{def:stable-op}.
\end{corollary}
The next property we study is the well-definedness of the complete (and thus stable) operator, which is not guaranteed in view of Remark~\ref{remark:complete:might:not:exist}.
Next, we show two useful lemmas (the first one is based on~\cite{pelov2004semantics}), which show that minimal
pre-fixpoints are also minimal fixpoints and vice versa. For this, we first generalize the notion of a pre-fixpoint from the deterministic setting to non-deterministic operators.
\begin{definition}
We say that $w\in {\cal L}$ is a {\em pre-fixpoint\/} of the non-deterministic operator $O$ on ${\cal L}$, if $O(w)\preceq^S_L w$.
\end{definition}
\begin{lemma}
\label{lemma:minimalpre-fix:is:minima:fix}
Let $O:{\cal L}\rightarrow \wp({\cal L})$ be a $\preceq^S_L$-monotonic non-deterministic operator.
Then if $w$ is a $\leq$-minimal pre-fixpoint of $O$, it is a $\leq$-minimal fixpoint of $O$.\footnote{Notice that for any ndao ${\cal O}$, ${\cal O}_l(.,x)$ is an operator of the type
${\cal O}:{\cal L}\rightarrow \wp({\cal L})$ and thus a non-deterministic operator, which we denote by $O$.}
\end{lemma}
\begin{proof}
Suppose that $w$ is a $\leq$-minimal pre-fixpoint of $O$, i.e., $O(w)\preceq^S_L w$. This means that there is some $z\in O(w)$ s.t.\ $z\leq w$.
Since $O$ is $\preceq^S_L$-monotonic, $O(z)\preceq^S_L O(w)$. Since $z\in O(w)$, $O(z)\preceq^S_L z$, i.e.\ $z$ is a pre-fixpoint of $O$. Since $w$ is a $\leq$-minimal pre-fixpoint
and $z\leq w$, $z=w$. Minimality is immediate since fixpoints are in particular pre-fixpoints.
\end{proof}
\begin{lemma}
\label{minimalfp:then:minimal:prefp}
Let $O:{\cal L}\rightarrow \wp({\cal L})$ be a $\preceq^S_L$-monotonic non-deterministic operator. Then if $w$ is a $\leq$-minimal fixpoint of $O$, it is a $\leq$-minimal pre-fixpoint of $O$.
\end{lemma}
\begin{proof}
Suppose that $w$ is a $\leq$-minimal fixpoint of $O$. Then $w\in O(w)$ and so $O(w)\preceq^S_L w$. Thus, $w$ is a pre-fixpoint. Suppose now towards a contradiction
that for some $w'<w$, $O(w')\preceq^S_L w'$. Without loss of generality, we may assume that $w'$ is a minimal pre-fixpoint. But then, by Lemma~\ref{lemma:minimalpre-fix:is:minima:fix},
it is a minimal fixpoint of $O$, a contradiction.
\end{proof}
Uniqueness of this $\leq$-minimal fixpoint cannot be guaranteed (as can be seen in e.g.\ Example~\ref{sec:application:to:dlp:ex}). This is a crucial difference with deterministic operators.
Thus, to summarize, non-determinism forces us to take $\leq$-minimal fixpoints instead of the greatest lower bound. This choice, on its turn, means that existence is not guaranteed on infinite lattices.
Therefore, we now turn to conditions that ensure the existence of $\leq$-minimal fixpoint of non-deterministic operators over infinite lattices. As we shall see (Proposition~\ref{proposition:downward:closed:then:fp} below), the next property (inspired by~\cite{pelov2004semantics}) assures existence.
\begin{definition}%
\label{def:downwards:closed}
A non-deterministic operator $O:{\cal L}\rightarrow \wp({\cal L})$ is \emph{downward closed} if for every sequence $X=\{x_\epsilon\}_{\epsilon<\alpha}$ of elements in ${\cal L}$ such that:
\begin{enumerate}
\item for every $\epsilon<\alpha$, $O(x_\epsilon)\preceq^S_L \{x_\epsilon\}$, and
\item for every $\epsilon <\epsilon'<\alpha$, $x_{\epsilon'}< x_\epsilon$,
\end{enumerate}
it holds that $O(glb(X))\preceq^S_L glb(X)$.
\end{definition}
Definition~\ref{def:downwards:closed} is a generalization of a similar definition in~\cite{pelov2004semantics}. Its says that an operator is downward closed if the greatest lower bound of every chain
of pre-fixpoints is itself a pre-fixpoint. As we will see in Proposition~\ref{prop:stable:is:minimal:fp}, this ensures that $O$ admits a fixpoint.
As an example of an operator that is downward closed, we consider ${\cal IC}^l_{\cal P}(\cdot,y)$
(recall Definition~\ref{def:IC_P-ndo})\footnote{This is inspired by the proof of a similar result in~\cite{pelov2004semantics}.}
\begin{proposition}
\label{proposition:IC^l_P-is-downward:closed}
For any dlp ${\cal P}$ and any $y\subseteq {\cal A}_{\cal P}$, ${\cal IC}_{\cal P}(\cdot,y)$ is downward closed.
\end{proposition}
\begin{proof}
Let $\{x_\epsilon\}_{\epsilon<\alpha}$ be a descending chain of sets of atoms of post-fixpoints of ${\cal IC}^{l}_{\cal P}(\cdot,y)$ for some $y\subseteq {\cal A}_{\cal P}$,
and let $x=\bigcap \{x_\epsilon\}_{\epsilon<\alpha}$. We show that ${\cal IC}_{\cal P}(x,y)\preceq^S_L \{x\}$. If the chain is finite, this is trivial.
Suppose therefore that $\{x_\epsilon\}_{\epsilon<\alpha}$ is infinite.
We first show the following lemma:
\begin{lemma}
$(x,y)(\phi)\in \{{\sf T},{\sf C}\}$ implies $(x_\epsilon,y)(\phi)\in \{{\sf T},{\sf C}\}$ for every $\epsilon<\alpha$, and $(x_\epsilon,y)(\phi)\in \{{\sf F},{\sf C}\}$ implies
$(x_\epsilon,y)(\phi)\in \{{\sf F},{\sf C}\}$ for every $\epsilon<\alpha$.
\end{lemma}
\begin{proof}
By induction on the structure of $\phi$. Base case: suppose that $\phi=p \in {\cal A}_{\cal P}$. If $(x,y)(p)\in \{{\sf T},{\sf C}\}$ then $p \in x$ and so $p \in x_\alpha$ for every $\epsilon <\alpha$, thus
$(x_\epsilon,y)(p)\in \{{\sf T},{\sf C}\}$ as well. If $(x,y)(p)\in \{{\sf F},{\sf C}\}$ then $p \not\in y$, and so $(x_\epsilon,y)(p)\in \{{\sf F},{\sf C}\}$ as well. Inductive case: the cases where
$\phi=p_1 \land p_2$ and $\phi=p_1\lor p_2$ are straightforward. Suppose now that $\phi=\lnot p$ and $(x,y)(\phi)\in \{{\sf T},{\sf C}\}$. Thus, $(x,y)(p)\in \{{\sf F},{\sf C}\}$ and by the
inductive hypothesis, $(x_\epsilon,y)(p)\in \{{\sf F},{\sf C}\}$ for every $\epsilon<\alpha$, which implies that $(x_\epsilon,y)(\lnot p)\in \{{\sf T},{\sf C}\}$ for every $\epsilon<\alpha$. The proof of the other case is similar.
\end{proof}
Back to the proof of the proposition. We first show that $x\cap \Delta\neq\emptyset$ for every $\bigvee\Delta\leftarrow\phi\in {\cal P}$ s.t.\ $(x,y)(\phi)\in \{{\sf T},{\sf C}\}$.
Indeed, consider some $\bigvee\Delta\leftarrow \phi\in {\cal P}$ and $(x,y)(\phi)\in \{{\sf T},{\sf C}\}$. By the lemma above, $(x_\epsilon,y)(\phi)\in \{{\sf T},{\sf C}\}$ for every
$\epsilon<\alpha$. Thus, for every $\epsilon<\alpha$, $x_\epsilon \cap\Delta\neq\emptyset$.
Since $\{x_\epsilon\}_{\epsilon<\alpha}$ is an infinite descending chain and $\Delta$ is finite,
there is a $\delta\in \Delta$ s.t.\ $\delta$ is part of an infinite number of sets in $\{x_\epsilon\}_{\epsilon<\alpha}$.
Since $\{x_\epsilon\}_{\epsilon<\alpha}$ is a $\subseteq$-descending chain, $\delta\in x_\epsilon$ for every $\epsilon<\alpha$,
and thus $\delta\in x$.
We can now show that ${\cal IC}_{\cal P}(x,y)\preceq^S_L \{x\}$. Indeed, since $x\cap \Delta\neq\emptyset$ for every $\bigvee\Delta\leftarrow\phi\in {\cal P}$,
$z=x\cap \bigcup{\cal HD}_{\cal P}(x,y)\in {\cal IC}_{\cal P}(x,y)$ and thus we have found our interpretation $z\in {\cal IC}_{\cal P}(x,y)$ s.t.\ $z\subseteq x$.
\end{proof}
Next we show that downward closure is indeed a sufficient condition for assuring the existence of a fixpoint:
\begin{proposition}
\label{proposition:downward:closed:then:fp}
Let ${\cal L}=\langle L,\leq\rangle$ be a lattice and let a $O:{\cal L}\rightarrow \wp({\cal L})$ be a downward closed, $\preceq^S_L$-monotonic non-deterministic operator.
Then $O$ admits a $\leq$-minimal fixpoint.
\end{proposition}
\begin{proof}
By Lemma~\ref{lemma:minimalpre-fix:is:minima:fix} it is sufficient to show that $O$ admits a $\leq$-minimal pre-fixpoint.
The set of pre-fixpoints of $O$ is clearly a partially ordered set. With downwards closedness, every chain of pre-fixpoints has a lower bound (which is also a pre-fixpoint).
Thus, by Zorn's lemma, the set of pre-fixpoints has a minimum.
\end{proof}
We obtain the following corollary for the approximation operator ${\cal IC}^l_{\cal P}$:
\begin{corollary}
For every dlp ${\cal P}$, ${\cal IC}^l_{\cal P}(\cdot,y)$ has a $\leq$-minimal fixpoint.
\end{corollary}
\begin{proof}
By Propositions~\ref{proposition:IC^l_P-is-downward:closed} and~\ref{proposition:downward:closed:then:fp}, and since ${\cal IC}^l_{\cal P}(\cdot,y)$ is $\preceq^S_L$-monotonic.
\end{proof}
{As we have now established conditions under which the stable operator is well-defined, we turn to the property of $\preceq^A_i$-monotonicity of the stable operator.
We notice that in general, $S({\cal O})$ is {\em not\/} a $\preceq^A_i$-monotonic operator:
\begin{example}
Consider the program ${\cal P}=\{ p\lor q\leftarrow; \quad p\leftarrow \lnot r\}$. We calculate the applications of the stable operators as follows:
\begin{itemize}
\item Since $(\{p\},\{r\})(\lnot r)=(\{q\},\{r\})(\lnot r)={\sf F}$, it holds that $C({\cal IC}_{\cal P}^l)(\{r\})=\{\{p\},\{q\}\}$ for any $x\subseteq {\cal A}_{\cal P}\setminus\{r\}$.
\item Since $(\{r\},x)(\lnot r)={\sf F}$ for any $x\subseteq {\cal A}_{\cal P}\setminus \{r\}$, it holds that ${\cal IC}^u_{\cal P}(x,\{r\})={\cal IC}^l_{\cal P}(\{r\},x)=\{\{p\},\{q\}\}$
and thus $C({\cal IC}_{\cal P}^u(\{r\})=\{\{p\},\{q\}\}$.
\item Since $(\emptyset,x)(\lnot r)={\sf T}$ for any for any $x\subseteq {\cal A}_{\cal P}\setminus \{r\}$, it holds that $C({\cal IC}_{\cal P}^u)(\{r\})=\{\{p\}\}$.
\end{itemize}
Altogether, this means that $S({\cal IC}_{\cal P})(\emptyset,\{r\}))=\{\{p\},\{q\}\}\times \{\{p\}\}$ whereas $S({\cal IC}_{\cal P})(\{r\},\{r\})=\{\{p\},\{q\}\}\times\{\{p\},\{q\}\}$.
However, $\{\{p\},\{q\}\}\not\preceq^H_L\{\{p\}\}$, or, equivalently, there is no $(x,y)\in S({\cal IC}_{\cal P})(\emptyset,\{r\}))$ s.t.\
$(x,y)\leq_i (\{p\},\{q\})\in S({\cal IC}_{\cal P})(\emptyset,\emptyset)$. Thus, although $(\emptyset,\{r\}) \leq_i (\{r\},\{r\})$, it does {\em not\/} hold that
$S({\cal IC}_{\cal P})(\emptyset,\{r\})) \preceq^A_i S({\cal IC}_{\cal P})(\{r\},\{r\})$.
\end{example}
Recall that (in contrast to the last example), by Proposition~\ref{lemma:O':is:alcantara:monotonic},
the state version of the stable operator {\em is\/} still $\preceq^A_i$-monotonic. Thus, we can still construct a state by iteratively applying the state version of the stable operator.
We will detail this construction in Section~\ref{subsec:well-foundedstate} and show that this state, which we call the \emph{well-founded state\/}, exists, is unique, is more precise
than the Kripke-Kleene state, and coincides with the well-founded fixpoint for deterministic operators.
\medskip
A third property we investigate is the existence of stable fixpoints\footnote{Notice that this is not the same as the existence of $\leq$-minimal fixpoints of ${\cal O}^l(.,y)$: this establishes merely that $S({\cal O})$
is well-defined, but does not guarantee that stable fixpoints exist as we will see now.}. Even when the complete stable operator is non-empty for every element of a lattice, stable fixpoints may not exist:
\begin{example}
\label{ex:stable:not:exist}
Consider the following dlp: ${\cal P}=\{p\lor q\lor r \leftarrow; \quad p\leftarrow \lnot q; \quad r\leftarrow \lnot p; \quad q\leftarrow \lnot r\}$.
It can be checked that there are no $x,y\subseteq \{p,q,r\}$ s.t.\ $(x,y)\in S({\cal IC}_{\cal P})(x,y)$. To make this clearer, we calculate some of the outcomes of the complete stable operator $C({\cal IC}^l_{\cal P})$:
\begin{itemize}
\item $C({\cal IC}^l_{\cal P})(\emptyset)=C({\cal IC}^u_{\cal P})(\emptyset)=\{\{p,q,r\}\}$.
\item $C({\cal IC}^l_{\cal P})(\{p\})=C({\cal IC}^u_{\cal P})(\{p\})=\{\{p,q\}\}$.
\item $C({\cal IC}^l_{\cal P})(\{p,q\})=C({\cal IC}^u_{\cal P})(\{p\})=\{\{q\}\}$.
\item $C({\cal IC}^l_{\cal P})(\{p,q,r\})=C({\cal IC}^u_{\cal P})(\{p\})=\{\{p\},\{q\},\{r\}\}$.
\end{itemize}
Notice that $C({\cal IC}^u_{\cal P}(x))=C({\cal IC}^l_{\cal P}(x))$ for any $x\subseteq {\cal A}_{\cal P}$ as ${\cal IC}_{\cal P}$ is symmetric.
Other cases can be easily derived in view of symmetry of ${\cal IC}_{\cal P}^l$ w.r.t.\ $p$, $q$ and $r$. As there is no $x,y\subseteq{\cal A}_{\cal P}$ for which
$x\in C({\cal IC}^l_{\cal P})(y)$ and $y\in C({\cal IC}^u_{\cal P})(x)=C({\cal IC}^l_{\cal P})(x)$, we conclude that no stable interpretation exists, which is in accordance
with the stable model semantics for disjunctive logic programming, where a well-founded or more generally three-valued stable model does not exist in this case.
\end{example}
We now move to the last property of stable fixpoints considered here: their $\leq_t$-minimality. To show that stable fixpoints are $\leq_t$-minimal, we will have to assume that the upper bound operator
${\cal O}_u$ is $\preceq^S_L$-monotonic. As the following example shows, if this condition is not satisfied, $\leq_t$-minimality of stable fixpoints is not guaranteed:
\begin{example}
\label{ex:stable:not:t:minimal}
Consider a lattice ${\cal L}=\langle \{\bot,x,x',y,y',\top\},\leq\rangle$ with $\leq$ as follows:
\[\xymatrix@R-10pt@C-10pt{
&\top\\
x\ar[ru]&&y \ar[lu]\\
x'\ar[u] &&y'\ar[u]
\\
&\bot\ar[ur]\ar[lu]}
\]
Consider an ndao ${\cal O}$ such that the following hold:
\def\arraystretch{1,3}\tabcolsep=10pt
\begin{center}
\begin{tabular}{l|l}
$(w,z)$& ${\cal O}(w,z)$ \\ \hline
$(x,y)$ & $\{x\}\times\{y\}$ \\
$(x',y)$ & $\{\bot,x\}\times\{y\}$ \\
$(x,y')$ & $\{x\}\times\{y\}$\\
$(x',y')$ & $\{x'\}\times\{y,y'\}$\\
$(\bot,y)$& $\{x'\}\times \{y,y'\}$\\
$(x,\bot)$& $\{x,x'\}\times \{y'\}$
\end{tabular}
\end{center}
and such that for any $(w,z)$ not occuring in the table, ${\cal O}(w,z)=\{w\}\times \{z\}$.
It can be verified that this operator is $\preceq^A_i$-monotonic.
Also, $(x,y)\in S({\cal O})(x,y)$, since:
\begin{itemize}
\item $x\in {\cal O}_l(x,y)=\{x\}$, (and $x'\not\in {\cal O}_l(x',y)$, i.e., $x$ is a $\leq$-minimal fixpoint of ${\cal O}_l(.,y)$), and
\item $y\in {\cal O}_u(x,y)=\{y\}$ (and $y'\not\in {\cal O}_u(x,y')$, i.e., $y$ is a $\leq$-minimal fixpoint of ${\cal O}_u(.,x)$).
\end{itemize}
Furthermore, $(x',y')\in {\cal O}(x',y')$. Finally, since $(x',y')\leq_t (x,y)$, the stable fixpoint $(x,y)$ is not a $\leq_t$ minimal fixpoint.
\end{example}
The next proposition shows that if stable fixpoints of ${\cal O}$ do exist, they must be fixpoints of ${\cal O}$. Furthermore,
if ${\cal O}_l(.,x)$ is downward closed and ${\cal O}_u(.,z)$ is $\preceq^S_L$-anti monotonic, they are $\leq_t$-minimal fixpoints of ${\cal O}$.
\begin{proposition}
\label{prop:stable:is:minimal:fp}
Let $L=\langle {\cal L},\leq\rangle$ be a finite complete lattice and let ${\cal O}:{\cal L}^2 \rightarrow \wp({\cal L})\times\wp({\cal L})$ be an ndao. Then:
\begin{enumerate}
\item A stable fixpoint of ${\cal O}$ is also a fixpoint of ${\cal O}$.
\item If ${\cal O}_l(.,x)$ is downward closed and ${\cal O}_u(.,x)$ is $\preceq^S_L$-anti monotonic for every $x\in L$, then every stable fixpoint of ${\cal O}$ is a $\leq_t$-minimal fixpoint of ${\cal O}$.
\end{enumerate}
\end{proposition}
\begin{proof}
Part~1 of the proposition immediately follows from the definition of stable fixpoint. For Part~2, suppose that $(x,y)\in S({\cal O})$. Then $x\in C({\cal O})(y)$ and $y\in C({\cal O})(x)$,
which implies that $x\in {\cal O}(x,y)$ and $y\in {\cal O}_u(x,y)$. Thus, $(x,y)\in {\cal O}(x,y)$. Consider now some $(x',y')\leq_t (x,y)$ with $(x',y')\in {\cal O}(x',y')$. Since ${\cal O}_u(\cdot,y')$
is $\preceq^S_L$-anti monotonic and $x'\leq x$, we have that ${\cal O}_u(x,y')\leq_t {\cal O}_u(x',y')$, which implies (with $y'\in {\cal O}_u(x',y')$) that ${\cal O}_u(x,y')\preceq^S_L y'$, i.e.\
$x$ is a pre-fixpoint of ${\cal O}_u(\cdot,y')$. By Lemma~\ref{minimalfp:then:minimal:prefp}, $y$ is a minimal pre-fixpoint of ${\cal O}_l(x,\cdot)$. Since $y'\leq y$, necessarily $y'=y$.
In a similar way one shows that $x'=x$ .
\end{proof}
This means in particular that for a symmetric operator ${\cal O}$ on a finite and complete lattice, every stable fixpoint of ${\cal O}$ is a $\leq_t$-minimal fixpoint of ${\cal O}$.
Even though they are not guaranteed to exist, stable fixpoints are useful in knowledge representation.
For example, the stable fixpoints of ${\cal IC}_{\cal P}$ characterize with the (three-valued) stable models of ${\cal P}$:
\begin{theorem}
\label{prop:stable:fixpoints:represent:stable:models}
Consider a normal disjunctive logic program ${\cal P}$ and a consistent interpretation $(x,y)\in \wp({\cal A}_{\cal P}) \times \wp({\cal A}_{\cal P})$.
Then $(x,y)$ is a stable model of ${\cal P}$ iff $(x,y)\in S({\cal IC}_{\cal P})(x,y)$.
\end{theorem}
\begin{proof}
$[\Rightarrow]$ Suppose that $(x,y)$ is a stable model of ${\cal P}$. We show that $x\in C({\cal IC}_{\cal P}^l)(y))$.
(The proof that $y\in C({\cal IC}_{\cal P}^l)(x))$ (thus $y \in C(({\cal IC}_{\cal P}^u)(x))$, since ${\cal IC}_{\cal P}$ is symmetric) is analogous). We first show that
$x\in {\cal IC}^{l}_{\cal P}(x,y)$. Indeed, this immediately follows from the fact that any stable interpretation is weakly supported and that any weakly supported model is a
fixpoint of ${\cal IC}_{\cal P}$ (Theorem~\ref{theo:correspondence:supported}). It remains to show $\subseteq$-minimality of $x$ among fixpoints of ${\cal IC}^l_{\cal P}(.,y)$
and of $y$ among fixpoints of ${\cal IC}^u_{\cal P}(x,.)$. Suppose towards a contradiction that there is some $x'\subset x$ such that\ $x'\in {\cal IC}^{l}_{\cal P}(x',y)$.
We show that $(x',y)\in mod(\frac{\cal P}{(x,y)})$, which contradicts $(x,y)\in \min_{\leq_t}(mod(\frac{\cal P}{(x,y)}))$ (the latter follows from the assumption
that $(x,y)$ is stable). Indeed, let $\bigvee\!\Delta \leftarrow \bigwedge\!\Theta \land \bigwedge_{i=1}^n\lnot\beta_i\in\frac{\cal P}{(x,y)}$. We consider three cases:
\begin{itemize}
\item $(x,y)(\lnot \beta_i)={\sf T}$ for every $1\leq i\leq n$. This means that $\bigvee\!\Delta \leftarrow \bigwedge\!\Theta \land {\sf T} \in \frac{\cal P}{(x,y)}$.
Notice that for any $\alpha\in {\cal A}_{\cal P}$, $(x',y)(\alpha)\leq_t (x,y)(\alpha)$ (since $x'\subseteq x$). Now,
\begin{itemize}
\item If $(x',y)(\bigwedge \Theta)={\sf F}$, $(x',y)(\bigvee\!\Delta \leftarrow \bigwedge\!\Theta \land {\sf T})$ is trivially satisfied.
\item If $(x',y)(\bigwedge \Theta)={\sf U}$, $(x',y)(\bigwedge\!\Theta)\leq_t(x,y)(\bigwedge\!\Theta)\leq_t (x,y)(\bigvee\!\Delta)$ implies
$(x,y)(\bigwedge\!\Theta)\in\{{\sf T},{\sf U}\}$ and thus, since $(x,y)$ is a stable model of $\frac{{\cal P}}{(x,y)}$,
$(x,y)(\bigvee\!\Delta)\in\{{\sf T},{\sf U}\}$, i.e.\ $\Delta\cap y\neq \emptyset$. Thus, $(x',y)(\bigvee\!\Delta)\in \{{\sf T},{\sf U}\}$.
\item If $(x',y)(\bigwedge\!\Theta)={\sf T}$, then $\Delta \in \mathcal{HD}^l_{\cal P}(x',y)$ (since $x'\in {\cal IC}_{\cal P}(x',y)$), and so (since $(x',y)\in {\cal IC}_{\cal P}^{\sf cons}(x',y)$),
$x'\cap \Delta\neq\emptyset$.
\end{itemize}
\item $(x,y)(\lnot \beta_i) \in \{{\sf T},{\sf U}\}$ for every $1 \leq i \leq n$, and $(x,y)(\lnot\beta_i)={\sf U}$ for some $1 \leq i \leq n$.
Then $\bigvee\!\Delta \leftarrow \bigwedge\!\Theta \land {\sf U} \in \frac{\cal P}{(x,y)}$. It can be shown that $(x',y)$ satisfies
$\bigvee\!\Delta \leftarrow \bigwedge\!\Theta \land {\sf U}$ just like the previous case.
\item $(x,y)(\lnot \beta_i)={\sf F}$ for some $1 \leq i \leq n$: trivial.
\end{itemize}
Altogether, we have shown that $(x',y)$ satisfies any $\bigvee\Delta\leftarrow \bigwedge\Theta\land \bigwedge_{i=1}^n\lnot\beta\in\frac{\cal P}{(x,y)}$, contradicting the assumption that
$(x,y)\in \min_{\leq_t}(mod(\frac{\cal P}{(x,y)}))$. We conclude then that $x$ is a $\subseteq$-minimal fixpoint of ${\cal O}_l(.,y)$.
Analogously, it can be shown that $y$ is $\subseteq$-minimal among fixpoints of ${\cal IC}^u_{\cal P}(x,.)$. \medskip
\noindent$[\Leftarrow]$ Suppose now that $(x,y) \in S({\cal IC}_{\cal P})(x,y)$. We first show that $(x,y)$ is a model of $\frac{\cal P}{(x,y)}$. Indeed, by
Proposition~\ref{prop:stable:is:minimal:fp} $(x,y)\in{\cal IC}_{\cal P}(x,y)$, thus by Theorem~\ref{theo:correspondence:supported} $(x,y)$ is a weakly supported model
of ${\cal P}$. Since any model $(x,y)$ of ${\cal P}$ is also a model of $\frac{\cal P}{(x,y)}$, we have that $(x,y)$ is a model of $\frac{\cal P}{(x,y)}$.
For $\leq_t$-minimality, suppose towards a contradiction that there is some $(x',y')<_t(x,y)$ such that $(x',y')\in mod(\frac{\cal P}{(x,y)})$. Since
$(x',y')<_t(x,y)$, either $x'\subsetneq x$ or $y'\subsetneq y$. Suppose first that $x'\subsetneq x$. By Lemma~\ref{prop:decomposition:of:ndao},
$ \mathcal{HD}^l_{\cal P}(x',y) \subseteq \mathcal{HD}^l_{\cal P}(x,y)$, and for a similar reason $\mathcal{HD}^l_{\cal P}(x',y)\subseteq \mathcal{HD}^l_{\cal P}(x',y')$,
thus $\mathcal{HD}^l_{\cal P}(x',y') \subseteq \mathcal{HD}^l_{\cal P}(x,y)$. We have: $ {\cal IC}_{\cal P}(x',y')=\min_{\leq_t}( mod(\frac{{\cal P}}{(x',y')})
\subseteq \min_{\leq_t}( mod(\frac{{\cal P}}{(x,y)})) = {\cal IC}_{\cal P}(x,y)$. Hence $x'\in {\cal IC}_{\cal P}(x,y)$, but this contradicts the fact that
$x$ is a $\leq$-minimal fixpoint of ${\cal IC}_{\cal P}^l(.,y)$ (which follows from the assumption that $(x,y)\in S({\cal IC}_{\cal P})(x,y)$). The proof of the case where
$y'\subsetneq y$ is similar.
\end{proof}
Notice that this also means that two-valued stable model coincide with total stable fixpoints (i.e.\ $x$ is a two-valued stable model iff
$(x,x)\in S({\cal IC}_{\cal P})(x,x)$).
\begin{example}
\label{ex:IC-stable:operator:correspondence}
Consider the dlp ${\cal P}=\{p\lor q\leftarrow\}$ from Example~\ref{examp:IC-deterministic-case} (see also Example \ref{ex:IC-stable:operator}). In view of Theorem~\ref{prop:stable:fixpoints:represent:stable:models}, it is not a coincidence that $(\{p\},\{p\})$ and $(\{q\},\{q\})$ are the stable fixpoints of ${\cal IC}_{\cal P}$ and the stable
interpretations of ${\cal P}$.
\end{example}
\subsection{Well-founded state Semantics}
\label{subsec:well-foundedstate}
The well-founded fixpoint in determinstic AFT is obtained by iteratively applying the stable operator $S({\cal O})$ to the least precise pair $(\bot,\top)$, which results in a fixpoint
that approximates any fixpoint of the operator $O$ approximated by ${\cal O}$ and guaranteed to exist, be unique, and be more precise than the Kripke-Kleene fixpoint.
In this section, we generalize this construction to the non-deterministic setting by defining the \emph{well-founded state}, a convex set that is unique, guaranteed to exist, is more precise
than the Kripke-Kleene state, approximates any fixpoint of the non-deterministic operator $O$ approximated by ${\cal O}$, and obtained by iteratively applying $S({\cal O})$.
Thus, the well-founded state ${\sf WF}({\cal O})$ is obtained, for an approximation operator ${\cal O}$, by first taking the stable operator $S({\cal O})$ on the basis of ${\cal O}$ and then
taking the Kripke-Kleene state ${\sf KK}(S({\cal O}))$ of this operator (i.e., iterating the application the state-version of the operator starting from the least precise element until a fixpoint is reached),
thus resulting in ${\sf WF}({\cal O})={\sf KK}(S({\cal O}))$.
We first show the following useful lemma, which shows that, at least when building up the well-founded state, applications of $S({\cal O})'$ result in at least as precise convex
sets as applications of ${\cal O}$.
\begin{lemma}
\label{lemma:stable:is:more:precise:than:kk}
Let a lattice ${\cal L}=\langle L,\leq\rangle$ and an ndao ${\cal O}$ over ${\cal L}$ be given s.t.\ ${\cal O}_l(.,x)$ is downward closed for every $x\in L$. Then for any ordinal
$\alpha$, $({\cal O}')^\alpha(\bot,\top)\preceq^A_i ((S({\cal O}))')^\alpha(\bot,\top)$.
\end{lemma}
\begin{proof}
We show this by induction on $\alpha$.
For the base case, we show that ${\cal O}(\bot,\top)\preceq^A_i S({\cal O})(\bot,\top)$. Let $S({\cal O})(\bot,\top)=X\times Y$.
Consider some $z\in C({\cal O})(\top)$. I.e.\ $z\in {\cal O}_l(z,\top)$ and for every $w\in {\cal O}(w,\top)$, $w\not <z$. Since $(\bot,\top)\leq_i (z,\top)$, with the $\preceq^A_i$-monotonicity
of ${\cal O}$, ${\cal O}_l(\bot,\top)\preceq^S_L {\cal O}_l(z,\top)$
Since this argument holds for an arbitrary $z\in C({\cal O})(\top)$, we have established ${\cal O}_l(\bot,\top)\preceq^S_L C({\cal O})(\top)$. The proof for $C({\cal O})(\bot)$
(i.e., that $C({\cal O})(\bot)) \preceq^H_L {\cal O}_u(\bot,\top$) is similar.
For the inductive case, consider two ordinals $\alpha$ and $\beta$,
let $\beta$ be the successor ordinal of $\alpha$, and assume that $({\cal O}')^\alpha(\bot,\top)\preceq^A_i ((S({\cal O}))')^\alpha(\bot,\top)$.
Let $((S({\cal O}))')^\alpha(\bot,\top)=X\times Y$ and consider some $y\in Y$. Let $x \in X$. Recall that $x\in C({\cal O})(y)$ means hat $x$ is a
$\leq$-minimal fixpoint of ${\cal O}_l(.,y)$, and thus $x\in {\cal O}_l(x,y)$. Notice that $(\bot,\top)\leq_i (x,y)$ and so ${\cal O}(\bot,\top)\preceq^A_i {\cal O}(x,y)$, which implies
that ${\cal O}_l(\bot,\top)\preceq^S_L {\cal O}_l(x,y)$. This means that ${\cal O}_l(\bot,\top)\preceq^S_L \{x\}$ (since $x\in {\cal O}_l(x,y)$). By the inductive hypothesis,
$\{y\}\preceq^H_L {\cal O}_l^\alpha (\bot,\top)$, which means
(for any ordinal $\gamma$ smaller than $\alpha$), in view of ${\cal O}'$ is $\preceq^A_i$-monotonic and ${\cal O}^\alpha_u(\bot,\top)\preceq^H_L{\cal O}^\gamma_u(\bot,\top)$, that
$\{y\}\preceq^H_L{\cal O}_l^\gamma (\bot,\top)$. Thus, ${\cal O}(\bot,\top)\preceq^A_i (x,y)$. We can now use the same line of reasoning recursively until we reach the ordinal $\alpha$
to obtain $({\cal O}')^\alpha(\bot,\top)\preceq^A_i (x,y)$. Applying ${\cal O}'$ one more time gives us $({\cal O}')^\beta(\bot,\top)\preceq^A_i {\cal O}(x,y)$, which, with $x\in {\cal O}(x,y)$
means $({\cal O}_l')^\beta(\bot,\top)\preceq^S_L \{x\}$, as desired.
The proof that $\{y\} \preceq^H_L ({\cal O}_u')^\beta(\bot,\top)$ for every $y \in Y$ is similar.
For a limit ordinal $\alpha$, we have to show that $lub_{\preceq^A_i}\{ ({\cal O}')^\beta(\bot,\top)\mid \beta<\alpha\}\preceq^A_i lub_{\preceq^A_i}\{ (S({\cal O})')^\beta(\bot,\top)\mid \beta<\alpha\}$ under the assumption that $({\cal O}')^\beta(\bot,\top)\preceq^A_i ((S({\cal O}))')^\beta(\bot,\top)$ for any $\beta<\alpha$. This is immediate, in view of the following considerations:
\begin{enumerate}
\item By Corollary~\ref{fact:lub:and:glb:under:preceq}, $lub_{\preceq^A_i}\{ ({\cal O}')^\beta(\bot,\top)\mid \beta<\alpha\}=
(\bigcap_{\beta<\alpha} (({\cal O}')^\beta(\bot,\top))_1, \bigcap_{\beta<\alpha} (({\cal O}')^\beta(\bot,\top))_2)$,
and $lub_{\preceq^A_i}\{ (S({\cal O})')^\beta(\bot,\top)\mid \beta<\alpha\}=
(\bigcap_{\beta<\alpha} ((S({\cal O}'))^\beta(\bot,\top))_1, \bigcap_{\beta<\alpha} ((S({\cal O}'))^\beta(\bot,\top))_2)$.
\item By the inductive hypothesis, it holds that
$\bigcap_{\beta<\alpha} (({\cal O}')^\beta(\bot,\top))_1\preceq^S_L \bigcap_{\beta<\alpha} ((S({\cal O}'))^\beta(\bot,\top))_1$
and $((S({\cal O}'))^\beta(\bot,\top))_2\preceq^H_L \bigcap_{\beta<\alpha} (({\cal O}')^\beta(\bot,\top))_2$. \qedhere
\end{enumerate}
\end{proof}
Using the above lemma, we can now show that the well-founded state ${\sf WF}({\cal O})$, which we define as the Kripke-Kleene-state of the stable operator ${\sf KK}(S({\cal O}))$,
is more precise than the Kripke-Kleene-state of ${\cal O}$ (for downward-closed operators):
\begin{theorem}
\label{proposition:properties:of:well-founded:state}
Let ${\cal L}=\langle L,\leq\rangle$ be a lattice and ${\cal O}$ an ndao over ${\cal L}$ s.t.\ ${\cal O}_l(.,x)$ is downward closed
for every $x\in L$. Then ${\sf WF}({\cal O})$ exists, is unique, and has the following properties:
\begin{itemize}
\item ${\sf KK}({\cal O})\preceq^A_i {\sf WF}({\cal O})$,
\item ${\sf WF}({\cal O})$ approximates any stable interpretation $(x,y)\in S({\cal O})(x,y)$, i.e.\ ${\sf WF}({\cal O})\preceq^A_i (x,y)$ for any $(x,y)\in S({\cal O})(x,y)$.
\item If ${\cal O}$ approximates $O$, for any fixpoint $x\in O(x)$, ${\sf WF}({\cal O})\preceq^A_i (x,x)$.
\end{itemize}
\end{theorem}
\begin{proof}
The proof of existence and uniqueness is similar to that of Theorem~\ref{theorem:ndso:fixpoint}, since $S({\cal O})'$ is $\preceq^A_i$-monotonic
(Proposition~\ref{lemma:O':is:alcantara:monotonic}).\footnote{Recall that
$S({\cal O})'$ is obtained by taking the state-version (Remark~\ref{remark:ndso:from:ndao}) of the stable operator (Definition~\ref{def:stable:op}) based on ${\cal O}$.}
The first property follows from Lemma~\ref{lemma:stable:is:more:precise:than:kk}, using again Knaster-Tarski fixpoint theorem.
For the second property, consider some $(x,y)\in S({\cal O})(x,y)$.
Since $(\bot,\top)\leq_i (x,y)$ and $S({\cal O})'$ is $\preceq^A_i$-monotonic, $S({\cal O})'(\bot,\top)\preceq^A_i S({\cal O})'(x,y)$. Let $S({\cal O})'(x,y)= X\times Y$.
Since $(x,y)$ is a stable fixpoint, $x\in X$ and $y\in Y$. Thus, $S({\cal O})'(\bot,\top)\preceq^A_i (x,y)$. We can repeat this argument until we reach ${\sf KK}(S({\cal O}))={\sf WF}({\cal O})$.
The proof of the third property is similar to that of the second property.
\end{proof}
\begin{example}
We illustrate the construction in the proof of Theorem~\ref{proposition:properties:of:well-founded:state} by the program from Example~\ref{ex:stable:not:exist}.
Recall that:
$${\cal P}=\{p\lor q\lor r \leftarrow; \quad p\leftarrow \lnot q; \quad r\leftarrow \lnot p; \quad q\leftarrow \lnot r\}.$$
The well-founded state is constructed as follows:
\begin{itemize}
\item $S({\cal IC}_{\cal P})'({\upclosure{\emptyset}},{\downclosure{\{p,q,r\}}})=\{\{p\},\{q\},\{r\}\}\uparrow\times \{\{p,q,r\}\}\downarrow$.
In more detail, this is obtained as follows (recall that $C({\cal IC}^l_{\cal P})$ is described in Example~\ref{ex:stable:not:exist}):
\begin{align*}
S({\cal IC}_{\cal P})'({\emptyset\uparrow},{\{p,q,r\}\downarrow}) \hspace*{3mm} & =
\bigcup_{y\in \downclosure{\{p,q,r\}\:}} \hspace*{-3mm} \upclosure{C({\cal IC}^l_{\cal P})(y)} \ \times \ \bigcup_{x \in \upclosure{\emptyset\:\:}} \downclosure{C({\cal IC}^l_{\cal P})(y)} \\
\ & = \bigcup_{y\subseteq\{p,q,r\}} \hspace*{-2mm} \upclosure{C({\cal IC}^l_{\cal P})(y)} \ \times \ \hspace*{-3mm} \bigcup_{x\subseteq \{p,q,r\}} \hspace*{-2mm} \downclosure{C({\cal IC}^l_{\cal P})(y)}
\end{align*}
\item $(S({\cal IC}_{\cal P}))'(S({\cal IC}_{\cal P})({\upclosure{\emptyset}},{\downclosure{\{p,q,r\}}}))=\upclosure{\{\{p\},\{q\},\{r\}\}}\times \downclosure{\{\{p,q\},\{q,r\},\{p,r\}\}}$.
\item $(S({\cal IC}_{\cal P}))'^2(S({\cal IC}_{\cal P})({\upclosure{\emptyset}},\downclosure{\{p,q,r\}}))=(S({\cal IC}_{\cal P}))'(S({\cal IC}_{\cal P})({\emptyset\uparrow},{\{p,q,r\}\downarrow}))$
and thus a fixed point is reached.
\end{itemize}
We thus see that
\[{\sf WF}({\cal IC}_{\cal P})={\sf KK}(S({\cal IC}_{\cal P}))=\upclosure{\{\{p\},\{q\},\{r\}\}}\times \downclosure{\{\{p,q\},\{q,r\},\{p,r\}\}}\]
This is represented by the convex set:
\[ \{\{p\},\{q\},\{r\},\{p,q\},\{q,r\},\{p,r\}\}\]
Intuitively, the well-founded state expresses that at least one among $p$, $q$ or $r$ is true (i.e.\ $p\lor q\lor r$ is true), and at least one among $p$, $q$ or $r$ is false (i.e.\ $\lnot p\lor \lnot q\lor \lnot r$ is true).
It is interesting to note that this is exactly the same outcome as the well-founded semantics with disjunction (see~\cite[Example 6]{alcantara2005well}). We will see in
Section~\ref{sec:well-founded:alcantara} that this close resemblance is not a coincidence. For this program, the Kripke-Kleene state coincides with the well-founded state.
It shows that the state semantics give meaning to programs which do not have (partial)
stable interpretations. Thus, this example illustrates the existence and uniqueness-properties of the well-founded state (and the Kripke-Kleene state).
\end{example}
\begin{example}
Consider the dlp ${\cal P}=\{p\lor q\leftarrow\lnot s; \quad s\leftarrow r; \quad r\leftarrow s\}$. We calculate ${\sf WF}({\cal IC}_{\cal P})$ as follows (using Theorem~\ref{prop:stable:fixpoints:represent:stable:models}):
\begin{eqnarray*}
S({\cal IC}_{\cal P})'(\emptyset,\{p,q,s\})&=& \upclosure{\min_\subseteq {\sf Mod}(\frac{{\cal P}}{{\cal A}_{\cal P}})}\times \downclosure{
\min_\subseteq {\sf Mod}(\frac{{\cal P}}{\emptyset})} =\upclosure{\{\emptyset\}}\times \downclosure{\{\{p\},\{q\}\}}\\
S({\cal IC}_{\cal P})'^2(\emptyset,\{p,q\})&=&
\upclosure{\left(\min_\subseteq {\sf Mod}(\frac{{\cal P}}{\{p\}})
\cup
\min_\subseteq {\sf Mod}(\frac{{\cal P}}{\{q\}})\right)}
\times \downclosure{
\min_\subseteq {\sf Mod}(\frac{{\cal P}}{\emptyset})} \\
&=&
\upclosure{\{\{p\},\{q\}\}}\times \downclosure{\{\{p\},\{q\}\}}\\
S({\cal IC}_{\cal P})'^3(\emptyset,\{p,q\})&=& \upclosure{\left(\min_\subseteq {\sf Mod}(\frac{{\cal P}}{\{p\}})
\cup
\min_\subseteq {\sf Mod}(\frac{{\cal P}}{\{q\}})\right)}
\times \downclosure{\left(\min_\subseteq {\sf Mod}(\frac{{\cal P}}{\{p\}})
\cup
\min_\subseteq {\sf Mod}(\frac{{\cal P}}{\{q\}})\right)}\\
&=&
\upclosure{\{\{p\},\{q\}\}}\times \downclosure{\{\{p\},\{q\}\}}\\
\end{eqnarray*}
and thus a fixpoint is reached after two iterations. The well-founded state is thus represented by the convex set $\{\{p\},\{q\}\}$.
This can be compared to the Kripke-Kleene state ${\sf KK}({\cal IC}_{\cal P})$:
\begin{itemize}
\item $({\cal IC}_{\cal P}(\emptyset,\{p,q,s\}))'=\upclosure{\emptyset}\times\downclosure{\{\{p,s,r\},\{q,s,r\}\}}$.
\item $({\cal IC}_{\cal P}(\emptyset,\{p,q,s\}))'^2=\upclosure{\emptyset}\times\downclosure{\{\{p,s,r\},\{q,s,r\}\}}$ and thus a fixpoint is reached.
\end{itemize}
The Kripke-Kleene state is thus represented by the convex set $\wp({{\cal A}_{\cal P}})$. This means that in this case, the well-found state is significantly more precise than the Kripke-Kleene state.
This example also illustrates that the well-founded state approximates the stable interpretations of ${\cal P}$. Indeed, the stable interpretations are $\{p\}$ and $\{q\}$, and it holds that
$\upclosure{\{\{p\},\{q\}\}}\times \downclosure{\{\{p\},\{q\}\}}\preceq^A_i (\{p\},\{p\})$ and $\upclosure{\{\{p\},\{q\}\}}\times \downclosure{\{\{p\},\{q\}\}}\preceq^A_i (\{q\},\{q\})$.
\end{example}
We conclude this section by showing that the well-founded state coincides with the well-founded fixpoint for deterministic approximation operators for
approximation operators over finite lattices, thus showing that the well-founded state is a faithful generalization of the deterministic well-founded fixpoint:
\begin{theorem}
Consider an ndao ${\cal O}:{\cal L}^2\rightarrow \wp({\cal L})^2$ over a finite lattice ${\cal L}$ s.t.\ ${\cal O}(x,y)$ is a pair of singleton sets for every $x,y\in{\cal L}$.
Let ${\cal O}^{\sf AFT}$ be defined by ${\cal O}^{\sf AFT}(x,y)=(w,z)$ where ${\cal O}(x,y)=(\{w\},\{z\})$, and let $(x^{\sf WF},y^{\sf WF})$ be the well-founded fixpoint of
${\cal O}^{\sf AFT}$.\footnote{Recall Definition~\ref{def:stable-op} for the definition of the well-founded fixpoint of a deterministic approximation operator.} Then
${\sf WF}({\cal O})= \upclosure{x^{\sf WF}}\times \downclosure{y^{\sf WF}}$.
\end{theorem}
\begin{proof}
Since the well-founded fixpoint of ${\cal O}^{\sf AFT}$ is a fixpoint of $S({\cal O})$, by Proposition \ref{prop:stble:coincide:deterministic} $(x^{\sf WF},y^{\sf WF})$ is
a stable fixpoint of $S({\cal O})$. By the second item of Theorem~\ref{proposition:properties:of:well-founded:state}, ${\sf WF}({\cal O})\preceq^A_i (x^{\sf WF},y^{\sf WF})$.
We now show that $\upclosure{x^{\sf WF}}\times\downclosure{y^{\sf WF}}\preceq^A_i {\sf WF}({\cal O})$ by induction on the number of iterations for reaching a fixpoint.
For the base case notice that, again by Proposition~\ref{prop:stble:coincide:deterministic},
$\upclosure{\{S({\cal O}_l^{\sf AFT})(.,\top)\}}\times \downclosure{ \{S({\cal O}_u^{\sf AFT})(\bot,.)\}}= S({\cal O})'(\bot,\top)$.
For the inductive case, suppose that for some $i\in\mathbb{N}$, $(x_i,y_i)$ corresponds to the result of applying $i$ times $S({\cal O})$ to $(\bot,\top)$ and suppose that
$\upclosure{\{x_i\}}\times \downclosure{\{y_i\}}\preceq^A_i S({\cal O})'^i(\bot,\top)$. This means that there are some $x',y'\in {\cal L}$ where $x'$ occurs in the first component
of $S({\cal O})'^i(\bot,\top)$ and $y'$ occurs in the second component of $S({\cal O})'^i(\bot,\top)$ s.t.\ $x_i \leq x'$ and $y'\leq y_i$, i.e.\ $(x_i,y_i)\leq_i (x',y')$.
Since $S({\cal O}^{\sf AFT})$ is $\leq_i$-monotonic (see~\cite[Proposition 20]{denecker2000approximations}), $S({\cal O}^{\sf AFT})(x_i,y_i)\leq_i S({\cal O}^{\sf AFT})(x',y')$.
By definition,
\begin{align*}
S({\cal O})'^{i+1}(\bot,\top)&=& \hspace{-15mm} \bigcup_{(x,y)\in S({\cal O})'^i(\bot,\top)}& \upclosure{C({\cal O}_l)(y)}\times \downclosure{ C({\cal O}_u)(x)} \\
&=& \hspace{-15mm} \bigcup_{(x,y)\in S({\cal O})'^i(\bot,\top)} &\upclosure{\{C({\cal O}^{\sf AFT}_l)(y)\}}\times \downclosure{\{ C({\cal O}^{\sf AFT}_u)(x)\}}
\end{align*}
and thus $(S({\cal O}^{\sf AFT}))^{i+1}(x',y') \preceq^A_i S({\cal O})'^{i+1}(\bot,\top)$. Hence, with a slight abuse of the notations, we have shown that
$S({\cal O}^{\sf AFT})(x_i,y_i)\preceq^A_i S({\cal O})'^{i+1}(\bot,\top)$.
\end{proof}
An interesting property of the well-founded state of ${\cal IC}_{\cal P}$ is that for positive logic programs, the well-founded state coincides with the \emph{minimal\/}
models of a the logic program.
\begin{proposition}
\label{prop:positive:programs:state}
If ${\cal P}$ is a positive dlp, then ${\sf WF}({\cal IC}_{\cal P})=\upclosure{\min_\subseteq mod({\cal P})}\times \downclosure{\min_\subseteq mod({\cal P})}$.
\end{proposition}
\begin{proof}
Notice first that, since ${\cal P}$ is positive, $\frac{{\cal P}}{y}={\cal P}$ for any $y\subseteq {\cal A}_{\cal P}$ (no rule in ${\cal P}$ contains negative literals in the body, and so no rule is deleted
or transformed in the construction of $\frac{{\cal P}}{y}$). By Proposition \ref{lemma:stable:ic:is:reduct}, this means that, for any $y\subseteq {\cal A}_{\cal P}$,
$C({\cal IC}^l_{\cal P})(y)=\min_\subseteq(mod({\cal P}))$. Thus, $S({\cal IC}_{\cal P})'(\emptyset,{\cal A}_{\cal P})=\upclosure{\min_\subseteq mod({\cal P})}\times \downclosure{\min_\subseteq mod({\cal P})}$
and a fixpoint is reached at the first iteration of the construction of the well-founded state.
\end{proof}
\subsection{The Relationship with Well-Founded Semantics with Disjunction}
\label{sec:well-founded:alcantara}
As another indication for the usefulness of our constructions, we show that the well-founded state approximates the existing well-founded semantics for disjunctive logic programs,
which is the well-founded semantics for disjunction ${\sf WFS}_d$ by Alc{\^a}ntara, Dam{\'a}sio and Pereira~\cite{alcantara2005well}.
Alc{\^a}ntara, Dam{\'a}sio and Pereira~\cite{alcantara2005well} define the well-founded semantics for disjunction ${\sf WFS}_d$ which bears similarities to our well-founded semantics.
We present this semantics here, adapting the notation and technicalities to our setting.
The basic idea behind the well-founded semantics with disjunction as defined by Alc{\^a}ntara, Dam{\'a}sio and Pereira~\cite{alcantara2005well}
is the following: a sequence of a set of lower bounds and upper bounds approximating the stable models of a disjunctive logic program is constructed iteratively.
Given a set of lower bounds and a set of upper bounds,
new (more precise) lower and upper bounds can be obtained by applying the two-valued immediate consequence operator $IC$ to the reducts of the program obtained on the basis of
the upper bounds and lower bounds (respectively). The lower bounds are thus used to obtain new upper bounds and vice versa.
This iteration leads to more and more precise lower and upper bounds, until a fixpoint is reached. This well-founded semantics is guaranteed to exist, be unique, and coincide
with the well-founded model for normal logic programs~\cite{alcantara2005well}.
We now develop this notion in more technical details. The operator $\Gamma_{\cal P}(X)$ is defined as follows:\footnote{Recall that the \emph{two-valued models} of a positive
program ${\cal P}$ are the sets
$x\subseteq {\cal A}_{\cal P}$ s.t.\ for every $\bigvee\Delta\leftarrow \phi \in {\cal P}$, $(x,x)(\phi)={\sf T}$ implies $x\cap \Delta\neq\emptyset$ (Footnote~\ref{footnote:2-val mod}).}
\[\Gamma_{\cal P}(X)=\bigcup_{x\in X}\min_\subseteq(mod_2(\frac{{\cal P}}{x}))\]
Instead of just applying the $\Gamma_{\cal P}$-operator to the lower bound and closing it downwards to obtain a new upper bound, a form of closed world reasoning is performed
in~\cite{alcantara2005well} by applying $\Gamma_{\cal P}$ to the interpretations in the lower bound not containing any atoms not occurring in any upper bound.
Formally, this is done by defining the set ${\frak F}(Y)$ that contains all atoms not occurring in any upper bound $y\in Y$, and the set ${\frak T}_Y(X)$ that contains
all the sets in $X$ without any atoms in ${\frak F}(Y)$.
\begin{definition}%
Given $X,Y\subseteq {\cal A}_{\cal P}$, we define:
\begin{itemize}
\item ${\frak F}(Y)=\{ \alpha\in {\cal A}_{\cal P}\mid \alpha\not\in \bigcup Y\}$.
\item ${\frak T}_Y(X)=\{x\in X\mid x\cap {\frak F}(Y)=\emptyset\}$.
\end{itemize}
\end{definition}
We are now ready to define the $\Phi$-operator which is the basis of the well-founded semantics for disjunction~\cite{alcantara2005well}, obtained by taking as set of new lower bounds
all models of reducts of some upper bound, and as new upper bounds all models of reducts of some lower bound in ${\frak T}_Y(X)$.
\begin{definition}
Let some disjunctive logic program ${\cal P}$ and some $X,Y\subseteq \wp({\cal A}_{\cal P})$ be given. Then:
\[ \Phi_{\cal P}(X,Y)=\Gamma_{\cal P}(Y)\uparrow\times \Gamma_{\cal P}({\frak T}_Y(X))\downarrow.\]
The \emph{well-founded semantics for disjunction of a program ${\cal P}$}, denoted ${\sf WFS}_d({\cal P})$ is defined as the least fixpoint of $\Phi_{\cal P}$, obtained by applying
$\Phi_{\cal P}$ iteratively to $\{\emptyset\}\times \{{\cal A}_{\cal P}\}$.
\end{definition}
We can show that our well-founded semantics is an approximation of the ${\sf WFS}_d$. It really is an approximation, since we do not apply closed world reasoning in constructing the lower
bound (but one could).
\begin{theorem}
\label{prop:well:founded:state:represents:alcantara:almost}
For any disjunctive logic program ${\cal P}$, ${\sf WF}({\cal IC}_{\cal P})\preceq^A_i {\sf WFS}_d({\cal P})$.
\end{theorem}
\begin{proof}
By Proposition \ref{lemma:stable:ic:is:reduct}, $\Gamma_{\cal P}(X)=\bigcup_{x\in X}C({\cal IC}^l_{\cal P})(x)$ for any $X\subseteq 2^{{\cal A}_{\cal P}}$. Furthermore, as for any
$X,Y\subseteq {\cal A}_{\cal P}$, ${\frak T}_Y(X)\subseteq X$, it holds that $\bigcup_{x\in{\frak T}_Y(X)} S({\cal IC}_{\cal P})(x)\preceq^H_L \bigcup_{x\in X} S({\cal IC}_{\cal P})(x)$.
The proposition now immediately follows from these two observations.
\end{proof}
The following example (taken from~\cite{alcantara2005well}) shows that ${\sf WFS}_d({\cal P})$ can give rise to a strictly more precise approximation than that of ${\sf WF}({\cal IC}_{\cal P})$:
\begin{example}
Consider the logic program ${\cal P}=\{p\lor q\leftarrow; q\leftarrow \lnot r\}$. We first calculate ${\sf WF}({\cal IC}_{\cal P})$ as follows:
\begin{eqnarray*}
S({\cal IC}_{\cal P})(\upclosure{\{\emptyset\}},\downclosure{\{p,q,r\}})&=&
\upclosure{\min_\subseteq\left(\bigcup_{x\subseteq \{p,q,r\}}mod_2(\frac{{\cal P}}{x})\right)}\times \downclosure{\min_\subseteq\left(\bigcup_{x\subseteq \{p,q,r\}}mod_2(\frac{{\cal P}}{x})\right)}\\
&=& \upclosure{\{\{p\},\{q\}\}}\times \downclosure{\{\{p\},\{q\}\}}\\
S^2({\cal IC}_{\cal P})(\upclosure{\{\emptyset\}},\downclosure{\{p,q,r\}})&=&\upclosure{\min_\subseteq\left(mod_2(\frac{{\cal P}}{\{p\}})\cup mod_2(\frac{{\cal P}}{\{q\}})\right)}\times \downclosure{ \min_\subseteq\left(\bigcup_{x\subseteq \{p,q,r\}}mod_2(\frac{{\cal P}}{x})\right)}\\
&=&\upclosure{\{\{q\}\}}\times \downclosure{\{\{p\},\{q\}\}}\\
S^3({\cal IC}_{\cal P})(\upclosure{\{\emptyset\}},\downclosure{\{p,q,r\}})&=&
\upclosure{\min_\subseteq\left(mod_2(\frac{{\cal P}}{\{q\}})\cup mod_2(\frac{{\cal P}}{\{q\}})\right)}\times \downclosure{ \min_\subseteq\left(\bigcup_{x\subseteq \{p,q,r\}}mod_2(\frac{{\cal P}}{x})\right)}\\
&=&\upclosure{\{\{q\}\}}\times \downclosure{\{\{p\},\{q\}\}}\\
\end{eqnarray*}
and so a fixpoint is reached after the second iteration. The well-founded state for this program thus corresponds to the convex set $\{\{q\},\{p\},\{q\}\}$.
It can be observed that $\frac{{\cal P}}{x}=\{p\lor q\leftarrow\}$ for any $\{r\}\subseteq x\subseteq {\cal A}_{\cal P}$. In particular, as there are some $x\in \upclosure{\{p\},\{q\}}$ s.t.\ $r\in x$,
this explains why $\{p\}$ is part of the upper bound of ${\sf WF}({\cal IC}_{\cal P})$. It is exactly this kind of behaviour that the filtering out lower bounds that have elements not occuring in any upper
bound in ${\frak T}_Y(X)$ tries to avoid. Indeed, ${\sf WFS}_d({\cal P})$ is built up as follows:
\begin{eqnarray*}
\Phi_{\cal P}(\{\emptyset\},\{\{p,q,r\}\})&=&S({\cal IC}_{\cal P})(\upclosure{\{\emptyset\}},\downclosure{\{p,q,r\}})\\
&=&\upclosure{\{\{p\},\{q\}\}}\times \downclosure{\{\{p\},\{q\}\}}\\
\Phi^2_{\cal P}(\{\emptyset\},\{\{p,q,r\}\})&=&
\upclosure{\min_\subseteq\left(mod_2(\frac{{\cal P}}{\{p\}})\cup mod_2(\frac{{\cal P}}{\{q\}})\right)}\times
\downclosure{ \min_\subseteq\left(mod_2(\frac{{\cal P}}{\{p\}})\cup mod_2(\frac{{\cal P}}{\{q\}})\cup mod_2(\frac{{\cal P}}{\{q,r\}})\right)}\\
&=&\upclosure{\{\{p\}\}}\times \downclosure{\{\{p\}\}}\\
\Phi^3_{\cal P}(\{\emptyset\},\{\{p,q,r\}\})&=&
\upclosure{\min_\subseteq\left(mod_2(\frac{{\cal P}}{\{p\}})\cup mod_2(\frac{{\cal P}}{\{q\}})\right)}\times
\downclosure{ \min_\subseteq\left(mod_2(\frac{{\cal P}}{\{p\}})\cup mod_2(\frac{{\cal P}}{\{q\}})\cup mod_2(\frac{{\cal P}}{\{q,r\}})\right)}\\
&=&\upclosure{\{\{p\}\}}\times \downclosure{\{\{p\}\}}
\end{eqnarray*}
The upper bound of $\Phi^2_{\cal P}(\{\emptyset\},\{\{p,q,r\}\})$ can be seen to hold in view of ${\frak T}_{\downclosure{\{\{p\},\{q\}\}}}( \upclosure{\{\{p\},\{q\}\}})=\{\{p\},\{q\},\{p,q\}\}$. After two iterations, a fixed point is reached, and thus we see that ${\sf WFS}_d({\cal P})$ corresponds to the convex set $\{\{p\}\}$, which is a more precise approximation than ${\sf WF}({\cal IC}_{\cal P})$. Formally:
\[ {\sf WF}({\cal IC}_{\cal P})=\upclosure{\{\{q\}\}}\times \downclosure{\{\{p\},\{q\}\}}\prec_i^A {\sf WFS}_d({\cal P}) =\upclosure{\{\{p\}\}}\times \downclosure{\{\{p\}\}}.\]
\end{example}
We leave the investigation of techniques to make the well-founded fixpoint more precise, such as the technique using ${\frak T}_Y(X)$, for further work.}
\paragraph{Summary}
Let's summarize the results in Section~\ref{sec:stable:semantics}. We first defined and studied stable operators (Section \ref{subsec:stable:interpretation:sem}), establishing which properties carry over
(under certain conditions) from the deterministic to the non-deterministic setting, and showing the usefulness of stable fixpoints in disjunctive logic programming. Then (Section~\ref{subsec:well-foundedstate}),
we introduced and studied the well-founded state, proving its existence, uniqueness, and showing that it is more precise than the Kripke-Kleene state and that it approximates any fixpoint of the
approximated operator. Finally (Section~\ref{sec:well-founded:alcantara}), we have shown that the well-founded state is useful for knowledge representation, as it is closely related to the well-founded semantics for disjunction~\cite{alcantara2005well}.
\section{Related Work}
\label{sec:related:work}
The starting point of this work is the approximation fixpoint theory (for deterministic operator), as introduced by Denecker, Marek and Truszczy{\'n}ski~\cite{denecker2000approximations},
followed by a series of papers \cite{antic2013hex, bogaerts2019weighted, bogaerts2015grounded, charalambidis2018approximation, denecker2012approximation, denecker2002ultimate,
denecker2003uniform, HA2020argumentative, strass2015analyzing}. As indicated previously (see, e.g., Remark~\ref{remark:deterministic}), this work generalizes AFT in
the sense that all the operators and fixpoints defined in this paper coincide with the respective counterparts for deterministic operators.
This paper (extending and improving our paper in~\cite{DBLP:conf/kr/HeyninckA21}) is also inspired by the work of Pelov and Truszczy\'nski~\cite{pelov2004semantics},
which extends approximation fixpoint theory to dealing with non-deterministic operators. Their work provides a representation theorem, in terms of non-deterministic AFT,
of specific two-valued semantics for disjunctive logic programs (namely, the two-valued stable semantics and two-valued weakly supported and supported models).
We have compared our work to that of Pelov and Truszczy\'nski~\cite{pelov2004semantics} in Section~\ref{sec:intro}.
To the best of our knowledge, the only setting with a similar unifying potential that has been applied to non-deterministic or disjunctive reasoning is
\emph{equilibrium logic\/}~\cite{pearce2006equilibrium}. The similarities between equilibrium logic and AFT have been noted in~\cite{denecker2012approximation},
where it was indicated that equilibrium semantics are defined for a larger class of logic programs than those that are represented by AFT, a limitation of AFT which
we have overcome in this paper. Furthermore, defining three-valued stable and well-founded semantics is not possible in standard equilibrium logic, but requires an extension
known as \emph{partial equilibrium logic\/}~\cite{cabalar2006analysing,cabalar2007partial}, which can be seen as a six-valued semantics. In contrast, the well-founded semantics
{\em is defined\/} in AFT using the same operator used to define the stable semantics. That being said, in future work we plan to compare in more detail the well-founded semantics
for DLP obtained on the basis of partial equilibrium logic and the well-founded semantics obtained in this work.
\section{Summary, Conclusion, and Future Work}
\label{sec:conc}
This paper contains a full approximation fixpoint theory to non-deterministic operators. We introduced deterministic operators,
their non-deterministic approximation operators, and the various fixpoint semantics, namely, the Kripke-Kleene interpretation and state semantics, the stable interpretation semantics
and the well-founded state semantics. The properties of these semantics and their representation of disjunctive logic programming semantics is summarized in Table~\ref{tab:summary}.
The relation between these fixpoint semantics is summarized in Figure~\ref{fig:fixpoint:relations}.
\begin{table}[h]
{\centering
\renewcommand{\arraystretch}{1.3}
\setlength{\tabcolsep}{4.5pt}
\begin{tabular}{llcccll}
Name & Definition & Exist & Unique & $\leq_t$-min.& Result & DLP-representation \\ \hline
KK interp.\ & $\lfp({\cal O})$ & $\times$ & $\times$ & $\times$ & & weakly supported (Th.\ref{theo:correspondence:supported}) \\
KK state & $\lfp({\cal O}')$ & $\checkmark$ & $\checkmark$ & $\times$& Th.\ref{theorem:ndso:fixpoint} & \\
Stable interp.\ & ${\rm fp}(S({\cal O}))$ & $\times$ & $\times$ & $\checkmark$& Prop.\ref{prop:stable:is:minimal:fp}& stable models (Th.\ref{prop:stable:fixpoints:represent:stable:models}) \\
WF state & $\lfp(S({\cal O})')$ & $\checkmark$ & $\checkmark$ & $\times$ & Th.\ref{proposition:properties:of:well-founded:state}& WF sem.\ with disjunct.\ (Th.\ref{prop:well:founded:state:represents:alcantara:almost}) \\
& &&&&& Min.\ mod.\ of positive dlps (Prop.\ref{prop:positive:programs:state})
\end{tabular}}
\caption{Approximating operators and their properties.}
\label{tab:summary}
\end{table}
\begin{figure}[h]\centering
\begin{tikzpicture}[thick,scale=1, every vertex/.style={scale=1}]
\tikzset{vertex/.style = {shape=rectangle,draw,minimum size=1.5em,rounded corners=.8ex,scale=1}}
\tikzset{edge/.style = {->,> = latex'}}
\node[vertex] (KKS) at (0,0) [draw, align=left] {KK-state\\ $l\!f\!p_{\preceq^A_i}({\cal O}')$};
\node[vertex] (WFS) at (5,0) [draw, align=left] {Well-founded state\\ $l\!f\!p_{\preceq^A_i}(S({\cal O})')$};
\node[vertex] (KKI) at (0,2) [draw, align=left] {Fixpoint of ndao \\$(x,y)\in {\cal O}(x,y)$};
\node[vertex] (2KKI) at (0,4) [draw, align=left] {Total Fixpoint of ndao \\$(x,x)\in{\cal O}(x,x)$};
\node[vertex] (SI) at (5,2) [draw, align=left] {Stable interpetation\ \\$(x,y)\in S({\cal O})(x,y)$};
\node[vertex] (2SI) at (5,4) [draw, align=left] {Total Stable interpetation\ \\$(x,x)\in S({\cal O})(x,x)$};
\node[vertex] (O) at (10,2) [draw, align=left] {Fixpoint of operator \\ $x\in O(x)$};
\draw[edge, dotted] (KKI) to (KKS);
\draw[edge, dashed] (WFS) to (KKS);
\draw[edge, dotted] (SI) to (WFS);
\draw[edge] (SI) to (KKI);
\draw[edge] (2SI) to (SI);
\draw[edge, dotted] (O) to (SI);
\draw[edge] (2KKI) to (KKI);
\draw[edge] (2SI) to (2KKI);
\end{tikzpicture}
\caption{Relations between various fixpoints introduced in this paper. The arrows have the following meaning: full arrows mean that every instance of the first block
(i.e., at the outgoing end of the arrow) is an instance of the second block (at the ingoing end of the arrow). Dotted arrows mean that all instances of
the first block are approximated by the second block. Dashed arrows mean that every instance of the first block is more precise than every instance of the second block.
The relations are shown in~Proposition \ref{prop:KK-states-properties} and Theorem~\ref{proposition:properties:of:well-founded:state}.}
\label{fig:fixpoint:relations}
\end{figure}
This work also
allows to generalize the results in~\cite{antic2013hex,pelov2004semantics}, which provide further approximation operators for disjunctive logic programs with aggregates or external atoms, to further semantics of disjunctive logic programs, thus answering an open question in
these works.
The advantage of studying non-deterministic operators
is thus at least twofold:
\begin{enumerate}
\item allowing to define a family of semantics
%
for non-monotonic reasoning with disjunctive information,
%
\item clarifying similarities and differences between semantics stemming from the use of different operators.
%
%
\end{enumerate}
The introduction of disjunctive information in AFT points to a wealth of further research, such as defining three-valued and well-founded semantics for various disjunctive
nonmonotonic formalisms and studying on the basis of which operators various well-founded semantics for DLP can be represented in our framework. For example, our framework
can potentially be used for defining three-valued and well-founded semantics for propositional theories~\cite{truszczynski2010reducts}, disjunctive logic programs with
recursive aggregates~\cite{faber2004recursive}, logic programs with aggregates in the head~\cite{gelfond2014vicious}, logic programs with forks~\cite{aguado2019forgetting},
and disjunctive default logics~\cite{Gelfond_et-al_PKRR_1991,bonevac2018defaulting}.
Non-deterministic approximation fixpoint theory has already been applied in order to obtain a generalization of abstract dialectical frameworks (ADFs) to \emph{conditional abstract dialectical frameworks}. In a nutshell, abstract dialectical frameworks consist of sets of arguments or atoms, in which every atom $a$ is assigned a Boolean acceptance condition $C_a$, which
codifies under which conditions an atom can be accepted. Heyninck and co-authors~\cite{DBLP:conf/aaai/HeyninckTKRS22} generalized ADFs as to allow for acceptance conditions to be
assigned to any, i.e.\ possibly non-atomic, formulas. This necessitated the generalization of the so-called $\Gamma$-operator to a non-deterministic operator, which was done in the
framework of non-deterministic approximation fixpoint theory as presented here.
Our
framework lays the ground for the generalization
of various interesting concepts introduced (or adapted) to AFT, such as ultimate approximations \cite{denecker2002ultimate}, grounded fixpoints
\cite{bogaerts2015grounded}, strong equivalence \cite{truszczynski2006strong}, stratification \cite{vennekens2006splitting} and argumentative representations
\cite{HA2020argumentative} to a non-deterministic setting. Extensions to DLP with negations in the rules' heads and corresponding 4-valued semantics~\cite{SI95}
can also be considered.
Another issue that is worth some consideration is a study of the complexity of computing different types of fixpoints of non-deterministic
approximation operators, in the style of Strass and Wallner \cite{strass2015analyzing}.
\section*{Acknowledgements}
We thank the reviewers of \cite{DBLP:conf/kr/HeyninckA21} for their helpful remarks.
The first author is supported by the German National Science Foundation (DFG-project KE-1413/11-1). He worked on this paper while affiliated with the Vrije Universiteit Brussel, the
Technische Universität Dortmund, the University of Cape Town and CAIR South-Africa, in addition to his current affiliation.
The second author is supported by the Israel Science Foundation (Grant~550/19).
The first and last author are supported by the Flemish Government in the ``Onderzoeksprogramma Artificiële
Intelligentie (AI) Vlaanderen'' programme, and by the FWO Flanders project G0B2221N.
\bibliographystyle{plain} %
| {'timestamp': '2022-12-02T02:10:17', 'yymm': '2211', 'arxiv_id': '2211.17262', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17262'} | arxiv |
\section{Introduction}
Textual Inversion~\citep{textual_inversion} is a novel technique for introducing a new concept in a pre-trained text conditional generative model. Given a few images of a user-provided concept (e.g. an object or style), Textual inversion learns a new ``word" in the embedding space to represent that object. Remarkably, these new \textit{pseudo-words} can be composed in language to produce all kinds of creative compositions.
We extend Textual inversion to learn multiple pseudo-words that represent a concept at different resolutions.
For example, in Fig. \ref{fig:figure1} the input concept is the
re-creation, with various small objects, of Vermeer's \textit{Girl with a Pearl Earring}, by artist J. Perkins~\citep{janeperkins}.
We learn this concept using 4 re-croppings of the input.
We then use a pre-trained text-to-image model to generate images using prompts that contain the learned pseudo-words that represent the concept at various resolutions.
\begin{figure}[ht]
\centering
\subcaptionbox*{Inputs}[0.23\textwidth]{}
\subcaptionbox*{\texttt{A painting of a dog in the style of <jane({$t_{\mathrm{fixed}}$})>.}}[0.69\textwidth]{}
\subcaptionbox*{}[0.23\textwidth]{\includegraphics[width=0.23\textwidth]{figures/jane/jane.png}}
\subcaptionbox{$t_{\mathrm{fixed}}=0.0$}[0.23\textwidth]{\includegraphics[width=0.23\textwidth]{figures/fig1/dog-jane0-200.png}}
\subcaptionbox{$t_{\mathrm{fixed}}=0.5$}[0.23\textwidth]{\includegraphics[width=0.23\textwidth]{figures/fig1/dog-jane5.png}}
\subcaptionbox{$t_{\mathrm{fixed}}=0.7$}[0.23\textwidth]{\includegraphics[width=0.23\textwidth]{figures/fig1/dog-jane7.png}}
\caption{\small{Multi-resolution textual inversion. We learn with our method the input concept as \texttt{<jane>}. We then show images generated with the prompt: \texttt{A painting of a dog in the style of <jane({$t_{\mathrm{fixed}}$})>}, where $t_{\mathrm{fixed}}$ controls the resolution in which the pseudo-word captures the input concept. Each pseudo-word represents the concept with different levels of detail with the zero index capturing the full detailed learned concept.}}
\label{fig:figure1}
\end{figure}
\section{Method}
\paragraph{Background.}
Text-conditional diffusion models are trained to restore a clean image, $x$, based on a corrupted observation, $z_t(x)$, and a text caption, $y$, describing the image~\citep{dalle2, imagen, ldms, ho2020denoising, song2020scorebased}. The corruption, which is typically additive noise, can be either in the image itself~\citep{dalle2, imagen} or in an encoding of the image~\citep{ldms}. We denote with $z_t(x)$ the diffused observation of image $x$ at time $t$. Text-conditional models are typically trained to minimize the objective:
\begin{gather}
J(\theta) = \mathbb E_{t\sim \mathcal U[0,1]} \mathbb E_{(x, y) \sim p}\mathbb E_{z_t\sim q_t(z_t|x, t)}||\hat \epsilon_{\theta}(z_t(x), t, c_{\theta}(y)) - \epsilon(z_0, z_t)||^2,
\end{gather}
where $p$ is the joint distribution of image-captions, $q_t$ is the distribution of the diffused observations, $y$ is the text-conditioning and $\epsilon$ is the unscaled residual to $z_0(x)$.
The conditioning network, $c_{\theta}(y)$, maps the tokenized text $y$ into a latent that is used to inform the prediction of the denoiser network, $\hat \epsilon_{\theta}$. The first layer of $c_{\theta}(y)$ is typically a lookup table, $\mathrm{emb}(y)$, that maps tokens to vectors. We decompose the conditioning network as: $c_{\theta}(y) = \mathrm{enc}_{\theta}(\mathrm{emb}_{\theta}(y))$.
The authors of Textual Inversion~\citep{textual_inversion} consider the task of finding an embedding, $\mathrm{emb}^*$ for a pseudo-token $y^*$ that represents a concept described by a small collection of images $X = \{x_1, ..., x_N\}$. They do so by solving the following optimization problem:
\begin{gather}
\min_{\mathrm{emb}}\mathbb E_{t\in \mathcal U[0, 1]}\mathbb E_{x \sim \mathcal U_X} \mathbb E_{z_t\sim q_t(z_t|x, t)}\left|\left| \hat \epsilon_{\theta}(z_t(x), t, \mathrm{enc}_{\theta}(\mathrm{emb})) - \epsilon(z_0, z_t)\right|\right|^2.
\label{eq:textual_obj}
\end{gather}
Intuitively, Textual Inversion is optimizing for an embedding that helps the model predict in the most effective way the residual across all the images in the set and across all corruption levels.
\paragraph{Multiresolution Textual Inversion.}
The key idea of our method is that \textit{the conditioning signal can depend on the diffusion time (i.e. the noise level)}. For example, if the input image to the diffusion model is a slightly noisy image of a cat, the text conditioning should give information on the details of the cat (e.g. texture) and not necessarily on the image class which can easily be inferred from the image input. Similarly, for very noisy images the conditioning should be capturing basic information such as image class (e.g. cat vs dog) and colors. In general, we propose the following objective:
\begin{gather}
\min_{\{\mathrm{emb}_0, ..., \mathrm{emb}_{T-1}\}}\mathbb E_{t\sim \mathcal U[0, 1]}\mathbb E_{x \sim \mathcal U_X} \mathbb E_{z_t\sim q_t(z_t|x, t)}\left|\left| \hat \epsilon_{\theta}(z_t(x), t, \mathrm{enc}_{\theta}(\mathrm{emb}_{\lfloor t/T \rfloor})) - \epsilon(z_0, z_t)\right|\right|^2.
\label{eq:ours}
\end{gather}
After training, we have learned a set of embeddings, $\mathrm{Emb}^*=\{\mathrm{emb}_{0}, ..., \mathrm{emb}_{T-1}\}$. Each of the the elements of the set, captures different levels of detail.
The idea of having latents that describe the image with different amounts of agreement to the input has been exploited to solve inverse problems with GANs~\citep{ilo, sgilo, gan_surgery}. In these works, the resolution is controlled by the index of the GAN layer in which we invert our images. In our method the agreement to the input is determined by the diffusion time index and we can manipulate the different resolutions using language.
We note that our method can also be extended to support DreamBooth~\citep{ruiz2022dreambooth}, an alternative method for Textual Inversion that finetunes the whole model.
We can create embeddings indexed by continuous time by using linear interpolations of the elements of the learned set.
We present three different ways to use the learned embeddings to sample at different levels of agreement to the concept appearing in the input images. For a visual comparison, we show how these methods perform for a given image at different resolution levels, in Fig. \ref{fig:sampling_comparisons}.
\paragraph{Fixed Resolution Sampling (Method 1).} The first method fixes the conditioning to a specific embedding throughout the sampling. It is the most similar sampling method to Textual Inversion, in the sense that it is using a fixed embedding for all diffusion levels. The user can control the resolution by picking one embedding from the set $\mathrm{Emb}^*$. This method allows the user to visualize what is learned at each resolution. As we explained earlier, we expect that embeddings that correspond to time close to $t=0$, should learn details (e.g. texture) since those are more informative to denoise a slightly noisy image than image class for example. Embeddings closer to $t=1$ should be related to more coarse information about the image, e.g. what is the object, what are the colors, etc.
For the next two sampling methods, we change the conditioning based on the sampling time. Assume that we want to generate an image at resolution $t=t_{\mathrm{fixed}}$. We propose two sampling methods:
\paragraph{Semi Resolution-Dependent Sampling (Method 2).} Semi Resolution-Dependent Sampling uses $\mathrm{emb}_{t}$ when the sampling time is $t$ if $t \geq t_{\mathrm{fixed}}$ and no conditioning otherwise. Essentially, this forces the model to generate images that match (in a distributional sense) the input images at noise level $t$. This method is particularly useful for style-transfer and creative prompts -- for some percentage of the sampling procedure the model performs unconditional generation (with a starting point a diffused sample that matches the original concept with noise). This idea extends the novel SDEdit paper~\citep{sdedit} in the sense that it allows to do guided image synthesis (but this time starting from language tokens).
\paragraph{Fully Resolution-Dependent Sampling (Method 3).} Fully Resolution-Dependent Sampling is similar to Semi Resolution-Dependent Sampling, but instead of doing unconditional generation for $t<t_{\mathrm{fixed}}$, it fixes the embedding to $\mathrm{emb}_{\mathrm{fixed}}$. This still allows for variations from the given concept (since $\mathrm{emb}_{\mathrm{fixed}}$ only resembles it in a given resolution), but the variations are more controlled since there is no sampling period of unconditional generation.
\paragraph{Creating a textual interface.} Similar to Textual Inversion, we create pseudo-words that allow us to use language to guide the image generation process with our learned embeddings. The difference is that the embeddings for our pseudo-words might be changing based on the sampling time. We use $S^*|t_{\mathrm{fixed}}|, S^*(t_{\mathrm{fixed}}), S^*[t_{\mathrm{fixed}}]$ to denote tokens that are used with Fixed Resolution, Semi Resolution and Fully Resolution Dependent Sampling respectively.
\section{Experiments}
\begin{figure}[!htp]
\centering
\captionsetup[subfigure]{aboveskip=-7pt,belowskip=-1pt}
\subcaptionbox*{\label{fig:button_inputs}}{\includegraphics[width=0.18\textwidth]{figures/jane/jane.png}}
\subcaptionbox*{\label{fig:cat_inputs}}{\includegraphics[width=0.18\textwidth]{figures/cat/cat.png}}
\subcaptionbox*{}{\includegraphics[width=0.18\textwidth]{figures/combinations/dog_jane1.png}}
\subcaptionbox*{}{\includegraphics[width=0.18\textwidth]{figures/combinations/cat_jane.png}}
\subcaptionbox*{}{\includegraphics[width=0.18\textwidth]{figures/combinations/jane_cat.png}}
\subcaptionbox{Inputs learned as <jane> and <cat>.\label{fig:button_cat_inputs}}[0.36\textwidth]{}
\subcaptionbox{\tiny{A painting of a dog made with <jane$|0.1|$>.}}[0.18\textwidth]{}
\subcaptionbox{\tiny{A photo of <cat$(5)$> made with <jane$|0.1|$>.}}[0.18\textwidth]{}
\subcaptionbox{\tiny{A photo of <jane$(3)$> similar to <cat$[0]$>.}}[0.18\textwidth]{}
\caption{\small{Compositions of learned pseudo-words across resolutions.
Observe that the dog (b) and cat (c) are made from small plastic objects, i.e. using the detailed structure of <jane>, but in the shape of a dog or the toy cat. In (d) the color stripes are obtained from the cat detail.
}}
\label{fig:mixes}
\end{figure}
We begin by comparing the different sampling methods. Results are shown in Fig. \ref{fig:sampling_comparisons}. Each row shows a different sampling algorithm each each column a different resolution. With Fixed Resolution Sampling (row 1), we can selectively extract details of the image, e.g. $S^*_{0.0}$ extracts only the buttons. Semi Resolution-Dependent Sampling (row 2) allows for larger variations from the input for high values of $t_{\mathrm{fixed}}$, e.g. $S^*(0.8)$ gives a photorealistic image of person that only roughly preserves colors and pose from the input concept. Finally, Fully Resolution-Dependent Sampling (row 3) maintains higher agreement to the input concept along all resolutions.
\begin{figure}[ht]
\centering
\captionsetup[subfigure]{aboveskip=-8pt,belowskip=-1pt}
\subcaptionbox*{Inputs}[0.15\textwidth]{}
\subcaptionbox*{\tiny{\texttt{A photo of $S^*|{t_{\mathrm{fixed}}}|$} (Fixed Resolution Sampling)}}[0.45\textwidth]{}
\subcaptionbox*{}{\includegraphics[width=0.15\textwidth]{figures/jane/jane.png}}
\subcaptionbox*{}{\includegraphics[width=0.15\textwidth]{figures/jane/each/8/1.png}}
\subcaptionbox*{}{\includegraphics[width=0.15\textwidth]{figures/jane/each/5/1.png}}
\subcaptionbox*{}{\includegraphics[width=0.15\textwidth]{figures/jane/each/0/2.png}}
\subcaptionbox*{}[0.15\textwidth]{}
\subcaptionbox*{\tiny{\texttt{A photo of $S^*({t_{\mathrm{fixed}}})$} (Semi Resolution-Dependent Sampling})}[0.45\textwidth]{}
\subcaptionbox*{}[0.15\textwidth]{}
\subcaptionbox*{}{\includegraphics[width=0.15\textwidth]{figures/jane/semi/8_alt.png}}
\subcaptionbox*{}{\includegraphics[width=0.15\textwidth]{figures/jane/semi/5.png}}
\subcaptionbox*{}{\includegraphics[width=0.15\textwidth]{figures/jane/semi/0.png}}
\subcaptionbox*{}[0.15\textwidth]{}
\subcaptionbox*{\tiny{\texttt{A photo of $S^*[{t_{\mathrm{fixed}}}]$} (Fully Resolution-Dependent Sampling)}}[0.45\textwidth]{}
\captionsetup[subfigure]{aboveskip=5pt,belowskip=0pt}
\subcaptionbox*{}[0.15\textwidth]{}
\subcaptionbox{$t_{\mathrm{fixed}}=0.8$}{\includegraphics[width=0.15\textwidth]{figures/jane/8.png}}
\subcaptionbox{$t_{\mathrm{fixed}}=0.5$}{\includegraphics[width=0.15\textwidth]{figures/jane/5.png}}
\subcaptionbox{$t_{\mathrm{fixed}}=0.0$}{\includegraphics[width=0.15\textwidth]{figures/jane/0.png}}
\caption{\small{Comparison of different sampling methods that be used for Multiresolution Textual Inversion. Each row shows a different sampling algorithm and each column a different resolution. With Fixed Resolution Sampling (row 1), we can selectively extract details of the image, e.g. $S^*|0.0|$ extracts only the buttons. Semi Resolution-Dependent Sampling (row 2) allows for larger variations from the input for high values of $t_{\mathrm{fixed}}$. Fully Resolution-Dependent Sampling (row 3) maintains higher agreement to the inputs along all resolutions.}}
\label{fig:sampling_comparisons}
\end{figure}
\begin{figure}[ht]
\begin{subfigure}{0.30\textwidth}
\caption*{\large{Inputs}}
\end{subfigure}
\begin{subfigure}{0.3\textwidth}
\caption*{\large{Ours}}
\end{subfigure}
\begin{subfigure}{0.3\textwidth}
\caption*{\large{Textual Inversion}}
\end{subfigure}
\subcaptionbox{}{\includegraphics[width=.3\textwidth]{figures/bird/inputs.png}}
\subcaptionbox{\scriptsize{Watercolor painting of $S^*$ on a branch.}}{\includegraphics[width=.15\textwidth]{figures/bird/watercolor/ours.png}}
\subcaptionbox{\scriptsize{Grainy photo of $S^*$ in angry birds.}}{\includegraphics[width=.15\textwidth]{figures/bird/angry_birds/ours_alt.png}}
\subcaptionbox{\scriptsize{Watercolor painting of $S^*$ on a branch.}}{\includegraphics[width=.15\textwidth]{figures/bird/watercolor/baseline.png}}
\subcaptionbox{\scriptsize{Grainy photo of $S^*$ in angry birds.}}{\includegraphics[width=.15\textwidth]{figures/bird/angry_birds/baseline.png}}
\subcaptionbox{}{\includegraphics[width=.3\textwidth]{figures/clock/inputs.png}}
\subcaptionbox{\scriptsize{A photo of $S^*$ on the beach.}}{\includegraphics[width=.15\textwidth]{figures/clock/beach/ours.png}}
\subcaptionbox{\scriptsize{A photo of $S^*$ on the moon.}}{\includegraphics[width=.15\textwidth]{figures/clock/moon/ours.png}}
\subcaptionbox{\scriptsize{A photo of $S^*$ on the beach.}}{\includegraphics[width=.15\textwidth]{figures/clock/beach/baseline.png}}
\subcaptionbox{\scriptsize{A photo of $S^*$ on the moon.}}{\includegraphics[width=.15\textwidth]{figures/clock/moon/baseline.png}}
\subcaptionbox{}{\includegraphics[width=.3\textwidth]{figures/physics_mug/inputs.png}}
\subcaptionbox{\scriptsize{A photo of $S^*$ on the beach.}}{\includegraphics[width=.15\textwidth]{figures/physics_mug/beach/ours.png}}
\subcaptionbox{\scriptsize{A photo of $S^*$ on the moon.}}{\includegraphics[width=.15\textwidth]{figures/physics_mug/moon/ours.png}}
\subcaptionbox{\scriptsize{A photo of $S^*$ on the beach.}}{\includegraphics[width=.15\textwidth]{figures/physics_mug/beach/baseline.png}}
\subcaptionbox{\scriptsize{A photo of $S^*$ on the moon.}}{\includegraphics[width=.15\textwidth]{figures/physics_mug/moon/baseline.png}}
\caption{\small{Personalized image generation. We show that with our method we can use the pseudo-words for the learned concept to create personalized images as if it was a normal word token. Our method performs on par and sometimes better than Textual Inversion on this task.}}
\label{fig:compositions}
\end{figure}
We then show that Multiresolution Textual Inversion performs on par (or even better) with Textual Inversion. Fig. \ref{fig:compositions} shows that our method can use the learned concepts in combinations with prompts of all sorts -- we use the prompt and images from the Textual Inversion paper.
Finally, Fig. \ref{fig:mixes} shows that the learned pseudo-words can be combined in arbitrary ways across different resolutions and concepts. For example, we can extract the plastic object detailed structure of concept <jane> and use it to generate other objects, such as a dog painting and the cat of Fig. \ref{fig:button_cat_inputs}.
\section{Conclusions and Future Work}
We showed how to learn multiple pseudo-words representing an input concept at different scales. This expands the prompt vocabulary and can be easily used with pre-trained text conditional diffusion models.
As future work, we would like to quantitatively measure if our method outperforms Textual Inversion and if models trained with diffusion processes beyond additive noise \citep{bansal2022cold, soft_diffusion} can
extract different aspects of scale, depending on how they corrupt their inputs.
\clearpage
\begin{ack}
This research has been supported by NSF Grants CCF 1763702,
AF 1901292, CNS 2148141, Tripods CCF 1934932, IFML CCF 2019844, the Texas Advanced Computing Center (TACC) and research gifts by Western Digital, WNCG IAP, UT Austin Machine Learning Lab (MLL), Cisco, Onassis Fellowship, Bodossaki Fellowship and the Archie Straiton Endowed Faculty Fellowship.
\end{ack}
| {'timestamp': '2022-12-01T02:18:16', 'yymm': '2211', 'arxiv_id': '2211.17115', 'language': 'en', 'url': 'https://arxiv.org/abs/2211.17115'} | arxiv |
\section{Introduction}
Causal inference using observational text data is increasingly popular across many research areas \citep{keith2020text}. It expands the range of research questions that can be explored when using text data across various fields, such as in the social and data sciences; adding to an extensive literature of text analysis methods and applications \citet{grimmer2013text_as_data,gentzkow2019text}.
Where randomized controlled trials are not possible, observational data might often be the only source of information and statistical methods need to be deployed to adjust for confounding biases. Text data can either serve as a proxy for otherwise unobserved confounding variables, be a confounding factor in itself, or even represent the treatment or outcome variable of interest.
\textbf{The framework:}
We consider the causal inference settings where we allow for the treatment variable to be binary, categorical or continuous. In our setting, text might be either a confounding factor or a proxy for a latent confounding variable. We also allow for additional non-text confounders (covariates). To the best of our knowledge, we are the first to provide such statistical inference framework.
Considering both text and numerical data jointly can not only improve prediction performance, but can be crucial for conducting unbiased statistical inference. When treatment and confounders are correlated with each other and with the outcome, the Frisch-Waugh-Lovell theorem \cite{frisch1933partial,lovell1963seasonal}, described in Section \ref{section:CEF}, implies that all regression weights must be estimated jointly, otherwise estimates will be biased. Text features themselves are `estimated data'. If they stem from supervised learning, which estimated the text features with respect to the outcome variable separately from the numerical features, then the resulting estimated (causal) effects will be biased.
\textbf{Our contributions:} With this paper, we introduce a Bayesian Topic Regression (BTR) framework that combines a Bayesian topic model with a Bayesian regression approach. This allows us to perform supervised representation learning for text features jointly with the estimation of regression parameters that include both treatment and additional numerical covariates. In particular, information about dependencies between outcome, treatment and controls does not only inform the regression part, but directly feeds into the topic modelling process.
Our approach aims towards estimating `causally sufficient' text representations in the spirit of \citet{veitch2020adapting}. We
show on both synthetic and semi-synthetic datasets that our BTR model recovers the ground truth more accurately than a wide range of benchmark models.
Finally, we demonstrate on two real-world customer review datasets - \emph{Yelp} and \emph{Booking.com} - that a joint supervised learning strategy, using both text and non-text features, also improves prediction accuracy of the target variable compared to a `two-step' estimation approach with the same models. This does not come at a cost of higher perplexity scores on the document modelling task. We also show that relatively simple supervised topic models with a linear regression layer that follow such joint approach can even compete with much more complex, non-linear deep neural networks that do not follow the joint estimation approach.
\section{Background and Related Work}\label{section:background}
\subsection{Causal Inference with Text}
\citet{egami2018make} and \citet{wood2018challenges} provide a comprehensive conceptional framework for inference with text and outline the challenges, focusing on text as treatment and outcome. In a similar vein, \citet{tan_2014,fong_grimmer_2016} focus on text as treatment. \citet{roberts2020adjusting, mozer2020} address adjustment for text as a confounder via text matching considering both topic and word level features.
\citet{veitch2020adapting} introduce a framework to estimate causally sufficient text representations via topic and general language models. Like us, they consider text as a confounder. Their framework exclusively focuses on binary treatment effects and does not allow for additional numerical confounders. We extend this framework.\\
\noindent \textbf{Causal inference framework with text:}
This general framework hinges on the assumption that through supervised dimensionality reduction of the text, we can identify text representations that capture the correlations with the outcome, the treatment and other control variables. Assume we observe iid data tuples $D_i = (y_i, r_i, \bs{W_i}, \bs{C_i})$, where for observation $i$, $y_i$ is the outcome, $t_i$ is the treatment, $\bs {W_i}$ is the associated text, and $\bs{C_i}$ are other confounding effects for which we have numerical measurements. Following the notational conventions set out in \cite{pearl_2009causality}, define the average treatment effect of the treated (ATT\footnote{depicted is the ATT of a binary treatment. The same logic applies for categorical or continuous treatments.}) as:
\begin{equation*}
\small
\begin{split}
\delta = \mathbb{E}[ y |\text{do}( t =1), t =1]-\mathbb{E}[ y | \text{do}( t =0), t =1].
\end{split}
\end{equation*}
In the spirit of \citet{veitch2020adapting}, we assume that our models can learn a supervised text representation $\bs{Z_i} = g(\bs{W_i},y_i,t_i,\bs{C_i})$, which in our case, together with $\bs{C_i}$ blocks all `backdoor path' between $y_i$ and $t_i$, so that we can measure the casual effect
\begin{equation}
\small
\delta = \mathbb{E}[\mathbb{E}[y| \bs{Z},\bs{C},t = 1] - \mathbb{E}[y|\bs{Z},\bs{C},t=1] | t=1 ]. \nonumber
\end{equation}
Intuitively, to obtain such $\bs{Z_i}$ and consequently an unbiased treatment effect, one should estimate the text features in a supervised fashion taking into account dependencies between $\bs{W_i}$, $y_i$, $t_i$, and $\bs{C_i}$.
\subsection{\textbf{Estimating Conditional Expectations}} \label{section:CEF}
To estimate the ATT, we need to compute the conditional expectation function (CEF): $\mathbb{E}[\bs y| \bs t,\bs{Z}, \bs{C}]$. Using regression to estimate our conditional expectation function, we can write
\begin{equation}\label{eq_cef_general}
\mathbb{E}[\bs y | \bs t,\bs{Z}, \bs{C}] = f(\bs t,g(\bs{W,\bs y, \bs t, \bs C}; \Theta),\bs{C}; \bs{\Omega}).
\end{equation}
Let $f()$ be the function of our regression equation that we need to define, and $\bs{\Omega}$ be the parameters of it. Section \ref{section_sup_topic_rep} covers text representation function $g()$. For now,
let us simply assume that we obtain $\bs Z$ in a joint supervised estimation with $f()$. The predominant assumption in causal inference settings in many disciplines is a linear causal effect assumption. We also follow this approach, for the sake of simplicity. However, the requirement for joint supervised estimation of text representations $\bs{Z}$ to be able to predict $\bs y$, $\bs t$ (and if relevant $\bs{C}$) to be considered `causally sufficient' is not constrained to the linear case \cite{veitch2020adapting}. Under the linearity assumption, the CEF of our regression can take the form
\begin{equation}\label{eq_linear_reg_ci}
\bs y = \mathbb{E}[\bs y| \bs t,\bs{Z}, \bs{C}] + \epsilon = \bs{t} \omega_t + \bs{Z} \bs{\omega_Z}+ \bs{C}\bs{\omega_C} + \epsilon,
\end{equation}
where $\epsilon \sim N(0,\sigma_\epsilon^2)$ is additive i.i.d. Gaussian. When the CEF is causal, the regression estimates are causal \cite{angrist2008mostly}. In such a case, $\omega_t$ measures the treatment effect.
\noindent \textbf{Regression Decomposition theorem:} The Frisch-Waugh-Lovell (FWL) theorem \citep{frisch1933partial,lovell1963seasonal}, implies that the supervised learning of text representations $\bs Z$ and regression coefficients $\bs \omega$ cannot be conducted in separate stages, but instead must be learned jointly.
The FWL theorem states that a regression such as in \eqref{eq_linear_reg_ci} can only be decomposed into separate stages, and still obtain mathematically unaltered coefficient estimates, if for each partial regression, we were able to residualize both outcome and regressors with respect to all other regressors that have been left out. In general, for a regression such as
$
\bs y = \bs X \bs{\omega} + \bs \epsilon,
$
we have a projection matrix
$
\bs P = \bs X(\bs X^\intercal \bs X )^{-1}\bs X^\intercal
$
that produces projections $\bs{\widehat{y}}$ when applied to $\bs y$.
Likewise, we have a `residual maker' matrix $\bs M$ which is $\bs P$'s complement
$
\bs M = \bs I - \bs P.
$
FWL says that if we could estimate
\begin{equation}\label{eq_fwl_alt}
\bs M_{c,z} \bs{y} = \bs{M}_{c,z} \bs{t}\hat{\omega}_t + \hat{\epsilon},
\end{equation}
the estimates $\hat{\omega}_t$ of treatment effect $\omega_t$ in equations \eqref{eq_linear_reg_ci} and \eqref{eq_fwl_alt} would be mathematically identical (full theorem and proof in Appendix \ref{section:app_ci_text}). Here, $\bs M_{c,z}$ residualizes $\bs t$ from confounders $\bs C$ and $\bs Z$. This is however infeasible, since $\bs Z$ itself must be estimated in a supervised fashion, learning the dependencies towards $\bs y$, $\bs t$ and $\bs C$.
Equation \eqref{eq_linear_reg_ci} must therefore be learned jointly, to infer $\bs Z$ and the CEF in turn.
An approach in several stages in such a setup cannot fully residualize $\bs t$ from all confounders and estimation results would therefore be biased. What is more, if incorrect parameters are learned, out of sample prediction might also be worse. We demonstrate this both on synthetic and semi-synthetic datasets (section \ref{section:synthetic_data} and \ref{section:semi_synthetic_data}).
\subsection{Supervised topic representations}\label{section_sup_topic_rep}
Topic models are a popular choice of text representation in causal inference settings \citep{keith2020text} and in modelling with text as data in social sciences in general \citep{gentzkow2019text}. We focus on this text representation approach for function $g()$
in our joint modelling strategy.
\textbf{BTR:} We create BTR, a fully Bayesian supervised topic model that can handle numeric metadata as regression features and labels. Its generative process builds on LDA-based models in the spirit of \citet{blei_mcauliffe2008supervised}.
Given our focus on causal interpretation, we opt for a Gibbs Sampling implementation. This provides statistical guarantees of providing asymptotically exact samples of the target density while (neural) variational inference does not \cite{robertcasella2013MCMC}. \citet{blei2017variational_review} point out that MCMC methods are preferable over variational inference when the aim of the task is to obtain asymptotically precise estimates.
\textbf{rSCHOLAR:} SCHOLAR \cite{card_2018_SCHOLAR} is a supervised topic model that generalises both sLDA \citep{blei_mcauliffe2008supervised} as it allows for predicting labels, and SAGE \cite{sage_2011} which handles jointly modelling covariates via `factorising' its topic-word distributions ($\beta$) into deviations from the background log-frequency of words and deviations based on covariates. SCHOLAR is solved via neural variational inference \cite{KingmaWellingVAE14, rezende14}. However, it was not primarily designed for causal inference. We extend SCHOLAR with a linear regression layer (rSCHOLAR) to allow direct comparison with BTR. That is, its downstream layer is
$
\bs y =\bs A \bs \omega,
$
where $\bs A = [\bs t, \bs C, \bs \theta]$ is the design matrix in which $\bs \theta$ represents the estimated document-topic mixtures. $\bs \omega$ represents the regression weight vector. This regression layer is jointly optimized with the main SCHOLAR model via backpropagation using ADAM \cite{kingma_2015_ADAM}, replacing the original downstream cross-entropy loss with mean squared error loss.
Other recent supervised topic models that can handle covariates are for example STM \cite{roberts2016model} and DOLDA \cite{dolda2020}. DOLDA was not designed for regression nor for causal inference setups. Topics models in the spirit of STM incorporate document metadata, but in order to better predict the content of documents rather than to predict an outcome. Many approaches on supervised topic models for regression have been suggested over the years. \cite{blei_mcauliffe2008supervised} optimize their sLDA model with respect to the joint likelihood of the document data and the response variable using VI. MedLDA \cite{zhu2012medlda} optimizes with respect to the maximum margin principle, Spectral-sLDA \cite{wang2014spectral} proposes a spectral decomposition algorithm, and BPsLDA \cite{chen_bpslda_2015} uses backward propagation over a deep neural network. Since BPsLDA reports to outperform sLDA, MedLDA and several other models, we include it in our benchmark list for two-stage models. We include a Gibbs sampled sLDA to have a two-stage model in the benchmark list that is conceptually very similar to BTR in the generative topic modelling part. Unsupervised LDA \cite{blei2003latent, griffiths2004finding} and a neural topic model counterpart GSM \cite{miao2017discovering} are also added for comparison.
\section{Bayesian Topic Regression Model} \label{section:model}
\subsection{Regression Model}\label{section_reg_model}
We take a Bayesian approach and jointly estimate $f()$ and $g()$ to solve equation \eqref{eq_linear_reg_ci}. To simplify notation, encompass numerical features of treatment $\bs t$ and covariates $\bs C$ in data matrix $\bs{X} \in \mathbb{R}^{D \times (1 + \text{dim}_C)}$. All estimated topic features are represented via $\bs{\bar{Z}} \in \mathbb{R}^{D \times K}$, where $K$ is the number of topics. Finally, $\bs y \in \mathbb{R}^{D \times 1}$ is the outcome vector. Define $\bs A=[\bs{\bar{Z}}, \bs X]$ as the overall regression design matrix containing all features (optionally including interaction terms between topics and numerical features).
With our fully Bayesian approach, we aim to better capture feature correlations and model uncertainties. In particular, information from the numerical features (labels, treatment and controls) directly informs the topic assignment process as well as the regression. This counters bias in the treatment effect estimation, following the spirit of `causally sufficient' text representations \cite{veitch2020adapting}.
Following the previous section, we outline the case for $f()$ being linear. Our framework could however be extended to non-linear $f()$.
Assuming Gaussian iid errors $\bs{\epsilon} \sim \mathcal{N}(\bs 0,\sigma^2\bs{I})$, the model's regression equation is then $\bs{y} = \bs{A}\bs{\omega} + \bs{\epsilon}$, such that
\begin{equation} \label{eq_regression}
\small
p(\bs{y}| \bs{A},\bs{\omega},\sigma^2) = \mathcal{N}(\bs{y}|\bs{A}{\bs{\omega}}, \sigma^2\bs{I}). \end{equation}
The likelihood with respect to outcome $\bs{y}$ is then
\begin{equation}\label{eq_likelihood}
\small
p(\bs{y}| \bs{A},\bs{\omega},\sigma^2) = \prod_{d=1}^{D} \mathcal{N}(y_d | \bs{a}_d \bs{\omega}, \sigma^2\bs{I}),
\end{equation}
where $\bs{a}_d$ is the $d$th row of design matrix $\bs{A}$.
We model our prior beliefs about parameter vector $\bs{\omega}$ by a Gaussian density
\begin{equation}\label{omega_priors} \small
p(\bs{\omega}) = \mathcal{N}(\bs{\omega}|\bs{m}_0, \bs{S}_0)
\end{equation}
where mean $\bs{m}_0$ and covariance matrix $\bs{S}_0$ are hyperparameters. Following \citet{bishop2006}, we place an Inverse-Gamma prior on the conditional variance estimate $\sigma^2$ with shape and scale
hyperparameters $a_0$ and $b_0$
\begin{equation}\label{inv_gamma}
\small
p(\sigma^2) = \mathcal{IG}(\sigma^2 | a_0,b_0).
\end{equation}
Placing priors on all our regression parameters allows us to conduct full Bayesian inference, which not only naturally counteracts parameter over-fitting but also provides us with well-defined posterior distributions over $\bs{\omega}$ and $\sigma^2$ as well as a predictive distribution of our response variable.
Due to the conjugacy of the Normal-Inverse-Gamma prior, the regression parameters' posterior distribution has a known Normal-Inverse-Gamma distribution \cite{stuart1994kendall}
\begin{equation} \label{eq:omega_posterior}
\small
\begin{split}
p(\bs{\omega},\sigma ^{2} | & \bs{y}, \bs{A} ) \propto
p(\bs{\omega} | \sigma^{2},\bs{y} ,\bs{A} )p (\sigma ^{2}\mid \bs{y}, \bs{A}) \\
= & \mathcal{N}\left(\bs{\omega} | \bs{m}_{n},\sigma ^{2}\bs{S}_{n}^{-1}\right) {\mathcal{IG}}\left(\sigma^2 | a_{n},b_{n}\right).
\end{split}
\end{equation}
$\bs{m}_{n}$, $\bs{S}_{n}$, $a_{n}$, $b_{n}$ follow standard updating equations for a Bayesian linear regression (Appendix \ref{section:app_reg_model}).
\subsection{Topic Model}\label{section_topic_model}
The estimated topic features $\bs{\bar{Z}}$, which form part of the design regression matrix $\bs{A}$, are generated from a supervised model that builds on an LDA-based topic structure \cite{blei2003latent}. Figure \ref{fig:btr_graph} provides a graphical representation of BTR and brings together our topic and regression model.
We have $d$ documents in a corpus of size $D$, a vocabulary of $V$ unique words and $K$ topics. A document has $N_d$ words, so that $w_{d,n}$ denotes the $n$th word in document $d$. The bag-of-words representation of a document is $\bs w_d = [w_{d,1},\dots,w_{d,N_d}]$, so that the entire corpus of documents is described by $\bs{W} = [\bs{w}_1,\dots,\bs{w}_D]$. $z_{d,n}$ is the topic assignment of word $w_{d,n}$, where $\bs{z}_d$ and $\bs{Z}$ mirror $\bs{w}_d$ and $\bs{W}$ in their dimensionality. Similarly, $\bs{\bar{z}}_d$ denotes the estimated average topic assignments of the $K$ topics across words in document $d$, such that $\bs{\bar{Z}}=[\bs{\bar{ z}_1},\dots,\bs{\bar{z}_D}]^\intercal \in \mathbb{R}^{D \times K}$. $\bs{\beta} \in \mathbb{R}^{K \times V}$, describes the $K$ topic distributions over the $V$ dimensional vocabulary.
$\bs{\theta} \in \mathbb{R}^{D \times K}$ describes the $K$ topic mixtures for each of the $D$ documents.
$\eta \in \mathbb{R}^{V}$ and $\alpha \in \mathbb{R}^K$ are the respective hyperparameters of the prior for $\bs{\beta}$ and $\bs{\theta}$.
The generative process of our BTR model is then:
\begin{enumerate}[topsep=0.8pt,itemsep=0.2ex,partopsep=0ex,parsep=0.15ex]
\item $\bs{\omega} \sim \mathcal{N}(\bs{\omega} | \bs{m}_0, \bs{S}_0)$ and $\sigma^2 \sim \mathcal{IG}(\sigma^2 | a_0,b_0)$
\item \textbf{for} $k = 1,\dots,K$:
\begin{enumerate} [topsep=0pt,itemsep=-1ex,partopsep=0ex,parsep=1ex]
\item $\bs{\beta}_k \sim \text{Dir}(\eta)$
\end{enumerate}
\item \textbf{for} {$d = 1,\dots,D$}:
\begin{enumerate} [topsep=0pt,itemsep=-1ex,partopsep=0ex,parsep=1ex]
\item $\bs{\theta}_d \sim \text{Dir}(\alpha)$
\item \textbf{for} {$n = 1,\dots,N_d$}:
\begin{enumerate}[topsep=-3pt,itemsep=-0.0ex,partopsep=0ex,parsep=0ex]
\item topic assignment $z_{d,n} \sim Mult(\bs{\theta}_d)$
\item term $w_{d,n} \sim Mult(\bs{\beta}_{z_{d,n}})$
\end{enumerate}
\end{enumerate}
\item $\bs{y} \sim \mathcal{N}\left(\bs{A}\bs{\omega}, \sigma^2\bs{I} \right)$.
\end{enumerate}
Straightforward extensions also allow multiple documents per observation or observations without documents, as is described in Appendix \ref{section_obs_wo_docs}.
\begin{figure}
\centering
\resizebox{6.8cm}{2.55cm}{
\begin{tikzpicture}
\node[obs] (alpha) {$\alpha$}; %
\node[latent,right=of alpha ] (theta) {$\bs{\theta}_d$}; %
\node[latent,right=of theta ] (z) {$z_{d,n}$}; %
\node[obs, right=of z] (w) {$w_{d,n}$};%
\node[latent,right=of w,yshift= 0cm,fill] (beta) {$\bs{\beta}_k$}; %
\node[obs,right=of beta,xshift=0cm,fill] (eta) {$\eta$}; %
\node[obs, below=of z, xshift = 0cm, ] (y) {$y_d$};%
\node[obs, below=of theta, yshift = 0.5cm, ] (x) {$\bs{x}_d$};%
\node[latent,below=of beta,xshift=0cm] (omega) {$\omega_l$}; %
\node[obs,right=of omega,xshift=0cm] (m) {$m_0, S_0$}; %
\node[latent,below=of alpha,yshift=-0.7cm] (sigma) {$\sigma^2$}; %
\node[obs,above=of sigma,yshift=-0.5cm] (sigma_priors) {$a_0, b_0$}; %
\plate [inner sep=.45cm,yshift=.2cm] {plateD} {(theta)(z)(w)(y)(x)} {$D$}; %
\plate [inner sep=.25cm,yshift=.2cm] {plateN} {(z)(w)} {$N_d$};
\plate [inner sep=.25cm,yshift=.2cm] {plateN} {(beta)} {$K$};
\plate [inner sep=.25cm,yshift=.2cm] {plateL} {(omega)} {$L$};
\edge {alpha} {theta}
\edge {theta} {z}
\edge {z} {w}
\edge {beta} {w}
\edge {eta} {beta}
\edge {x} {y}
\edge {z} {y}
\edge {omega} {y}
\edge{m} {omega}
\edge{sigma} {y}
\edge{sigma_priors} {sigma}
\end{tikzpicture}
}
\caption{Graphical model for BTR.}
\label{fig:btr_graph}
\end{figure}
\section{Estimation}
\subsection{Posterior Inference}
The objective is to identify the latent topic structure and regression parameters that are most probable to have generated the observed data. We obtain the joint distribution for our graphical model through the product of all nodes conditioned only on their parents, which for our model is
\begin{equation}\label{joint}
\small
\begin{split}
p(\bs{\theta} &, \bs{\beta}, \bs{Z}, \bs{W}, \bs{y}, \bs{\omega}, \sigma^2| \bs{X}, \alpha, \eta, \bs{m}_0, \bs{S}_0, a_0, b_0) = \\
\prod_{d=1}^D & p(\bs{\theta}_d | \alpha) \prod_{k=1}^K p (\bs{\beta}_k | \eta) \prod_{d=1}^D \prod_{n=1}^{N_d} p(z_{d,n} | \bs{\theta}_d)
p(w_{d,n} |z_{d,n}, \bs{\beta}) \\
\prod_{d=1}^D &p(y_d | \bs{x}_d, \bs{z}_d, \bs{\omega}, \sigma^2) \prod_{l=1}^{L} p(\bs{\omega}_{l}|\bs{m}_0, \bs{S}_0) p(\sigma^2 | a_0, b_0).
\end{split}
\end{equation}
The inference task is thus to compute the posterior distribution of the latent variables ($\bs{Z}$, $\bs{\theta}$, $\bs{\beta}$, $\bs{\omega}$, and $\sigma^2$) given the observed data ($\bs{y}$, $\bs{X}$ and $\bs{W}$) and the priors governed by hyperparameters ($\alpha, \eta$, $\bs{m}_0,\bs{S}_0,a_0,b_0$). We will omit hyperparameters for sake of clarity unless explicitly needed for computational steps. The posterior distribution is then
\begin{equation}\label{posterior} \small
p(\bs{\theta}, \bs{\beta}, \bs{Z}, \bs{\omega}, \sigma^2 | \bs{W}, \bs{y}, \bs{X}) = \frac{p(\bs{\theta}, \bs{\beta}, \bs{Z}, \bs{W}, \bs{X}, \bs{y}, \bs{\omega}, \sigma^2 )}{p(\bs{W},\bs{X},\bs{y})}.
\end{equation}
In practice, computing the denominator in equation \eqref{posterior}, i.e. the evidence, is intractable due to the sheer number of possible latent variable configurations.
We use a Gibbs EM algorithm \cite{levine2001implementations} set out below, to approximate the posterior. Collapsing out the latent variables $\bs{\theta}$ and $\bs{\beta}$ \cite{griffiths2004finding}, we only need to identify the sampling distributions for topic assignments $\bs{Z}$ and regression parameters $\bs{\omega}$ and $\sigma^2$, conditional on their Markov blankets
\begin{equation}
\small
\begin{split}
& p(\bs{Z}, \bs{\omega}, \sigma^2 | \bs{W}, \bs{X}, \bs{y}) = \\
& p(\bs{Z} | \bs{W}, \bs{X}, \bs{y}, \bs{\omega}, \sigma^2)p(\bs{\omega}, \sigma^2 | \bs{Z}, \bs{X}, \bs{y}).
\end{split}
\end{equation}
Once topic assignments $\bs{Z}$ are estimated, it is straightforward to recover $\bs{\beta}$ and $\bs{\theta}$. The expected topic assignments are estimated by Gibbs sampling in the E-step, and the regression parameters are estimated in the M-step.
\subsection{E-Step: Estimate Topic Parameters} \label{section:E_Step}
In order to sample from the conditional posterior for each $z_{d,n}$ we need to identify the probability of a given word $w_{d,n}$ being assigned to a given topic $k$, conditional on the assignments of all other words (as well as the model's other latent variables and the observed data)
\begin{equation}
\small
p(z_{d,n} = k | \bs{Z}_{-(d,n)}, \bs{W}, \bs{X}, \bs{y}, \bs{\omega}, \sigma^2),
\end{equation}
where $\bs{Z}_{-(d,n)}$ are the topic assignments of all words apart from $w_{d,n}$. This section defines this distribution, with derivations in Appendix \ref{section:app_topic_model}. By conditional independence properties of the graphical model, we can split this joint posterior into
\begin{equation}
\small \label{sLDA_cov_posterior_form}
p(\bs{Z}|\bs{W}, \bs{X}, \bs{y}, \bs{\omega}, \sigma^2) \propto p(\bs{Z}|\bs{W}) p(\bs{y}|\bs{Z}, \bs{X}, \bs{\omega}, \sigma^2).
\end{equation}
Topic assignments within one document are independent from topic assignments in all other documents and the sampling equation for $z_{d,n}$ only depends on it's own response variable $y_d$, hence
\begin{equation}
\label{eq:z_sampling_form}
\small
\begin{split}
& p(z_{d,n} = k | \bs{Z}_{-(d,n)}, \bs{W}, \bs{X}, \bs{y}, \bs{\omega}, \sigma^2) \propto \\
& p(z_{d,n} = k | \bs{Z}_{-(d,n)}, \bs{W}) p(y_d|z_{d,n}=k, \bs{Z}_{-(d,n)}, \bs{x}_d, \bs{\omega}, \sigma^2).
\end{split}
\end{equation}
The first part of the RHS expression is the sampling distribution of a standard LDA model. Following \citet{griffiths2004finding}, we can express it in terms of count variables $s$ (topic assignments across a document) and $m$ (assignments of unique words across topics over all documents).\footnote{For example, $s_{d,k}$ denotes the total number of words in document $d$ assigned to topic $k$ and $s_{d,k,-n}$ the number of words in document $d$ assigned to topic $k$, except for word $n$. Analogously, $m_{k,v}$ measures the total number of times term $v$ is assigned to topic $k$ across all documents and $m_{k,v,-(d,n)}$ measures the same, but excludes word $n$ in document $d$.}
The second part is the predictive distribution for $y_d$. This is a Gaussian distribution depending on the linear combination $\bs{\omega}(\bs{a}_d|z_{d,n} = k)$, where $\bs{a}_d$ includes the topic proportions $\bs{\bar{z}}_d$ and $\bs{x}_d$ variables (and any interaction terms), conditional on $z_{d,n} = k$. We can write this in a convenient form that preserves proportionality with respect to $z_{d,n}$ and depends only on the data and the count variables.
First, we split the $\bs{X}$ features into those that are interacted, $\bs{X}_{1,d}$, and those that are not, $\bs{X}_{2,d}$ such that the generative model for $y_d$ is then
\begin{equation}
\small
y_d \sim \mathcal{N}(\bs{\omega}_z^\intercal \bs{\bar{z}}_{d} + \bs{\omega}_{zx}^\intercal (\bs{x}_{1,d} \otimes \bs{\bar{z}}_d) + \bs{\omega}_x^\intercal \bs{x}_{2,d}, \sigma^2),
\end{equation}
where $\otimes$ is the Kronecker product.
Define $\bs{\tilde{\omega}}_{z,d}$ as a length $K$ vector such that
\begin{equation}
\small
\tilde{\omega}_{z,d,k} = \omega_{z,k} + \bs{\omega}_{zx,k}^\intercal \bs{x}_{1,d}.
\end{equation}
Noting that $\bs{\tilde{\omega}}_{z,d}^\intercal \bs{\bar{z}}_d = \frac{\bs{\tilde{\omega}}_{z,d}^\intercal}{N_d}(\bs{s}_{d,-n} + s_{d,n})$, gives us the sampling distribution for $z_{d,n}$ stated in equation \eqref{eq:z_sampling_form}: a multinomial distribution parameterised by
\begin{align} \scriptsize
& p(z_{d,n} = k | z_{-(d,n)}, W,X,y, \alpha, \eta, \omega, \sigma^2) \propto \nonumber \\
& (s_{d,k, -n } + \alpha) \times
\frac{m_{k,v, -(d,n)} +\eta}{\sum_v m_{k,v, -(d,n)} +V \eta} \nonumber \\
& \exp \Bigg\{ \frac{1}{2 \sigma^2} \bigg( \frac{2 \tilde{\omega}_{z,d,k}}{N_d} \left(y_d - \nonumber \bs{\omega}_x^\intercal \bs{x}_{2,d} - \frac{\bs{\tilde{\omega}}_{z,d}^\intercal}{N_d}\bs{s}_{d,-n}\right) \nonumber \\
& - \left(\frac{\tilde{\omega}_{z,d,k}}{N_d} \right) ^2 \bigg) \Bigg\}.
\end{align}
This defines the probability for each $k$ that $z_{d,n}$ is assigned to that topic $k$. These $K$ probabilities define the multinomial distribution from which $z_{d,n}$ is drawn.
\subsection{M-Step: Estimate Regression Parameters}
To estimate the regression parameters, we hold the design matrix $\bs{A} = [\bs{\bar{Z}},\bs{X}]$ fixed. Given the Normal-Inverse-Gamma prior, this is a standard Bayesian linear regression problem and the posterior distribution for which is given in equation \eqref{eq:omega_posterior} above. To prevent overfitting to the training sample there is the option to randomly split the training set into separate sub-samples for the E- and M-steps, following a Cross-Validation EM approach \cite{shinozaki2007cross}. We use the prediction mean squared error from the M-step sample to assess convergence across EM iterations.
\subsection{Implementation}
We provide an efficient \textit{Julia} implementation for BTR and a \textit{Python} implementation for rSCHOLAR on Github to allow for reproducibility of the results in the following experiment sections.\footnote{BTR: \href{https://github.com/julianashwin/BTR.jl}{github.com/julianashwin/BTR.jl} \\ rSCHOLAR: \href{https://github.com/MaximilianAhrens/scholar4regression}{github.com/MaximilianAhrens/scholar4regression}}
\section{Experiment: Synthetic Data}\label{section:synthetic_data}
\subsection{Synthetic Data Generation}
To illustrate the benefits of our BTR approach, we generate a synthetic dataset of documents which have explanatory power over a response variable, along with an additional numerical covariate that is correlated with both documents and response.
\begin{figure*}[t!]
\centering
\begin{subfigure}{0.25\textwidth}
\includegraphics[width=\linewidth]{images/synth/synth_BTR.pdf}
\label{fig:synth_btr}
\end{subfigure}\hfil
\begin{subfigure}{0.25\textwidth}
\includegraphics[width=\linewidth]{images/synth/synth_SCHOLAR.pdf}
\label{fig:synth_scholar}
\end{subfigure}\hfil
\begin{subfigure}{0.25\textwidth}
\includegraphics[width=\linewidth]{images/synth/synth_LR_sLDA.pdf}
\label{fig:synth_lr_slda}
\end{subfigure}
\medskip
\begin{subfigure}{0.25\textwidth}
\includegraphics[width=\linewidth]{images/synth/synth_LR_BPsLDA.pdf}
\label{fig:synth_lr_bpslda}
\end{subfigure}\hfil
\begin{subfigure}{0.25\textwidth}
\includegraphics[width=\linewidth]{images/synth/synth_sLDA_LR.pdf}
\label{fig:synth_slda_lr}
\end{subfigure}\hfil
\begin{subfigure}{0.25\textwidth}
\includegraphics[width=\linewidth]{images/synth/synth_BPsLDA_LR.pdf}
\label{fig:synth_bpslda_lr}
\end{subfigure}
\caption{Comparing recovery of true regression weights across different topic models. For each panel, the true regression weights are shown as red points and the estimated $95\%$ posterior credible (or bootstrap, depending on model) interval in blue. Only BTR contains the true weights within the estimated intervals.}
\label{fig:synth_data_model_comparion}
\end{figure*}
We generate $10,000$ documents of $50$ words each, following an LDA generative process, with each document having a distribution over three topics, defined over a vocabulary of 9 unique terms. A numerical feature, $\bs{x}=[x_1,...,x_D]^\intercal $, is generated by calculating the document-level frequency of the first word in the vocabulary. As the first topic places a greater weight on the first three terms in the vocabulary, $\bs{x}$ is positively correlated with $\bs{\bar{z}}_{1}$. The response variable $\bs{y}=[y_1,...,y_D]$ is generated through a linear combination of the numerical feature $\bs{x}$ and the average topic assignments $\bs{\bar{Z}}=\{\bs{\bar{z}}_{1},\bs{\bar{z}}_{2},\bs{\bar{z}}_{3}\}$,
\begin{equation} \label{eq:y_gen}
\small
\bs{y} = - \bs{\bar{z}}_{1} + \bs{x} + \bs{\epsilon}.
\end{equation}
where $\bs{\epsilon}$ is an iid Gaussian white noise term. The regression model to recover the ground truth is then
\begin{equation} \label{eq:y_gen}
\small
\bs y = \omega_1 \bs{\bar{z}}_{1} + \omega_2 \bs{\bar{z}}_{2} + \omega_3 \bs{\bar{z}}_{3} + \omega_4 \bs x_{d} + \bs{\epsilon}.
\end{equation}
The \textit{true} regression weights are thus $\bs{\omega}^* = [-1, 0, 0,1]$. In accordance with the FWL theorem, we cannot recover the true coefficients with a two-stage estimation process.
\subsection{Synthetic Data Results}\label{section:synth_results}
We compare the ground truth of the synthetic data generating process against: (1) \textbf{BTR:} our Bayesian model, estimated via Gibbs sampling. (2) \textbf{rSCHOLAR}: the regression extension of SCHOLAR, estimated via neural VI. (3) \textbf{LR-sLDA:} first linearly regress $\bs{y}$ on $\bs{x}$, then use the residual of that regression as the response in an sLDA model, estimated via Gibbs sampling. (4) \textbf{sLDA-LR:} First sLDA, then linear regression. (5) \textbf{BPsLDA-LR} and (6)\textbf{ LR-BPsLDA:} replace sLDA with BPsLDA, which is sLDA estimated via the backpropagation approach of \citet{chen_bpslda_2015}.
Figure \ref{fig:synth_data_model_comparion} shows the true and estimated regression weights for each of the six models. LR-sLDA and sLDA-LR estimate inaccurate regression weights for both the text and numerical features, as do the BPsLDA variants. Similarly, rSCHOLAR fails to recover the ground truth. However, BTR estimates tight posterior distributions around to the true parameter values. The positive correlation between $\bs{z}_{1}$ and $\bs{x}$ makes a joint estimation approach crucial for recovering the true parameters. Standard supervised topic models estimate the regression parameters for the numerical features separately from the topic proportions and their associated regression parameters, violating the FWL theorem as outlined in section \ref{section:CEF}. A key difference between rSCHOLAR and BTR lies in their posterior estimation techniques (neural VI vs Gibbs). rSCHOLAR's approach seems to have a similarly detrimental effect as the two-stage approaches. We suspect further research into (neural) VI assumptions and their effect on causal inference with text could be fruitful.
\section{Experiment: Semi-Synthetic Data} \label{section:semi_synthetic_data}
\subsection{Semi-Synthetic Data Generation}
We further benchmark the models' abilities to recover the ground truth on two semi-synthetic datasets. We still have access to the ground truth (GT) as we either synthetically create or directly observe the correlations between treatment, confounders and outcome. However, the text and some numeric metadata that we use is empirical. We use customer review data from \textbf{(i) Booking.com}\footnote{Available at \href{https://www.kaggle.com/jiashenliu}{kaggle.com/jiashenliu}} and \textbf{(ii) Yelp}\footnote{Available at \href{https://www.yelp.com/dataset}{yelp.com/dataset}, Toronto subsample}, and analyse two different `mock' research questions. For both datasets, we randomly sample $50,000$ observations and select $75\%$ in Yelp, $80\%$ in Booking for training.\footnote{Appendix \ref{section_app_real_world_data} for full data summary statistics. Data samples used for experiments available via: \href{https://github.com/MaximilianAhrens/data}{github.com/MaximilianAhrens/data}}
\\~\\
\noindent \textbf{Booking:}
\textit{Do people give more critical ratings ($y_i$) to hotels that have high historic ratings ($av\_score_i$), once controlling for review texts?}
\begin{equation}
\small
GT_B:\quad y_i = - \text{hotel\_av}_i + 5\text{prop\_pos}_i
\end{equation}
where $\text{prop\_pos}_i$ is the proportion of positive words in a review. The textual effect is estimated via topic modelling in our experiment. The treatment in question is the average historic customer rating, being modelled as continuous.
\\~\\
\noindent \textbf{Yelp:}
\textit{Do people from the US ($\text{US}_i$=1) give different Yelp ratings ($y_i$) than customers from Canada ($\text{US}_i$=0), controlling for average restaurant review ($\text{stars\_av\_b}_i$) and the review text?}
\begin{equation}
\small
GT_Y: y_i = - \text{US}_i + \text{stars\_av\_b}_i + sent_i.
\end{equation}
To create the binary treatment variable $\text{US}_i$, we compute each review's sentiment score ($sent_i$) using the Harvard Inquirer. This treatment effect is correlated with the text as
\begin{equation}
\small
\Pr(US_i = 1) = \frac{\exp(\gamma_1 sent_i)}{1 + \exp(\gamma_1 sent_i)},
\end{equation}
where $\gamma_1$ controls the correlation between text and treatment.\footnote{When $\gamma_1 =1 $, correlation between $US_i$ and $sent_i$ is $0.23$. For $\gamma_1 =0.5$ it is $0.39$.}
\begin{figure*}
\centering
\subfloat{
\includegraphics[trim=0cm 0 0 0, clip, height = 0.7 \columnwidth]{images/semi_synth/Booking_TEs.pdf}}
\subfloat{
\includegraphics[trim=2.1cm 0 0 0, clip, height = 0.7 \columnwidth]{images/semi_synth/Yelp_gamma1.0.pdf}}
\subfloat{
\includegraphics[trim=2.1cm 0 0 0, clip, height = 0.7 \columnwidth]{images/semi_synth/Yelp_gamma0.5.pdf}}
\caption{Estimated TE semi-synthetic Booking (left panel), Yelp (middle and right panel). Intervals are either 95\% credible interval of posterior distribution, or based on 20 run bootstrap, depending on model.}
\label{fig:groundtruth_semi_synth}
\end{figure*}
\subsection{Semi-Synthetic Data Results}
On both semi-synthetic datasets and across all benchmarked models, BTR estimates the regression weights that are the closest to the ground truth. This consistently holds true across all tested numbers of topics $K$ (see Figure \ref{fig:groundtruth_semi_synth}). For Yelp, we also vary the correlation strength between treatment and confounder. The middle panel in Figure \ref{fig:groundtruth_semi_synth} shows the estimation results with a very high correlation between confounder and treatment ($\gamma_1 = 1$). The RHS panel shows the results when this correlation is lower ($\gamma_1 = 0.5$). As expected, a higher correlation between confounder and treatment increases the bias as outlined in the section \ref{section:CEF}. If the correlation between confounder and treatment is zero, a two-stage estimation approach no longer violates FWL and all models manage to estimate the ground truth (see Appendix \ref{section:app_semisynth}). Since the topic modelling approach is an approximation to capture the true effect of the text and its correlation with the metadata - and since this approximation is not perfect - some bias may remain. Overall, BTR gets substantially closer to the ground truth than any other model.
\section{Experiment: Real-World Data}\label{section:emp_experiments}
\begin{table}[t]
\centering
\resizebox{\linewidth}{!}{
\begin{tabular}{@{\extracolsep{0pt}} lcc}
\toprule
\textit{Dataset} & \multicolumn{2}{c}{Booking}\\
\midrule
\textit{K} & 50 & 100\\
\midrule
{$pR^2$ (higher is better)} \\
\midrule
OLS & \multicolumn{2}{c}{0.315} \\
aRNN & \multicolumn{2}{c}{0.479 (0.007)} \\
LR+ TAM & 0.479 (0.014) & 0.487 (0.014)\\
LDA+LR & 0.426 (0.003) & 0.437 (0.002) \\
GSM+LR & 0.386 (0.004) & 0.395 (0.005)\\
LR+sLDA & 0.432 (0.002) & 0.438 (0.004)\\
LR+BPsLDA & 0.419 (0.009) & 0.455 (0.001)\\
LR+rSCHOLAR & 0.469 (0.002) & 0.465 (0.002)\\
\textbf{rSCHOLAR} & \textbf{0.494} (0.004)& \textbf{0.489} (0.003)\\
\textbf{BTR} & 0.454 (0.003)& 0.460 (0.002)\\
\bottomrule
\\[-1.8ex]
{Perplexity (lower is better)} \\
\midrule
LR+TAM & 521 (2) & 522 (2)\\
LDA+LR & 454 (1) & 432 (1)\\
GSM+LR & \textbf{369} (8) & \textbf{348} (5) \\
LR+sLDA & 436 (2) & 411 (1) \\
LR+rSCHOLAR & 441 (20) & 458 (11)\\
\textbf{rSCHOLAR} & 466 (19) & 464 (9) \\
\textbf{BTR} & 437 (1) & 412 (1) \\
\bottomrule
\end{tabular}}
\caption{Booking: mean $pR^2$ and perplexity, standard deviation in brackets. 20 model runs. Best model \textbf{bold}.}
\label{tab:results_empirical}
\end{table}
\begin{table}[t]
\centering
\resizebox{\linewidth}{!}{
\begin{tabular}{@{\extracolsep{0pt}} lcc}
\toprule
\textit{Dataset} & \multicolumn{2}{c}{Yelp} \\
\midrule
\textit{K} & 50 & 100 \\
\midrule
{$pR^2$ (higher is better)} \\
\midrule
OLS & \multicolumn{2}{c}{0.451} \\
aRNN & \multicolumn{2}{c}{0.582 (0.008)} \\
LR+ TAM & 0.585 (0.012) & 0.587 (0.008) \\
LDA+LR & 0.586 (0.006) & 0.606 (0.007) \\
GSM+LR & 0.495 (0.004) & 0.517 (0.007) \\
LR+sLDA & 0.571 (0.002) & 0.574 (0.001) \\
LR+BPsLDA & 0.603 (0.002) & 0.609 (0.001) \\
LR+rSCHOLAR & 0.550 (0.034) & 0.557 (0.027) \\
\textbf{rSCHOLAR} & 0.571 (0.01) & 0.581 (0.009) \\
\textbf{BTR} & \textbf{0.630} (0.001) & \textbf{0.633} (0.001)\\
\bottomrule
\\[-1.8ex]
{Perplexity (lower is better)} \\
\midrule
LR+TAM & 1661 (7) & 1655 (7) \\
LDA+LR & 1306 (4) & 1196 (2)\\
GSM+LR & 1431 (34) & 1387 (14) \\
LR+sLDA & 1294 (5) & 1174 (3) \\
LR+rSCHOLAR & 1515 (34) & 1516 (30) \\
\textbf{rSCHOLAR} & 1491 (9) & 1490 (9) \\
\textbf{BTR} & \textbf{1291 (5)} & \textbf{1165} (3) \\
\bottomrule
\end{tabular}}
\caption{Yelp: mean $pR^2$ and perplexity, standard deviation in brackets. 20 model runs. Best model \textbf{bold}.}
\label{tab:results_empirical}
\end{table}
The joint supervised estimation approach using text and non-text features, not only counteracts bias in causal settings. It also improves prediction performance. We use the real-world datasets of Booking and Yelp for our benchmarking. For both datasets, we predict customer ratings (response) for a business or hotel given customer reviews (text features) and business and customer metadata (numerical features).\footnote{full specifications for each case are given in Appendix \ref{section_app_real_world_data}}
\subsection{Benchmarks}
We add the following models to the benchmark list from the previous section:\footnote{We also tested sLDA+LR and a pure sLDA, which performed consistently worse, see Appendix \ref{app_empirical_data_results}} \textbf{LDA+LR} \cite{griffiths2004finding} and \textbf{GSM+LR} \cite{miao2017discovering} unsupervised Gibbs sampling and neural VI based topic models. \textbf{LR+rSCHOLAR}: the two-step equivalent for rSCHOLAR, estimating covariate regression weights in a separate step from the supervised topic model.
An alternative to topic based models are word-embedding based neural networks. We use (7) \textbf{LR+aRNN}: a bidirectional RNN with attention \cite{bahdanauCB15}. Since the model does not allow for non-text features, we use the regression residuals of the linear regression as the target. And (8) \textbf{LR+TAM}: a bidirectional RNN using global topic vector to enhance its attention heads \cite{wang2020neural} - same target as in LR+aRNN.
\footnote{\citet{wang2020neural} use $100$-dimensional word embeddings in their default setup for TAM and pre-train those on the dataset. We follow this approach. RNN and TAM results were very robust to changes in the hidden layer size in these setups, we use a layer size of $64$. Full details of all model parametrisations are provided in Appendix \ref{app:model_params}.}
\subsection{Prediction and Perplexity Results}
We evaluated all topic models on a range from 10 to 100 topics, with results for 50 and 100 in Table \ref{tab:results_empirical}.\footnote{ Hyperparameters of displayed results: $\alpha=0.5$, $\eta=0.01$} Hyperparameters of benchmark models that have no direct equivalent in our model were set as suggested in the pertaining papers. We find that our results are robust across a wide range of hyperparameters (extensive robustness checks in Appendix \ref{section:app_realworld_experiments}).
We assess the models' predictive performance based on predictive $R^2$ ($pR^2= 1 - \frac{\text{MSE}}{var(y)}$). The upper part of Table \ref{tab:results_empirical} shows that BTR achieves the best $pR^2$ in the Yelp dataset and and very competitive results in the Booking dataset, where our rSCHOLAR extension outperforms all other models. Even the non-linear neural network models aRNN and TAM cannot achieve better results. Importantly, rSCHOLAR and BTR perform substantially better than their counterparts that do not jointly estimate the influence of covariates (LR+rSCHOLAR and LR+sLDA).
To assess document modelling performance, we report the test set perplexity score for all models that allow this (Table \ref{tab:results_empirical}, bottom panel) . Perplexity is defined as $\exp\left\{ -\frac{\sum^{D}_{d=1} \log p(\bs{w}_d|\bs{\theta},\bs{\beta})}{\sum_{d=1}^{D}N_d}\right\}$. The joint approach of both rSCHOLAR and BTR does not come at the cost of increased perplexity. If anything, the supervised learning approach using labels and covariates even improves document modelling performance when compared against its unsupervised counterpart (BTR vs LDA).
Assessing the interpretability of topic models is ultimately a subjective exercise. In Appendix \ref{section:app_topics} we show topics associated with the most positive and negative regression weights, for each dataset. Overall, the identified topics and the sign of the associated weights seem interpretable and intuitive.
\section{Conclusions}
In this paper, we introduced BTR, a Bayesian topic regression framework that incorporates both numerical and text data for modelling a response variable, jointly estimating all model parameters. Motivated by the FWL theorem, this approach is designed to avoid potential bias in the regression weights, and can provide a sound regression framework for statistical and causal inference when one needs to control for both numerical and text based confounders in observational data. We demonstrate that our model recovers the ground truth with lower bias than any other benchmark model on synthetic and semi-synthetic datasets.
Experiments on real-world data show that a joint and supervised learning strategy also yields superior prediction performance compared to `two-stage' strategies, even competing with deep neural networks.
\section*{Acknowledgements}
Maximilian Ahrens and Julian Ashwin were supported by the Economic and Social Research Council of the UK. Maximilian Ahrens, Jan-Peter Calliess and Vu Nguyen are furthermore grateful for support from the Oxford-Man-Institute.
| {'timestamp': '2021-09-14T02:14:33', 'yymm': '2109', 'arxiv_id': '2109.05317', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05317'} | arxiv |
\section{Introduction}
\textbf{Semantic segmentation} provides dense per pixel classification corresponding to each pixel's labels \cite{caesar2018coco,cordts2016cityscapes,everingham2015pascal}, which is a crucial task in the field of computer vision. Solving and understanding the environment within an image using segmentation opens the door to many applications in the field of robotics, security, autonomous vehicles, helping blind and visually impaired people (BVIP), etc. With the advancements in deep neural networks, \cite{dhingra2019res3atn,rakelly2018conditional,krizhevsky2012imagenet,rota2018place}, computer vision tasks such as semantic segmentation performance have improved using large scale datasets for training as compared to segmentation using handcrafted features \cite{he2004multiscale,ladicky2009associative,yao2012describing,gould2009decomposing}. Segmentation of pixels in non-boundaries regions is easier than for the object boundaries, since border pixels are prone to have large ambiguity in belonging to a particular segment.
\textbf{Graph convolutional network}
Research in the field of Graph Neural Networks (GNN) have produced interesting results for graph classification that do not require as much resources as traditional Neural networks \cite{DBLP:journals/corr/KipfW16}. Graph Convolutional Networks (GCN) have been used in the field of body pose estimation, action recognition, etc, as human body data can be converted into graphical forms \cite{wang2020global,zheng2019fall,zhao2019semantic,yan2018spatial,li2019actional,gao2019optimized,liu2019si}. Similarly, point cloud data has also been used in graphical forms. \cite{qian2019pu,xu2019grid,li2019deepgcns}.
As illustrated in Figure \ref{fig:Simple overview}, we propose a novel GCN based architecture for refining the outline of object boundaries on the pre-segmented image from a baseline network such as Unet or any other arbitrary network. Instead of focusing on the whole video segmentation task using GCNs, we focus on improving the object boundaries causing more ambiguities at the boundaries than at the non-border regions. The loss function penalizes for the border pixels in the network. It also decreases the computation complexity for the whole network as it has to only focus on some regions of the whole scene in each frame of a video. We effectively build a pipeline to generate graph based data from the visual data using spatial and intensity information of the pixels. Our architecture gives the flexibility to use any baseline network for the pre-segmentation task. We performed evaluation using two baseline networks to study the effect of using very different baseline network. In addition, a visualization analysis reveals that the object outline segmentation learned by the proposed architecture has meaningful semantic predictions.
\begin{figure}[!htb]
\centering
\includegraphics[width=1\linewidth, height=5cm]{figures/Figintro_small.pdf}
\vspace{0.25cm}
\caption[Simple overview]{We aim to adapt a semantic segmentation model learned from base algorithm using a graph convolutional network (GCN). The initial segmentation from base algorithm is used as basis and thereafter, GCNs are used to improve the object border outline pixel classification.}
\label{fig:Simple overview}
\end{figure}
Our contributions are summarized as follows: (1) We develop a novel method, Border-SegGCN, using GCNs to improve the semantic segmentation performance by refining the predicted boundaries. (2) We test our pipeline using two open source datasets, i.e., Camvid and Carla dataset (3) We perform the evaluation of different border widths to be used for a better performance of the procedure. (4) We evaluate the performance with a varying number of edges for the nodes in the graph. (5) We study the effect of a different number of features used as an input to the GCN network. (6) We evaluate the training with different hyper-parameters such as dropout and regularisation. (7) We also verify the performance of Border-SegGCN visually using qualitative results. (8) We prove the performance of the network using two different baseline models, i.e., Unet and DeepLabV3+. Border-SegGCN consistently improves performance when used on top of baseline approaches.
\section{Related Work}
\textbf{Semantic segmentation} is actively researched by computer vision researchers due to its application in various domains such as robotics, health care, security, etc. Most recent work is using fully convolutional neural networks for pixel-wise classification \cite{rakelly2018conditional,mou2019relation,zhang2018fully,li2017fully,lin2016scribblesup}. Various model variants have been researched \cite{chen2018encoder,schwing2015fully,jampani2016learning,vemulapalli2016gaussian} to use the contextual information for the task of segmentation \cite{mostajabi2015feedforward,dai2015convolutional,yao2012describing,ladicky2009associative} based on multi-scale inputs \cite{farabet2012learning,eigen2015predicting,lin2016efficient} or based on probabilistic graphical models \cite{pinheiro2014recurrent,chandra2016fast,chandra2017dense,chen2017deeplab}. There are many open-source datasets available for semantic segmentation, such as e.g., PASCAL \cite{everingham2010pascal}, COCO \cite{lin2014microsoft}, CamVid \cite{CamVid}, Carla \cite{dosovitskiy2017carla}, etc. Our work uses the CamVid and Carla dataset for the semantic segmentation task. We use Unet and DeepLabV3+ as our base networks for the segmentation.
\textbf{Graph neural networks} have recently been used for various applications involving the graph structured data because of their effectiveness in representing such data \cite{xie2018memory}. Some of the tasks are action recognition, body pose estimation, link prediction, etc. Graph models can be subdivided into two categories, i.e, Graph Neural Network (GNN) \cite{xu2018powerful,wu2019comprehensive,qi20173d,monti2017geometric,zhang2018link,li2017situation,jaume2018image}, and GCNs.
The first category, i.e., GNN, consists of a graph and a recurrent neural network and has a functionality of passing messages and updating nodes states which store the semantic and structural information in the neighboring nodes. For instance, \cite{qi20173d} uses a 3D graph neural network (3DGNN) with a 3D point cloud to build a k-nearest neighbor graph for RGBD semantic segmentation. Every node in the graph represents a group of points which has a hidden representation vector that is updated based on the recurrent functions.
The second category, i.e., GCN, extends the mathematical operation of convolution to graph structures. GCNs can be distinguished into two types, i.e., spectral GCNs and spatial GCNs. Spectral GCNs convert signals in graphical form into graph spectral domains, in which they can be manipulated using spectral filters. For instance, in \cite{duvenaud2015convolutional,henaff2015deep}, graph Laplacian-based CNNs are used in the spectral domain. Spectral GCNs use convolution along with neighborhood data to calculate the feature vector for the node. They were first employed for semi-supervised classification on graph-structured data \cite{DBLP:journals/corr/KipfW16}. For example, \cite{simonovsky2017dynamic} use GCNs on point cloud data in the spatial domain. \cite{si2019attention} use GCNs in a recurrent structure for skeleton based action recognition.
Both \cite{graphcut} and \cite{zhang15multiclass} have shown that image semantic segmentation can be formulated and solved using graphs. This paper focuses on applying GCNs in the context of video segmentation. The main issues discussed revolve around creating an efficient pipeline to convert video frames into graphs and optimising the pipeline to maximizing the efficiency of the GCN.
\section{Methodology}
\label{chp:Our approach}
Figure \ref{fig:Simple overview} illustrates an overview of the used pipeline. In the following section, we will discuss how we approach the graph creation from an image.
\subsection{Efficient Graph Generation}
\label{sec:Efficient graph generation}
This approach includes a refinement of borders using existing segmentation algorithms. We use the Unet \cite{ronneberger2015u} and DeepLabv3+ architecture as a base segmentation networks. The dataset used for the evaluation of this architecture is the Cambridge-driving Labeled Video Database ("CamVid") dataset \cite{BrostowFC:PRL2008} and Carla dataset \cite{dosovitskiy2017carla}. The frame size is 360 pixels wide and 480 pixels high. A mask is used to determine which nodes to compute based on their location, while omitting the rest of the nodes. This allows the graph to have the same size from frame to frame. Performing computation on the selected nodes allows decreasing computation time drastically and provides more relevant training examples to the GCN.
\begin{figure}[!htb]
\centering
\includegraphics[width=\linewidth, height=2.2cm]{figures/boolean_new2.pdf}
\vspace{0.25cm}
\caption[Boolean mask generation example]{Example of how the data is processed during the Boolean mask generation.
Left: The initial frame is passed on to the base segmentation algorithm. Center: An initial rough segmentation is retrieved. Right: Pixels are either selected (yellow) or rejected (purple) depending if they are on the border of different objects.}
\label{fig:Boolean mask generation example}
\end{figure}
To determine which nodes are selected we use the initial segmentation that our base algorithm provides: in this case the Unet or DeepLabV3+. With the pre-segmentation provided, boundaries around the objects and different classes are determined. Depending on the task at hand, the pixels that lay on the border are then selected for further processing followed by training or prediction. Figure \ref{fig:Boolean mask generation example} shows the process of generating the Boolean mask.
\subsection{Generating the Features}
\label{subsec:Generating the features}
\begin{figure}[!htb]
\centering
\includegraphics[width=\linewidth, height=6cm]{figures/features_p}
\vspace{0.25cm}
\caption[Feature extraction pipeline]{Pipeline for feature extraction from the initial frame. Each feature set is concatenated into a single feature dictionary with the pixel coordinates being the keys of the hash map. Each pixel has at least the class predicted by the base algorithm and the associated RGB values. Intermediate layer values are very dependant on the base algorithm.}
\label{fig:Feature extraction pipeline}
\end{figure}
Features used for each node consist of the intensity values from the three RGB channels of the video and the output segmented image from the base algorithm such as from Unet or DeepLabV3+. All other features consist of the intermediate values. In case of Unet, the final layers provide features and for the DeepLabV3+, the intermediate layers are used as features for input to GCN. Figure \ref{fig:Feature extraction pipeline} illustrates the pipeline for feature extraction.
\subsection{Connecting the Graph}
\label{subsec:Connecting the graph}
Based on the Boolean mask, nodes are connected that are on the border of objects. The rest of the nodes are either isolated or have only incoming connections.
\begin{figure}[!htb]
\centering
\includegraphics[width=0.8\linewidth]{figures/edges}
\vspace{0.25cm}
\caption[Edge generation pipeline]{Pipeline for generating the edges of the graph. The first segmented image provides the size of the image and thus all the potential nodes that need to be processed. The Boolean mask directs which nodes should actually be worked on. If a pixel does not reside on a border then it will remain an isolated node.}
\label{fig:Edge generation pipeline}
\end{figure}
For each node, the mapping consists of two parts: The actual coordinates of the N closest neighbours denoted by $(x_i, y_i)$ with $i<N$, and the weights that are associated with each of those neighbours denoted by $d_i$ with $i<N$. The illustration of the pipeline for generating the edges is shown in Figure \ref{fig:Edge generation pipeline}.
The weights associated for the edge between two neighbours are completely arbitrary. We chose to use a weight definition that takes into account the distance and intensity differences as inspired by \cite{graphcut}. The resulting weight definition is shown in Equation \ref{eqn:weights}.
\begin{equation}
\centering
d_{n_{12}} = \frac{1}{d_{E_{12}}}\times\exp({-\frac{ \left\lVert I_{n_{1}} - I_{n_{2}}\right\rVert}{ \left\lVert I_{255}\right\rVert}})
\label{eqn:weights}
\end{equation}
Equation \ref{eqn:weights} represents the weight between two nodes $n_1$ and $n_2$ in the $[0,1]$ range. The inverse of the Euclidean distance between these two nodes denoted as $d_{E_{12}}$. The difference in intensities of the two pixels is taken into account for determining the weight of the edge. This value is normalized and its exponent is taken to penalise two nodes of different values. Considering that several operations have to be performed on each neighbour of every selected node, the overall computational cost is $O(n^k)$ with $n$ being the number of pixels selected, and $k$ the number of closest neighbours we would like to connect to. The Boolean mask assists in directing the resources. If a node is not marked as being on the border, the number of neighbours collapses to 0 in our dictionary. Thus, no computation is performed.
\begin{figure}[!htb]
\centering
\includegraphics[width=0.7\linewidth, height=5cm]{figures/RGBdiff}
\vspace{0.25cm}
\caption[Our connection weights]{Weights taking into account Euclidean distance and difference in pixel-intensity values.}
\label{fig:Our connection weights}
\end{figure}
Figure \ref{fig:Our connection weights} illustrates the behaviour of Equation \ref{eqn:weights}. The selected node is denoted as S on the grid. The values in each square represent the value of the weight between S and the node that contains the value. If the colours match and the node is directly adjacent, then the value is maximal. On the other hand, two pixels can be next to each other but with different shades of the same colour. In this case, the value will decrease. We thus encode both the spatial information and also the pixel intensity similarity.
\subsection{Encoding the Graph}
\label{subsec:Encoding the graph}
The input to GCN requires the generation of the associated adjacency and feature matrices. The resulting size of these two matrices depend on the initial size of the frame and on the feature set that was selected. An example is the CamVid dataset which provides frames of 360 by 480 pixels in a video. This creates a square adjacency matrix of 172'800 by 172'800 pixels for each frame. The feature matrix will depend on the selected features and in the case where only intensity values of 3 RGB channels of frames are used as features, the shape will be equal to 172'800 $\times$ 3.
\section{GCN Training}
\label{sec:GCN training}
After the data has been correctly generated as explained in the previous sections (\ref{sec:Efficient graph generation}-\ref{subsec:Encoding the graph}), the training is carried out. The employed GCN architecture in our Border-SegSGN is a modification on the network given in \cite{DBLP:journals/corr/KipfW16}. The architecture used consists of consecutive graph convolutional layers and dropout layers as shown in Figure \ref{fig:Our GCN architecture}. We experimented with several different versions of network architecture but the Figure \ref{fig:Our GCN architecture} has better performance.
\begin{figure}[!htb]
\centering
\includegraphics[width=1\linewidth, height=4cm]{figures/Comp_arch.pdf}
\vspace{0.2cm}
\caption[Our GCN architecture]{Illustration of our GCN architecture based on \cite{DBLP:journals/corr/KipfW16}.}
\label{fig:Our GCN architecture}
\end{figure}
The graph convolutional layers take two input matrices: the adjacency matrix and the feature matrix. The adjacency matrix is considered immutable and thus does not change between the layers. On the other hand, the feature matrix varies with each layer.
\begin{figure}[!htb]
\centering
\includegraphics[width=\linewidth, height=7.5cm]{figures/GCNtrain_font-2.pdf}
\vspace{0.2cm}
\caption[GCN training with Boolean mask]{Pipeline representing the inputs for the GCN training in Border-SegGCN.}
\label{fig:GCN training with boolean mask}
\end{figure}
However, most importantly, we use the Boolean mask created before to direct the GCN training. For the model to fit the correct labels, we pass the mask giving no training relevance on the loss function for the nodes that are not on the border. Figure \ref{fig:GCN training with boolean mask} shows the different inputs to the GCN Network.
\section{GCN Prediction}
\label{sec:GCN prediction}
For the prediction as shown in Figure \ref{fig:GCN predicition pipeline}, the GCN takes as input the desired adjacency matrix and feature matrix, but does not require the Boolean mask. We predict the class of every node. Due to the nature of the training, the GCN output is poor on pixels that do not lie on any borders. The solution is to combine the base output of the initial algorithm with the output of the GCN where non-border pixels are assigned to their classes from the output of the base algorithm, while border pixels are assigned to their classes from the GCN output.
\begin{figure}[!htb]
\centering
\includegraphics[width=\linewidth, height=7.5cm]{figures/GCNpred-5}
\caption[GCN prediction pipeline]{Pipeline of required inputs to generate final segmented image in Border-SegGCN.}
\label{fig:GCN predicition pipeline}
\end{figure}
\section{Experiments}
\label{chp:results}
In this section, we verify the effectiveness of our proposed approach for semantic segmentation.
\subsection{Implementation Details}
We use the Unet implementation of the "Segmentation models" PyTorch library \cite{Yakubovskiy:2019}. The encoder is ResNeXt-50 (32$\times$4d) and the weights of the network are pre-trained from ImageNet.
For DeepLabV3+, we use the openly available pre-trained model from \cite{semantic_cvpr19} based on\cite{chen2018encoderdecoder}. For both models, we register forward hooks after each layer and retrieve data at each step for every passing frame.
The GCN architecture is modelled based on \cite{DBLP:journals/corr/KipfW16} with slight modifications. It consists of three graph convolutional layers with 64, 128 and 64 channels respectively. A dropout layer is inserted between each graph convolutional layer.
The GCN is built in Keras using the "Spektral" library \footnote{https://spektral.graphneural.network} and an Adam \cite{kingma2014adam} optimiser with a learning rate of 0.001. This approach assumes that each pixel is a sample and this is why it is necessary to set a batch size of $N = H \times W$, where $H$ is the height of frame and $W$ is its width. As a metric for evaluation, we use the mean intersection over union (mIoU) score as defined in \cite{semantic_cvpr19}.
\subsection{Dataset}
\textbf{Camvid} We use the "CamVid" \cite{BrostowFC:PRL2008} dataset for the evaluation of Border-SegGCN. It consists of 367 training, 233 testing, and 101 validation fully annotated frames. Each frame is $360 \times 480$ pixels. The testing frames are from two different video sequences, Seq05VD and 0001TP. We do not perform any kind of augmentation on the data for training.
We work with the 11 recommended classes out of the 31 available ones to be able to compare with other literature that have followed similar approaches of using 11 classes \cite{semantic_cvpr19}.
\textbf{Carla} \cite{dosovitskiy2017carla} is a semantic segmentation dataset for self-driving cars. t is a simulated dataset and not the real-world images. It is available as open-source. The original dataset has 4550 training images and 449 testing images. We used a subset of this dataset, i.e., 500 for training, 100 for validation, and 300 for testing. We pre-processed this dataset to have the same frame-size as CamVid dataset i.e. $360 \times 480$ pixels. We cropped the image from the center of the image. There are 13 classes for the pixels to be classified on in the dataset.
\subsection{Quantitative Results}
Table \ref{Tab:conclusion} illustrates the mIoU results for the Border-SegGCN using Unet and DeepLabV3+ models as base segmentation networks on CamVid and Carla datasets.
\begin{table}[!htb]
\centering
\begin{tabular}{ccc}
\toprule
Metric & DeepLabV3+ & Unet\\
\midrule
Base mIoU & 81.63 & 79.77 \\
Our mIoU & \textbf{81.96} & \textbf{80.49}\\
Max theoretical mIoU & 89.15 & 83.98 \\
Base mIoU on border & 39.17 & 34.59\\
Our mIoU on border & \textbf{40.92} & \textbf{45.67}\\
\bottomrule
\end{tabular}
\vspace*{0.3cm}
\normalsize
\caption[Results considering context]{Quantitative mIoU values achieved using Border-SegGCN with UNet and DeepLabV3+. Note that the theoretical maximum is computed by replacing all labels for pixels on the border with their ground truth.}
\label{Tab:conclusion}
\end{table}
DeepLabV3+ has been shown to outperform the vanilla Unet. So, it has more border pixels than the Unet model. Hence, DeepLabV3+ model has a higher theoretical maximum. The relative improvement on the Unet is much larger than that on the DeepLabV3+ model because of a lower upper limit. Thus, having less problematic borders to re-classify.
The best performing mIoU on the CamVid dataset using our Border-SegGCN achieved 81.96. In \cite{semantic_cvpr19}, they obtained a mIoU of 81.7. Using their code, we managed to reproduce 81.63. We were able to register a real improvement on this as baseline by 0.404\%. Furthermore, it is important to consider that the border pixels only constitute between 10-20\% of the entire image. This effectively creates an upper limit on the performance that the Border-SegGCN can not exceed.
We do not train Carla dataset for two epochs with Unet because if trained till the best mIoU then most of the border pixels in the image are correctly classified for this dataset. We want to show with our algorithm and experiments that if there are wrong pixels classified along the border with base algorithm then BorderSegGCN helps to rectify those pixel classification on borders. We use same parameter setting for training with Carla dataset as used for with Camvid dataset when Unet is used as baseline.
We performed an ablation study on different parameters such as border thickness, number of edges for each node, number of input features from base network to GCN, effect of using different base network, etc. on CamVid dataset. The results are sumarized in Table \ref{Tab:ablation}
\subsubsection{Border Thickness:} Figure \ref{fig:Border thickness} shows the camvid dataset frames with different border pixel thickness. Figure \ref{fig:PixelThickness} shows that except certain outliers, the overall trend is that as the amount of border pixels increases, the mIoU decreases. This can be due to the spatial intrinsic characteristics that border pixels have, which allows the GCN to better fit to them.
\begin{figure}[!htb]
\centering
\includegraphics[width=0.31\linewidth]{figures/border1}
\includegraphics[width=0.31\linewidth]{figures/border2}
\includegraphics[width=0.305\linewidth]{figures/border3}
\vspace{0.2cm}
\caption[Border thickness]{Left to right: 1, 2, 3 border pixel are selected respectively. Frames taken from CamVid dataset.}
\label{fig:Border thickness}
\end{figure}
\begin{figure}[!htb]
\centering
\subfloat[Influence of border thickness.\label{fig:PixelThickness}]{%
\includegraphics[width=2.3in]{figures/chart-9.pdf}%
}
\hfill
\subfloat[Influence of number of connections.\label{fig:NumCon}]{%
\includegraphics[width=2.3in]{figures/chart-8.pdf}%
}
\vfill
\includegraphics[width=1.2in]{figures/legend.png}%
\caption[Influence of border thickness]{Influence of graph attributes on mIoU.}
\label{fig:GraphVar}
\end{figure}
\begin{table*}[!htb]
\centering
\begin{tabular}{cc|cc|cc|cc|ll}
\toprule
\# connections & mIoU & Border Thickness & mIoU & \# features & mIoU & Dropout Rate & mIoU & Regularization & mIoU\\
\hline
2 & 79.88 & 1 & 80.11 & 11 & 78.37 & 0 & 80.20 & 1.00e-01 & 74.79\\
4 & 79.97 & 2& 80.00 & 15 & 80.45 & 0.0001 & 80.39 & 1.00e-04 & 80.12 \\
8 & 80.11 & 3& 80.16 & 256 & 81.12 & 0.001 & 80.11 & 1.00e-08 &80.24\\
16 & 80.33 & 4 & 80.07 & 271 & 80.90 & 0.1 & 80.09 & 1.00e-11 & 80.14 \\
- & - & 5& 80.10 & 319 & 80.99 & 0.5 & 80.33 & 1.00e-13 & 80.22\\
- & - & 6 & 79.96 & 510 & 81.59& 0.9 & 79.39 & - & -\\
- & - & - & - & 1039 & 81.73 & - & -& - & -\\
- & - & - & - & 1999 & 81.92 & - & - & - & -\\
\bottomrule
\end{tabular}
\vspace*{0.1cm}
\normalsize
\vspace*{0.2cm}
\caption[Results considering context]{Ablation study with quantitative mIoU values achieved using Border-SegGCN with DeepLabV3+ for Camvid dataset using different number of connections in the graph, number of border pixel thickness, number of features, dropout rate, and regularization}
\label{Tab:ablation}
\end{table*}
\subsubsection{Number of Edges:} As the number of edges is variable, we see how the number of connections each node has influences the results of improving the segmentation task (with the help of improving the border pixel classification). Figure \ref{fig:NumCon} shows that the results steadily increase as the number of edges increases because the more edges a singular node has, the more spatial information it carries about its neighbours. It is also worth mentioning that increasing indefinitely the number of edges has two adverse effects. First, it becomes computationally more expensive to generate the graph as more information is stored per node. But second, and more importantly, the impact of each edge decreases as the number of edges increases.
\subsubsection{Number of Features:} The most important consideration within the graph creation process is the feature selection step. The features have to represent enough information to the GCN for it to predict the correct pixel class. Figure \ref{fig:FeatSeg} represents the correlation between the mean IoU and the number of feature channels.
\begin{figure}[!htb]
\centering
\subfloat[Border-SegGCN with Unet\label{fig:Unet feat1}]{%
\includegraphics[width=2.3in]{figures/chart-12.pdf}%
}
\hfill
\subfloat[Border-SegGCN with DeepLabV3+\label{fig:DeepLab feat1}]{%
\includegraphics[width=2.3in]{figures/chart-14.pdf}%
}
\vfill
\includegraphics[width=1.2in]{figures/legend.png}%
\caption[Influence of number of features]{Influence of number of features on the mIoU.}
\label{fig:FeatSeg}
\end{figure}
Each step represents a different set of features, representing a combination of different feature sets. Unsurprisingly, the best results are obtained by combining the base algorithm's output, the intensity values of the frames, and a combination of intermediary layers.
\begin{table}[!htb]
\footnotesize
\centering
\begin{tabular}{cc}
\toprule
Number of features & Constituent features\\
\midrule
3 & 'I' \\
4 & 'base' + 'I'\\
19 & 'RGB' + 'd5' \\
21 & 'base' + 'I' + 'seg' + 'd5' \\
128 & 'base' + 'I' + 'seg' + 'd3' + 'd4' + 'd5'\\
\bottomrule
\end{tabular}
\vspace*{0.3cm}
\normalsize
\caption[Unet number of feature mapping]{Decomposition of the features that were used as input to GCN when Unet is a base network in Border-SegGCN. Notations: I-intensity values of the RGB channels, base-output segmented image from base network, d3-d5-last 3 decoder layer of Unet.}
\label{tab:imprwdpatterns3}
\end{table}
\begin{table}[!htb]
\footnotesize
\centering
\begin{tabular}{cc}
\toprule
Number of features & Constituent features\\
\midrule
11 & 'I' \\
15 & 'I' + 'base' \\
256 & 'mba' \\
271 & 'base'+'I'+ '$final_{6}$'+'$final_{3}$'\\
319 & 'base'+'I'+ 'seg'+'mba'\\
510 & 'I'+ '$final_{6}$'+'m1+'m2'+'seg'+'mba'\\
1039 & 'I'+ '$final_{6}$'+'m5'\\
1999 & 'base'+ 'I'+ '$final_{6}$' +'m1'+'m2'+'m3'+'m4'+'m5' \\
\bottomrule
\end{tabular}
\vspace*{0.3cm}
\normalsize
\caption[Unet number of feature mapping]{Decomposition of the features that were used as input to GCN when DeepLabV3+ is a base network in Border-SegGCN. Notations: I-intensity values of the RGB channels, base-output segmented image from base network, '$final_{1-6}$'-Segmentation heads sublayers 1 to 6, m1-m7- Encoder layers 1 to 7, 'mba'-Atrous spatial pyramid pooling output}
\label{tab:imprwdpatterns}
\end{table}
\subsubsection{GCN Dropout Optimisation:}
We used a modification of the architecture given in \cite{DBLP:journals/corr/KipfW16} that showed an improvement when the number of layers is varied from the original network. We show the dropout effects on the mean IoU score in Figure \ref{fig:Dropout}.
\begin{figure}[!htb]
\centering
\subfloat[Dropout effect on mIoU\label{fig:Dropout}]{%
\includegraphics[width=2.3in]{figures/chart-10.pdf}%
}
\hfill
\subfloat[Regularisation effect on mIoU\label{fig:Regularisation}]{%
\includegraphics[width=2.3in]{figures/chart-11.pdf}%
}
\vfill
\includegraphics[width=1.2in]{figures/legend.png}%
\vspace*{0.2cm}
\caption[Dropout and regularisation]{Influence of dropout and regularisation on Border-SegGCN.}
\label{fig:DropReg}
\end{figure}
\subsubsection{GCN Regularisation Optimisation:}
Figure \ref{fig:Regularisation} shows the mIoU improvement as the regularisation coefficient decreases. This concludes that the GCN is not prone to overfitting and thus can generalise the results.
\subsubsection{Different Base Model: DeepLabV3+:}
We use the base network Unet in the previous studies. Recent research shows that there have been architectures that have improved performance over Unet such as the DeepLabV3+ \cite{chen2018encoderdecoder}.
We observe the same trend with the Unet experiments. When increasing the number of feature channels, mIoU increases as well. However, the amount of features is much higher and requires much more computational resources with this network. Figure \ref{fig:DeepLab feat1} suggests that we are capable of improving an output from different models with our architecture pipeline.
\subsection{Time Complexity}
Total time required for each frame in the video is around 19 seconds. The average time for DeepLabV3+ is 0.08sec per frame. So, Border-SegGCN has a drawback of latency. We are introducing this technique as a stepping stone so that the research can also be focused on GCNs for improving semantic segmentation using improved techniques.
\subsection{Image Size}
This approach requires adjacency matrix has squared dimension of the given image. So, due to available GPU resources, it is not possible to do experiments on various video segmentation datasets having large frame size.
\subsection{Qualitative Results}
\label{sec:Output}
Figure \ref{fig:Output} shows qualitative examples of the output generated by our pipeline. The output segmented frames from using both, the Unet and DeepLabV3+, as base network are illustrated with their best input feature set compared to an under-performing input feature set.
\begin{figure}[!htb]
\centering
\subfloat[\label{fig:Original}]{%
\includegraphics[width=0.22\linewidth, height=2cm]{figures/org}
}
\subfloat[\label{fig:DeepLabV3+ baseline}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/deep_base.png}
}
\subfloat[\label{fig:Border-SegGCN with DeepLabV3+ good}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/deep_good.png}
}
\subfloat[\label{fig:Border-SegGCN with DeepLabV3+ bad}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/deep_bad.png}
}\hfill
\subfloat[\label{fig:Ground truth}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/ground.png}
}
\subfloat[\label{fig:Unet baseline}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/unet_base.png}
}
\subfloat[\label{fig:Border-SegGCN with Unet good}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/unet_good.png}
}
\subfloat[\label{fig:Border-SegGCN with Unet bad}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/unet_bad.png}
}
\vspace{0.2cm}
\caption[Output]{(a) Original. (b) DeepLabV3+ baseline. (c) Best Border-SegGCN with DeepLabV3+. (d) Poor Border-SegGCN with DeepLabV3+.
(e) Ground truth. (f) Unet baseline. (g) Best Border-SegGCN with Unet. (h) Poor Border-SegGCN with Unet.}
\label{fig:Output}
\end{figure}
We noticed from Figure \ref{fig:Output} that
\begin{itemize}
\item In the case of Unet as shown in Figure \ref{fig:Unet baseline}, when the model is under-performing due to use of wrong feature set input to the GCN, the model defaults to the statistical most likely category \ref{fig:Border-SegGCN with Unet bad}.
\item DeepLabV3+ has difficulties with objects that appear smaller in the frame \ref{fig:DeepLabV3+ baseline},
\item Our model is capable of correcting the DeepLabV3+ predictions on the outline of those objects \ref{fig:Border-SegGCN with DeepLabV3+ good}.
\item The outlines using Border-SegGCN in \ref{fig:Border-SegGCN with Unet good} are better defined as compared to \ref{fig:Unet baseline}.
\end{itemize}
\section{Conclusion}
\label{sec:Conclusion}
Our proposed model “Border-SegGCN” employs the base segmentation network such as Unet and DeepLabV3+ along with the GCN. Border-SegGCN is used to refine the object boundaries predictions. The most important task for improving the prediction performance of the base algorithm is the feature selection to be used as input to GCN. The variation due to features is the largest contributing factor in both baseline architectures, i.e., Unet and DeepLabV3+. Our experiments showed that Border-SegGCN is agnostic to the choice of baseline model. The more spatial information a node has on its neighbours, expressed by the number of edges, the better is the performance of the GCN. Finally, our experimental results show that the proposed model gives a new state-of-the-art performance on CamVid dataset using DeepLabV3+ as baseline network. It also improved the results of Unet baseline for both Camvid and Carla datasets. In future work, we will work on tackling the drawbacks of this technique, i.e. improving latency, and reducing computation complexity.
{\small
\bibliographystyle{ieee_fullname}
\section{Introduction}
\textbf{Semantic segmentation} provides dense per pixel classification corresponding to each pixel's labels \cite{caesar2018coco,cordts2016cityscapes,everingham2015pascal}, which is a crucial task in the field of computer vision. Solving and understanding the environment within an image using segmentation opens the door to many applications in the field of robotics, security, autonomous vehicles, helping blind and visually impaired people (BVIP), etc. With the advancements in deep neural networks, \cite{dhingra2019res3atn,rakelly2018conditional,krizhevsky2012imagenet,rota2018place}, computer vision tasks such as semantic segmentation performance have improved using large scale datasets for training as compared to segmentation using handcrafted features \cite{he2004multiscale,ladicky2009associative,yao2012describing,gould2009decomposing}. Segmentation of pixels in non-boundaries regions is easier than for the object boundaries, since border pixels are prone to have large ambiguity in belonging to a particular segment.
\textbf{Graph convolutional network}
Research in the field of Graph Neural Networks (GNN) have produced interesting results for graph classification that do not require as much resources as traditional Neural networks \cite{DBLP:journals/corr/KipfW16}. Graph Convolutional Networks (GCN) have been used in the field of body pose estimation, action recognition, etc, as human body data can be converted into graphical forms \cite{wang2020global,zheng2019fall,zhao2019semantic,yan2018spatial,li2019actional,gao2019optimized,liu2019si}. Similarly, point cloud data has also been used in graphical forms. \cite{qian2019pu,xu2019grid,li2019deepgcns}.
As illustrated in Figure \ref{fig:Simple overview}, we propose a novel GCN based architecture for refining the outline of object boundaries on the pre-segmented image from a baseline network such as Unet or any other arbitrary network. Instead of focusing on the whole video segmentation task using GCNs, we focus on improving the object boundaries causing more ambiguities at the boundaries than at the non-border regions. The loss function penalizes for the border pixels in the network. It also decreases the computation complexity for the whole network as it has to only focus on some regions of the whole scene in each frame of a video. We effectively build a pipeline to generate graph based data from the visual data using spatial and intensity information of the pixels. Our architecture gives the flexibility to use any baseline network for the pre-segmentation task. We performed evaluation using two baseline networks to study the effect of using very different baseline network. In addition, a visualization analysis reveals that the object outline segmentation learned by the proposed architecture has meaningful semantic predictions.
\begin{figure}[!htb]
\centering
\includegraphics[width=1\linewidth, height=5cm]{figures/Figintro_small.pdf}
\vspace{0.25cm}
\caption[Simple overview]{We aim to adapt a semantic segmentation model learned from base algorithm using a graph convolutional network (GCN). The initial segmentation from base algorithm is used as basis and thereafter, GCNs are used to improve the object border outline pixel classification.}
\label{fig:Simple overview}
\end{figure}
Our contributions are summarized as follows: (1) We develop a novel method, Border-SegGCN, using GCNs to improve the semantic segmentation performance by refining the predicted boundaries. (2) We test our pipeline using two open source datasets, i.e., Camvid and Carla dataset (3) We perform the evaluation of different border widths to be used for a better performance of the procedure. (4) We evaluate the performance with a varying number of edges for the nodes in the graph. (5) We study the effect of a different number of features used as an input to the GCN network. (6) We evaluate the training with different hyper-parameters such as dropout and regularisation. (7) We also verify the performance of Border-SegGCN visually using qualitative results. (8) We prove the performance of the network using two different baseline models, i.e., Unet and DeepLabV3+. Border-SegGCN consistently improves performance when used on top of baseline approaches.
\section{Related Work}
\textbf{Semantic segmentation} is actively researched by computer vision researchers due to its application in various domains such as robotics, health care, security, etc. Most recent work is using fully convolutional neural networks for pixel-wise classification \cite{rakelly2018conditional,mou2019relation,zhang2018fully,li2017fully,lin2016scribblesup}. Various model variants have been researched \cite{chen2018encoder,schwing2015fully,jampani2016learning,vemulapalli2016gaussian} to use the contextual information for the task of segmentation \cite{mostajabi2015feedforward,dai2015convolutional,yao2012describing,ladicky2009associative} based on multi-scale inputs \cite{farabet2012learning,eigen2015predicting,lin2016efficient} or based on probabilistic graphical models \cite{pinheiro2014recurrent,chandra2016fast,chandra2017dense,chen2017deeplab}. There are many open-source datasets available for semantic segmentation, such as e.g., PASCAL \cite{everingham2010pascal}, COCO \cite{lin2014microsoft}, CamVid \cite{CamVid}, Carla \cite{dosovitskiy2017carla}, etc. Our work uses the CamVid and Carla dataset for the semantic segmentation task. We use Unet and DeepLabV3+ as our base networks for the segmentation.
\textbf{Graph neural networks} have recently been used for various applications involving the graph structured data because of their effectiveness in representing such data \cite{xie2018memory}. Some of the tasks are action recognition, body pose estimation, link prediction, etc. Graph models can be subdivided into two categories, i.e, Graph Neural Network (GNN) \cite{xu2018powerful,wu2019comprehensive,qi20173d,monti2017geometric,zhang2018link,li2017situation,jaume2018image}, and GCNs.
The first category, i.e., GNN, consists of a graph and a recurrent neural network and has a functionality of passing messages and updating nodes states which store the semantic and structural information in the neighboring nodes. For instance, \cite{qi20173d} uses a 3D graph neural network (3DGNN) with a 3D point cloud to build a k-nearest neighbor graph for RGBD semantic segmentation. Every node in the graph represents a group of points which has a hidden representation vector that is updated based on the recurrent functions.
The second category, i.e., GCN, extends the mathematical operation of convolution to graph structures. GCNs can be distinguished into two types, i.e., spectral GCNs and spatial GCNs. Spectral GCNs convert signals in graphical form into graph spectral domains, in which they can be manipulated using spectral filters. For instance, in \cite{duvenaud2015convolutional,henaff2015deep}, graph Laplacian-based CNNs are used in the spectral domain. Spectral GCNs use convolution along with neighborhood data to calculate the feature vector for the node. They were first employed for semi-supervised classification on graph-structured data \cite{DBLP:journals/corr/KipfW16}. For example, \cite{simonovsky2017dynamic} use GCNs on point cloud data in the spatial domain. \cite{si2019attention} use GCNs in a recurrent structure for skeleton based action recognition.
Both \cite{graphcut} and \cite{zhang15multiclass} have shown that image semantic segmentation can be formulated and solved using graphs. This paper focuses on applying GCNs in the context of video segmentation. The main issues discussed revolve around creating an efficient pipeline to convert video frames into graphs and optimising the pipeline to maximizing the efficiency of the GCN.
\section{Methodology}
\label{chp:Our approach}
Figure \ref{fig:Simple overview} illustrates an overview of the used pipeline. In the following section, we will discuss how we approach the graph creation from an image.
\subsection{Efficient Graph Generation}
\label{sec:Efficient graph generation}
This approach includes a refinement of borders using existing segmentation algorithms. We use the Unet \cite{ronneberger2015u} and DeepLabv3+ architecture as a base segmentation networks. The dataset used for the evaluation of this architecture is the Cambridge-driving Labeled Video Database ("CamVid") dataset \cite{BrostowFC:PRL2008} and Carla dataset \cite{dosovitskiy2017carla}. The frame size is 360 pixels wide and 480 pixels high. A mask is used to determine which nodes to compute based on their location, while omitting the rest of the nodes. This allows the graph to have the same size from frame to frame. Performing computation on the selected nodes allows decreasing computation time drastically and provides more relevant training examples to the GCN.
\begin{figure}[!htb]
\centering
\includegraphics[width=\linewidth, height=2.2cm]{figures/boolean_new2.pdf}
\vspace{0.25cm}
\caption[Boolean mask generation example]{Example of how the data is processed during the Boolean mask generation.
Left: The initial frame is passed on to the base segmentation algorithm. Center: An initial rough segmentation is retrieved. Right: Pixels are either selected (yellow) or rejected (purple) depending if they are on the border of different objects.}
\label{fig:Boolean mask generation example}
\end{figure}
To determine which nodes are selected we use the initial segmentation that our base algorithm provides: in this case the Unet or DeepLabV3+. With the pre-segmentation provided, boundaries around the objects and different classes are determined. Depending on the task at hand, the pixels that lay on the border are then selected for further processing followed by training or prediction. Figure \ref{fig:Boolean mask generation example} shows the process of generating the Boolean mask.
\subsection{Generating the Features}
\label{subsec:Generating the features}
\begin{figure}[!htb]
\centering
\includegraphics[width=\linewidth, height=6cm]{figures/features_p}
\vspace{0.25cm}
\caption[Feature extraction pipeline]{Pipeline for feature extraction from the initial frame. Each feature set is concatenated into a single feature dictionary with the pixel coordinates being the keys of the hash map. Each pixel has at least the class predicted by the base algorithm and the associated RGB values. Intermediate layer values are very dependant on the base algorithm.}
\label{fig:Feature extraction pipeline}
\end{figure}
Features used for each node consist of the intensity values from the three RGB channels of the video and the output segmented image from the base algorithm such as from Unet or DeepLabV3+. All other features consist of the intermediate values. In case of Unet, the final layers provide features and for the DeepLabV3+, the intermediate layers are used as features for input to GCN. Figure \ref{fig:Feature extraction pipeline} illustrates the pipeline for feature extraction.
\subsection{Connecting the Graph}
\label{subsec:Connecting the graph}
Based on the Boolean mask, nodes are connected that are on the border of objects. The rest of the nodes are either isolated or have only incoming connections.
\begin{figure}[!htb]
\centering
\includegraphics[width=0.8\linewidth]{figures/edges}
\vspace{0.25cm}
\caption[Edge generation pipeline]{Pipeline for generating the edges of the graph. The first segmented image provides the size of the image and thus all the potential nodes that need to be processed. The Boolean mask directs which nodes should actually be worked on. If a pixel does not reside on a border then it will remain an isolated node.}
\label{fig:Edge generation pipeline}
\end{figure}
For each node, the mapping consists of two parts: The actual coordinates of the N closest neighbours denoted by $(x_i, y_i)$ with $i<N$, and the weights that are associated with each of those neighbours denoted by $d_i$ with $i<N$. The illustration of the pipeline for generating the edges is shown in Figure \ref{fig:Edge generation pipeline}.
The weights associated for the edge between two neighbours are completely arbitrary. We chose to use a weight definition that takes into account the distance and intensity differences as inspired by \cite{graphcut}. The resulting weight definition is shown in Equation \ref{eqn:weights}.
\begin{equation}
\centering
d_{n_{12}} = \frac{1}{d_{E_{12}}}\times\exp({-\frac{ \left\lVert I_{n_{1}} - I_{n_{2}}\right\rVert}{ \left\lVert I_{255}\right\rVert}})
\label{eqn:weights}
\end{equation}
Equation \ref{eqn:weights} represents the weight between two nodes $n_1$ and $n_2$ in the $[0,1]$ range. The inverse of the Euclidean distance between these two nodes denoted as $d_{E_{12}}$. The difference in intensities of the two pixels is taken into account for determining the weight of the edge. This value is normalized and its exponent is taken to penalise two nodes of different values. Considering that several operations have to be performed on each neighbour of every selected node, the overall computational cost is $O(n^k)$ with $n$ being the number of pixels selected, and $k$ the number of closest neighbours we would like to connect to. The Boolean mask assists in directing the resources. If a node is not marked as being on the border, the number of neighbours collapses to 0 in our dictionary. Thus, no computation is performed.
\begin{figure}[!htb]
\centering
\includegraphics[width=0.7\linewidth, height=5cm]{figures/RGBdiff}
\vspace{0.25cm}
\caption[Our connection weights]{Weights taking into account Euclidean distance and difference in pixel-intensity values.}
\label{fig:Our connection weights}
\end{figure}
Figure \ref{fig:Our connection weights} illustrates the behaviour of Equation \ref{eqn:weights}. The selected node is denoted as S on the grid. The values in each square represent the value of the weight between S and the node that contains the value. If the colours match and the node is directly adjacent, then the value is maximal. On the other hand, two pixels can be next to each other but with different shades of the same colour. In this case, the value will decrease. We thus encode both the spatial information and also the pixel intensity similarity.
\subsection{Encoding the Graph}
\label{subsec:Encoding the graph}
The input to GCN requires the generation of the associated adjacency and feature matrices. The resulting size of these two matrices depend on the initial size of the frame and on the feature set that was selected. An example is the CamVid dataset which provides frames of 360 by 480 pixels in a video. This creates a square adjacency matrix of 172'800 by 172'800 pixels for each frame. The feature matrix will depend on the selected features and in the case where only intensity values of 3 RGB channels of frames are used as features, the shape will be equal to 172'800 $\times$ 3.
\section{GCN Training}
\label{sec:GCN training}
After the data has been correctly generated as explained in the previous sections (\ref{sec:Efficient graph generation}-\ref{subsec:Encoding the graph}), the training is carried out. The employed GCN architecture in our Border-SegSGN is a modification on the network given in \cite{DBLP:journals/corr/KipfW16}. The architecture used consists of consecutive graph convolutional layers and dropout layers as shown in Figure \ref{fig:Our GCN architecture}. We experimented with several different versions of network architecture but the Figure \ref{fig:Our GCN architecture} has better performance.
\begin{figure}[!htb]
\centering
\includegraphics[width=1\linewidth, height=4cm]{figures/Comp_arch.pdf}
\vspace{0.2cm}
\caption[Our GCN architecture]{Illustration of our GCN architecture based on \cite{DBLP:journals/corr/KipfW16}.}
\label{fig:Our GCN architecture}
\end{figure}
The graph convolutional layers take two input matrices: the adjacency matrix and the feature matrix. The adjacency matrix is considered immutable and thus does not change between the layers. On the other hand, the feature matrix varies with each layer.
\begin{figure}[!htb]
\centering
\includegraphics[width=\linewidth, height=7.5cm]{figures/GCNtrain_font-2.pdf}
\vspace{0.2cm}
\caption[GCN training with Boolean mask]{Pipeline representing the inputs for the GCN training in Border-SegGCN.}
\label{fig:GCN training with boolean mask}
\end{figure}
However, most importantly, we use the Boolean mask created before to direct the GCN training. For the model to fit the correct labels, we pass the mask giving no training relevance on the loss function for the nodes that are not on the border. Figure \ref{fig:GCN training with boolean mask} shows the different inputs to the GCN Network.
\section{GCN Prediction}
\label{sec:GCN prediction}
For the prediction as shown in Figure \ref{fig:GCN predicition pipeline}, the GCN takes as input the desired adjacency matrix and feature matrix, but does not require the Boolean mask. We predict the class of every node. Due to the nature of the training, the GCN output is poor on pixels that do not lie on any borders. The solution is to combine the base output of the initial algorithm with the output of the GCN where non-border pixels are assigned to their classes from the output of the base algorithm, while border pixels are assigned to their classes from the GCN output.
\begin{figure}[!htb]
\centering
\includegraphics[width=\linewidth, height=7.5cm]{figures/GCNpred-5}
\caption[GCN prediction pipeline]{Pipeline of required inputs to generate final segmented image in Border-SegGCN.}
\label{fig:GCN predicition pipeline}
\end{figure}
\section{Experiments}
\label{chp:results}
In this section, we verify the effectiveness of our proposed approach for semantic segmentation.
\subsection{Implementation Details}
We use the Unet implementation of the "Segmentation models" PyTorch library \cite{Yakubovskiy:2019}. The encoder is ResNeXt-50 (32$\times$4d) and the weights of the network are pre-trained from ImageNet.
For DeepLabV3+, we use the openly available pre-trained model from \cite{semantic_cvpr19} based on\cite{chen2018encoderdecoder}. For both models, we register forward hooks after each layer and retrieve data at each step for every passing frame.
The GCN architecture is modelled based on \cite{DBLP:journals/corr/KipfW16} with slight modifications. It consists of three graph convolutional layers with 64, 128 and 64 channels respectively. A dropout layer is inserted between each graph convolutional layer.
The GCN is built in Keras using the "Spektral" library \footnote{https://spektral.graphneural.network} and an Adam \cite{kingma2014adam} optimiser with a learning rate of 0.001. This approach assumes that each pixel is a sample and this is why it is necessary to set a batch size of $N = H \times W$, where $H$ is the height of frame and $W$ is its width. As a metric for evaluation, we use the mean intersection over union (mIoU) score as defined in \cite{semantic_cvpr19}.
\subsection{Dataset}
\textbf{Camvid} We use the "CamVid" \cite{BrostowFC:PRL2008} dataset for the evaluation of Border-SegGCN. It consists of 367 training, 233 testing, and 101 validation fully annotated frames. Each frame is $360 \times 480$ pixels. The testing frames are from two different video sequences, Seq05VD and 0001TP. We do not perform any kind of augmentation on the data for training.
We work with the 11 recommended classes out of the 31 available ones to be able to compare with other literature that have followed similar approaches of using 11 classes \cite{semantic_cvpr19}.
\textbf{Carla} \cite{dosovitskiy2017carla} is a semantic segmentation dataset for self-driving cars. t is a simulated dataset and not the real-world images. It is available as open-source. The original dataset has 4550 training images and 449 testing images. We used a subset of this dataset, i.e., 500 for training, 100 for validation, and 300 for testing. We pre-processed this dataset to have the same frame-size as CamVid dataset i.e. $360 \times 480$ pixels. We cropped the image from the center of the image. There are 13 classes for the pixels to be classified on in the dataset.
\subsection{Quantitative Results}
Table \ref{Tab:conclusion} illustrates the mIoU results for the Border-SegGCN using Unet and DeepLabV3+ models as base segmentation networks on CamVid and Carla datasets.
\begin{table}[!htb]
\centering
\begin{tabular}{ccc}
\toprule
Metric & DeepLabV3+ & Unet\\
\midrule
Base mIoU & 81.63 & 79.77 \\
Our mIoU & \textbf{81.96} & \textbf{80.49}\\
Max theoretical mIoU & 89.15 & 83.98 \\
Base mIoU on border & 39.17 & 34.59\\
Our mIoU on border & \textbf{40.92} & \textbf{45.67}\\
\bottomrule
\end{tabular}
\vspace*{0.3cm}
\normalsize
\caption[Results considering context]{Quantitative mIoU values achieved using Border-SegGCN with UNet and DeepLabV3+. Note that the theoretical maximum is computed by replacing all labels for pixels on the border with their ground truth.}
\label{Tab:conclusion}
\end{table}
DeepLabV3+ has been shown to outperform the vanilla Unet. So, it has more border pixels than the Unet model. Hence, DeepLabV3+ model has a higher theoretical maximum. The relative improvement on the Unet is much larger than that on the DeepLabV3+ model because of a lower upper limit. Thus, having less problematic borders to re-classify.
The best performing mIoU on the CamVid dataset using our Border-SegGCN achieved 81.96. In \cite{semantic_cvpr19}, they obtained a mIoU of 81.7. Using their code, we managed to reproduce 81.63. We were able to register a real improvement on this as baseline by 0.404\%. Furthermore, it is important to consider that the border pixels only constitute between 10-20\% of the entire image. This effectively creates an upper limit on the performance that the Border-SegGCN can not exceed.
We do not train Carla dataset for two epochs with Unet because if trained till the best mIoU then most of the border pixels in the image are correctly classified for this dataset. We want to show with our algorithm and experiments that if there are wrong pixels classified along the border with base algorithm then BorderSegGCN helps to rectify those pixel classification on borders. We use same parameter setting for training with Carla dataset as used for with Camvid dataset when Unet is used as baseline.
We performed an ablation study on different parameters such as border thickness, number of edges for each node, number of input features from base network to GCN, effect of using different base network, etc. on CamVid dataset. The results are sumarized in Table \ref{Tab:ablation}
\subsubsection{Border Thickness:} Figure \ref{fig:Border thickness} shows the camvid dataset frames with different border pixel thickness. Figure \ref{fig:PixelThickness} shows that except certain outliers, the overall trend is that as the amount of border pixels increases, the mIoU decreases. This can be due to the spatial intrinsic characteristics that border pixels have, which allows the GCN to better fit to them.
\begin{figure}[!htb]
\centering
\includegraphics[width=0.31\linewidth]{figures/border1}
\includegraphics[width=0.31\linewidth]{figures/border2}
\includegraphics[width=0.305\linewidth]{figures/border3}
\vspace{0.2cm}
\caption[Border thickness]{Left to right: 1, 2, 3 border pixel are selected respectively. Frames taken from CamVid dataset.}
\label{fig:Border thickness}
\end{figure}
\begin{figure}[!htb]
\centering
\subfloat[Influence of border thickness.\label{fig:PixelThickness}]{%
\includegraphics[width=2.3in]{figures/chart-9.pdf}%
}
\hfill
\subfloat[Influence of number of connections.\label{fig:NumCon}]{%
\includegraphics[width=2.3in]{figures/chart-8.pdf}%
}
\vfill
\includegraphics[width=1.2in]{figures/legend.png}%
\caption[Influence of border thickness]{Influence of graph attributes on mIoU.}
\label{fig:GraphVar}
\end{figure}
\begin{table*}[!htb]
\centering
\begin{tabular}{cc|cc|cc|cc|ll}
\toprule
\# connections & mIoU & Border Thickness & mIoU & \# features & mIoU & Dropout Rate & mIoU & Regularization & mIoU\\
\hline
2 & 79.88 & 1 & 80.11 & 11 & 78.37 & 0 & 80.20 & 1.00e-01 & 74.79\\
4 & 79.97 & 2& 80.00 & 15 & 80.45 & 0.0001 & 80.39 & 1.00e-04 & 80.12 \\
8 & 80.11 & 3& 80.16 & 256 & 81.12 & 0.001 & 80.11 & 1.00e-08 &80.24\\
16 & 80.33 & 4 & 80.07 & 271 & 80.90 & 0.1 & 80.09 & 1.00e-11 & 80.14 \\
- & - & 5& 80.10 & 319 & 80.99 & 0.5 & 80.33 & 1.00e-13 & 80.22\\
- & - & 6 & 79.96 & 510 & 81.59& 0.9 & 79.39 & - & -\\
- & - & - & - & 1039 & 81.73 & - & -& - & -\\
- & - & - & - & 1999 & 81.92 & - & - & - & -\\
\bottomrule
\end{tabular}
\vspace*{0.1cm}
\normalsize
\vspace*{0.2cm}
\caption[Results considering context]{Ablation study with quantitative mIoU values achieved using Border-SegGCN with DeepLabV3+ for Camvid dataset using different number of connections in the graph, number of border pixel thickness, number of features, dropout rate, and regularization}
\label{Tab:ablation}
\end{table*}
\subsubsection{Number of Edges:} As the number of edges is variable, we see how the number of connections each node has influences the results of improving the segmentation task (with the help of improving the border pixel classification). Figure \ref{fig:NumCon} shows that the results steadily increase as the number of edges increases because the more edges a singular node has, the more spatial information it carries about its neighbours. It is also worth mentioning that increasing indefinitely the number of edges has two adverse effects. First, it becomes computationally more expensive to generate the graph as more information is stored per node. But second, and more importantly, the impact of each edge decreases as the number of edges increases.
\subsubsection{Number of Features:} The most important consideration within the graph creation process is the feature selection step. The features have to represent enough information to the GCN for it to predict the correct pixel class. Figure \ref{fig:FeatSeg} represents the correlation between the mean IoU and the number of feature channels.
\begin{figure}[!htb]
\centering
\subfloat[Border-SegGCN with Unet\label{fig:Unet feat1}]{%
\includegraphics[width=2.3in]{figures/chart-12.pdf}%
}
\hfill
\subfloat[Border-SegGCN with DeepLabV3+\label{fig:DeepLab feat1}]{%
\includegraphics[width=2.3in]{figures/chart-14.pdf}%
}
\vfill
\includegraphics[width=1.2in]{figures/legend.png}%
\caption[Influence of number of features]{Influence of number of features on the mIoU.}
\label{fig:FeatSeg}
\end{figure}
Each step represents a different set of features, representing a combination of different feature sets. Unsurprisingly, the best results are obtained by combining the base algorithm's output, the intensity values of the frames, and a combination of intermediary layers.
\begin{table}[!htb]
\footnotesize
\centering
\begin{tabular}{cc}
\toprule
Number of features & Constituent features\\
\midrule
3 & 'I' \\
4 & 'base' + 'I'\\
19 & 'RGB' + 'd5' \\
21 & 'base' + 'I' + 'seg' + 'd5' \\
128 & 'base' + 'I' + 'seg' + 'd3' + 'd4' + 'd5'\\
\bottomrule
\end{tabular}
\vspace*{0.3cm}
\normalsize
\caption[Unet number of feature mapping]{Decomposition of the features that were used as input to GCN when Unet is a base network in Border-SegGCN. Notations: I-intensity values of the RGB channels, base-output segmented image from base network, d3-d5-last 3 decoder layer of Unet.}
\label{tab:imprwdpatterns3}
\end{table}
\begin{table}[!htb]
\footnotesize
\centering
\begin{tabular}{cc}
\toprule
Number of features & Constituent features\\
\midrule
11 & 'I' \\
15 & 'I' + 'base' \\
256 & 'mba' \\
271 & 'base'+'I'+ '$final_{6}$'+'$final_{3}$'\\
319 & 'base'+'I'+ 'seg'+'mba'\\
510 & 'I'+ '$final_{6}$'+'m1+'m2'+'seg'+'mba'\\
1039 & 'I'+ '$final_{6}$'+'m5'\\
1999 & 'base'+ 'I'+ '$final_{6}$' +'m1'+'m2'+'m3'+'m4'+'m5' \\
\bottomrule
\end{tabular}
\vspace*{0.3cm}
\normalsize
\caption[Unet number of feature mapping]{Decomposition of the features that were used as input to GCN when DeepLabV3+ is a base network in Border-SegGCN. Notations: I-intensity values of the RGB channels, base-output segmented image from base network, '$final_{1-6}$'-Segmentation heads sublayers 1 to 6, m1-m7- Encoder layers 1 to 7, 'mba'-Atrous spatial pyramid pooling output}
\label{tab:imprwdpatterns}
\end{table}
\subsubsection{GCN Dropout Optimisation:}
We used a modification of the architecture given in \cite{DBLP:journals/corr/KipfW16} that showed an improvement when the number of layers is varied from the original network. We show the dropout effects on the mean IoU score in Figure \ref{fig:Dropout}.
\begin{figure}[!htb]
\centering
\subfloat[Dropout effect on mIoU\label{fig:Dropout}]{%
\includegraphics[width=2.3in]{figures/chart-10.pdf}%
}
\hfill
\subfloat[Regularisation effect on mIoU\label{fig:Regularisation}]{%
\includegraphics[width=2.3in]{figures/chart-11.pdf}%
}
\vfill
\includegraphics[width=1.2in]{figures/legend.png}%
\vspace*{0.2cm}
\caption[Dropout and regularisation]{Influence of dropout and regularisation on Border-SegGCN.}
\label{fig:DropReg}
\end{figure}
\subsubsection{GCN Regularisation Optimisation:}
Figure \ref{fig:Regularisation} shows the mIoU improvement as the regularisation coefficient decreases. This concludes that the GCN is not prone to overfitting and thus can generalise the results.
\subsubsection{Different Base Model: DeepLabV3+:}
We use the base network Unet in the previous studies. Recent research shows that there have been architectures that have improved performance over Unet such as the DeepLabV3+ \cite{chen2018encoderdecoder}.
We observe the same trend with the Unet experiments. When increasing the number of feature channels, mIoU increases as well. However, the amount of features is much higher and requires much more computational resources with this network. Figure \ref{fig:DeepLab feat1} suggests that we are capable of improving an output from different models with our architecture pipeline.
\subsection{Time Complexity}
Total time required for each frame in the video is around 19 seconds. The average time for DeepLabV3+ is 0.08sec per frame. So, Border-SegGCN has a drawback of latency. We are introducing this technique as a stepping stone so that the research can also be focused on GCNs for improving semantic segmentation using improved techniques.
\subsection{Image Size}
This approach requires adjacency matrix has squared dimension of the given image. So, due to available GPU resources, it is not possible to do experiments on various video segmentation datasets having large frame size.
\subsection{Qualitative Results}
\label{sec:Output}
Figure \ref{fig:Output} shows qualitative examples of the output generated by our pipeline. The output segmented frames from using both, the Unet and DeepLabV3+, as base network are illustrated with their best input feature set compared to an under-performing input feature set.
\begin{figure}[!htb]
\centering
\subfloat[\label{fig:Original}]{%
\includegraphics[width=0.22\linewidth, height=2cm]{figures/org}
}
\subfloat[\label{fig:DeepLabV3+ baseline}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/deep_base.png}
}
\subfloat[\label{fig:Border-SegGCN with DeepLabV3+ good}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/deep_good.png}
}
\subfloat[\label{fig:Border-SegGCN with DeepLabV3+ bad}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/deep_bad.png}
}\hfill
\subfloat[\label{fig:Ground truth}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/ground.png}
}
\subfloat[\label{fig:Unet baseline}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/unet_base.png}
}
\subfloat[\label{fig:Border-SegGCN with Unet good}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/unet_good.png}
}
\subfloat[\label{fig:Border-SegGCN with Unet bad}]{%
\includegraphics[width=0.22\linewidth,height=2cm]{figures/unet_bad.png}
}
\vspace{0.2cm}
\caption[Output]{(a) Original. (b) DeepLabV3+ baseline. (c) Best Border-SegGCN with DeepLabV3+. (d) Poor Border-SegGCN with DeepLabV3+.
(e) Ground truth. (f) Unet baseline. (g) Best Border-SegGCN with Unet. (h) Poor Border-SegGCN with Unet.}
\label{fig:Output}
\end{figure}
We noticed from Figure \ref{fig:Output} that
\begin{itemize}
\item In the case of Unet as shown in Figure \ref{fig:Unet baseline}, when the model is under-performing due to use of wrong feature set input to the GCN, the model defaults to the statistical most likely category \ref{fig:Border-SegGCN with Unet bad}.
\item DeepLabV3+ has difficulties with objects that appear smaller in the frame \ref{fig:DeepLabV3+ baseline},
\item Our model is capable of correcting the DeepLabV3+ predictions on the outline of those objects \ref{fig:Border-SegGCN with DeepLabV3+ good}.
\item The outlines using Border-SegGCN in \ref{fig:Border-SegGCN with Unet good} are better defined as compared to \ref{fig:Unet baseline}.
\end{itemize}
\section{Conclusion}
\label{sec:Conclusion}
Our proposed model “Border-SegGCN” employs the base segmentation network such as Unet and DeepLabV3+ along with the GCN. Border-SegGCN is used to refine the object boundaries predictions. The most important task for improving the prediction performance of the base algorithm is the feature selection to be used as input to GCN. The variation due to features is the largest contributing factor in both baseline architectures, i.e., Unet and DeepLabV3+. Our experiments showed that Border-SegGCN is agnostic to the choice of baseline model. The more spatial information a node has on its neighbours, expressed by the number of edges, the better is the performance of the GCN. Finally, our experimental results show that the proposed model gives a new state-of-the-art performance on CamVid dataset using DeepLabV3+ as baseline network. It also improved the results of Unet baseline for both Camvid and Carla datasets. In future work, we will work on tackling the drawbacks of this technique, i.e. improving latency, and reducing computation complexity.
{\small
\bibliographystyle{ieee_fullname}
| {'timestamp': '2021-09-14T02:16:12', 'yymm': '2109', 'arxiv_id': '2109.05353', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05353'} | arxiv |
\section{Pressure Definition Comparison}
Here we present the key difference in pressure definition between our work and PressLight \cite{wei2019presslight}.
\subsection{Pressure in PressLight}
PressLight assumes that traffic movements are lane-to-lane, i.e., vehicles in one lane can only move into a particular lane in a link. Because of the lane-to-lane assumption, in PressLight, the pressure is defined per movement. PressLight defines the pressure of a movement as the difference of the vehicle density between an incoming lane $l$ and the outgoing lane $m$, i.e.,
\begin{equation*}
w^{*}(l, m) = \frac{x(l)}{x_{max}(l)} - \frac{x(m)}{x_{max}(m)},
\end{equation*}
PressLight then defines the pressure of an intersection $i$ as the absolute value of the sum of pressure of movements of intersection $i$, i.e.,
\begin{equation*}\label{eq:PressLight_pressure}
P^{*}_{i} = |\sum _{(l, m)\in \mathcal{M}_i} w^{*}(l, m)|,
\end{equation*}
where $\mathcal{M}_i$ is the set of permissible traffic movements of intersection $i$.
\subsection{Pressure in our work}
EMVLight assumes a lane-to-link style traffic movement as vehicles can enter either lane on the target link, see Fig 1. To present the pressure of an intersection, we first define the pressure of an incoming lane as (Definition 4)
\begin{equation*}
w(l) = \left|\frac{x(l)}{x_{max}(l)} - \sum_{\{m|(l, m)\in \mathcal{M}\}}\frac{1}{h(m)}\frac{x(m)}{x_{max}(m)}\right|.
\end{equation*}
The pressure of an intersection in EMVLight is defined as the average of the pressure of all incoming lanes (Definition 5),
\begin{equation*}\label{eq:EMVLight_pressure}
P_{i} = \frac{1}{|\mathcal{I}_i|}\sum _{l\in \mathcal{I}_i} w(l),
\end{equation*}
where $\mathcal{I}_i$ represents the set of all incoming lanes of intersection $i$.
\subsection{Comparison}
The first difference between the two definitions is that $w^{*}(l, m)$ can be both positive or negative, but $w(l)$ can only take positive values that measures the unevenness of the vehicle density in the incoming lane and that of the corresponding outgoing lanes. We take the absolute value since the direction of pressure is irrelevant here, and the goal of each agent is to minimize this unevenness. The second difference is that at the intersection level, $P^{*}_{i}$ takes a sum but $P_{i}$ takes an average. The average is more suitable for our purpose since it scales the pressure down and the unit penalty for normal agents would be relatively large as compared to rewards for pre-emption agents (Eqn. (3)). This design puts the efficient passage of EMV vehicles at the top priority. Our experimentation results indicate the proposed pressure design produces a more robust reward signal during training and outperforms PressLight in congestion reduction.
\section{Intralink EMV travel time}
The intra-link traffic pattern with the presence of an EMV on duty is complicated and is under-explored in the current literature. For simplicity, here we demonstrate a simple intra-link traffic model for a link with 2 lanes. The model can be easily extended for multiple lanes.
In a two-lane link, the EMV takes a lane and the non-EMVs on the other lane usually slows down or entirely stop. Some non-EMVs ahead of the EMV find pull-over spots in the other lane and park there. Those that cannot find a parking spot continue to drive in front of the EMV, potentially blocking the EMV passage \cite{su2021dynamic}. In this study, we propose a meso-scopic model to estimate the intra-link travel time of an EMV.
\begin{figure}[h]
\centering
\includegraphics[width=\linewidth]{images/fig_two_lanes_EMV.png}
\caption{Normal traffic state.}
\label{fig_two_lanes}
\end{figure}
Normally, the traffic flow of a link is modeled by a fundamental diagram, see Fig \ref{fig_two_lanes}. This diagram depicts a simplified relationship between the flow rate, i.e. number of vehicles passing within the unit amount of the time, and number of vehicles on a link. The max number of vehicles $H$ indicates the capacity of this link. The critical number of vehicles $F$ indicates the boundary differentiates the non-congested state and congested state. When the number of vehicles is smaller than $F$, all vehicles are traveling at the free flow speed, which is represented by the slope of $OB$. When number of vehicles is larger than $F$, vehicles are slowing down and traffic flows declines since the link is now congested. The max flow is attained when the number of vehicles is at $F$. The travel speed of vehicles in a congested state $Q$ is obtained by the slope of $OQ$.
\begin{figure}[h]
\centering
\includegraphics[width=\linewidth]{images/fig_one_lane_EMV.png}
\caption{Traffic state during EMV pre-emption.}
\label{fig_one_lane}
\end{figure}
During the EMV pre-emption, the original traffic flow relationship pictured in black are diverted into two parts, representing two lanes respectively. The green line represents the traffic conditions of the pre-emption lane, i.e. the lane where the EMV is traveling, and the orange line represents the other lane. During pre-emption, part of the vehicles originally travelling in front of the EMV pull over onto the adjacent lane, resulting a significant decrease in the max capacities of the pre-emption lane. Meanwhile, because vehicles can park onto the curbs, orange line depicts a larger maximum capacity $I$ than normal.
Regarding the max flow, the adjacent lane has a smaller max flow as the vehicles on this lane are required to slow down when EMV is on duty.
The pre-emption lane obtains a max capacity when there is one vehicle on the lane, i.e. the EMV itself. Under this circumstance, the flow rate is equivalent as the free flow speed of the EMV. However, when there are vehicles remaining in front of the EMV, the travel speed of the EMV might be slowed down, but still higher than the free flow speeds of the non-EMVs. Furthermore, the travel speed of EMV has a discrete value corresponding to the number of non-EMVs blocking. For example, pre-emption lane has a traffic state represented by $M$, and the travel speed of the EMV is obtained as the slope of $M$. We use this simple model, especially the green plot to estimate the intra-link travel time of EMV in a link as a function of number of vehicles in that link.
We calibrate this model with the SUMO environment. Intuitively, the travel speed of the EMV is affected more by the number of vehicles on the pre-emption lane than their positions. The reason behind is since the ETA is frequently updated every $\Delta T$ seconds ($\Delta T$ in our experiment), and the estimated ETA would eventually converge. Imagine there are vehicles very far away from the EMV and about to leave the intersections at $t$, their presence would not slow down the approaching EMV. Therefore, when they have left the intersection at $t+1$, we have an updated number of non-EMVs count and updated travel speed estimation.
\begin{algorithm}[h]
\caption{Multi-agent A2C Training}
\label{alg:training}
\SetEndCharOfAlgoLine{}
\SetKwInOut{Input}{Input}
\SetKwInOut{Output}{Output}
\SetKwData{ETA}{ETA}
\SetKwData{Next}{Next}
\SetKwFor{ParrallelForEach}{foreach}{do (in parallel)}{endfor}
\Input{\\\hspace{-3.7em}
\begin{tabular}[t]{l @{\hspace{3.3em}} l}
$T$ & maximum time step of an episode \\
$N_{\mathrm{bs}}$ & batch size \\
$\eta_\theta$ & learning rate for policy networks \\
$\eta_\phi$ & learning rate for value networks \\
$\alpha$ & spatial discount factor \\
$\gamma$ & (temporal) discount factor\\ $\lambda$ & regularizer coefficient
\end{tabular}
}
\Output{\\\hspace{-3.7em}
\begin{tabular}[t]{l @{\hspace{1.4em}} l}
$\{\phi_i\}_{i\in\mathcal{V}}$ & learned parameters in value networks \\
$\{\theta_i\}_{i\in\mathcal{V}}$ & learned parameters in policy networks \\
\end{tabular}
}
\textbf{initialize} $\{\phi_i\}_{i\in\mathcal{V}}$, $\{\theta_i\}_{i\in\mathcal{V}}$, $k \gets 0$, $B \gets \varnothing$;
\textbf{initialize} SUMO, $t \gets 0$, \textbf{get} $\{s^0_i\}_{i\in\mathcal{V}}$\;
\Repeat{Convergence}{
\tcc{generate trajectories}
\ParrallelForEach{$i \in \mathcal{V}$}{
\textbf{sample} $a^t_i$ from $\pi^t_i$\;
\textbf{receive} $\Tilde{r}^t_i$ and $s^{t+1}_i$\;
}
$B \gets B \cup \{(s_i^t, \pi_i^t, a_i^t, s_i^{t+1}, r_i^t)_{i\in \mathcal{V}}\}$\;
$t \gets t+1$, $k \gets k+1$\;
\If{$t == T$}{
\textbf{initialize} SUMO, $t \gets 0$, \textbf{get} $\{s^0_i\}_{i\in\mathcal{V}}$\;
}
\tcc{update actors and critics}
\If{$k == N_{\mathrm{bs}}$}{
\ParrallelForEach{$i \in \mathcal{V}$}{
\textbf{calculate} $\Tilde{r}^t_i$ (Eqn. (4)), $\Tilde{R}^t_i$ (Eqn. (5))\;
$\phi_i \gets \phi_i - \eta_\phi \nabla \mathcal{L}_v(\phi_i)$\;
$\theta_i \gets \theta_i - \eta_\theta \nabla \mathcal{L}_p(\theta_i)$\;
}
$k \gets 0, B \gets \varnothing$\;
}
}
\end{algorithm}
\section{Training Details}
\subsection{Value loss function}
With a batch of data $B = \{(s_i^t, \pi_i^t, a_i^t, s_i^{t+1}, r_i^t)_{i\in \mathcal{V}}^{t\in \mathcal{T}}\}$, each agent's value network is trained by minimizing the difference between bootstrapped estimated value and neural network approximated value
\begin{equation}
\label{eqn:L_v}
\mathcal{L}_v(\phi_i) = \frac{1}{2|B|} \sum_{B}\Big( \Tilde{R}^t_i - V_{\phi_i}(\Tilde{s}^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i}) \Big)^2.
\end{equation}
\subsection{Policy loss function}
Each agent's policy network is trained by minimizing its policy loss
\begin{align}
\label{eqn:L_p}
\mathcal{L}_p(\theta_i) = -& \frac{1}{|B|}\sum_{B} \bigg(\log \pi_{\theta_i}(a_i^t|s^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i}) \Tilde{A}^t_i \\
&- \lambda \sum_{a_i \in \mathcal{A}_i} \pi_{\theta_i} \log \pi_{\theta_i} (a_i | s^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i}) \bigg),
\end{align}
where $\Tilde{A}^t_i = \Tilde{R}^t_i - V_{\phi_i^-}(\Tilde{s}^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i})$ is the estimated advantage which measures how much better the action $a^t_i$ is as compared to the average performance of the policy $\pi_{\theta_i}$ in the state $s_i^t$. The second term is a regularization term that encourage initial exploration, where $\mathcal{A}_i$ is the action set of agent $i$. For an intersection as shown in Fig. 1, $\mathcal{A}_i$ contains 8 traffic signal phases.
\subsection{Training algorithm}
Algorithm \ref{alg:training} shows the multi-agent A2C training process.
\section{Implementation Details}
\subsection{Implementation details for synthetic $\text{grid}_{5 \times 5}$}
\begin{itemize}
\item dimension of $s^t_{\mathcal{V}_i}$: $5 \times (8+8+4+2)=110$
\item dimension of $\Tilde{s}^t_{\mathcal{V}_i}$: $5 \times (8+8+4+2)=110$
\item dimension of $\pi^{t-1}_{\mathcal{N}_i}$: $4 \times 8 = 32$
\item Policy network $\pi_{\theta_i}(a_i^t|s^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i})$:
\texttt{concat[}$110 \xrightarrow[]{\textrm{FC}} 128$ReLu, $32 \xrightarrow[]{\textrm{FC}} 64$ReLu\texttt{]} $ \xrightarrow[]{} 64$LSTM $ \xrightarrow[]{\textrm{FC}}8$Softmax
\item Value network $V_{\phi_i}(\Tilde{s}^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i})$: \texttt{concat[}$110 \xrightarrow[]{\textrm{FC}} 128$ReLu, $32 \xrightarrow[]{\textrm{FC}} 64$ReLu\texttt{]} $ \xrightarrow[]{} 64$LSTM $ \xrightarrow[]{\textrm{FC}}1$Linear
\item Each link is $200m$. The free flow speed of the EMV is $12m/s$ and the free flow speed for non-EMVs is $6m/s$.
\item Temporal discount factor $\gamma$ is $0.99$ and spatial discount factor $\alpha$ is $0.90$.
\item Initial learning rates $\eta_\phi$ and $\eta_\theta$ are both 1e-3 and they decay linearly. Adam optimizer is used.
\item MDP step length $\Delta t = 5s$ and for secondary pre-emption reward weight $\beta$ is $0.5$.
\item Regularization coefficient is $0.01$.
\end{itemize}
\subsection{Implementation details for $\text{Manhattan}_{16 \times 3}$}
The implementation is similar to the synthetic network implementation, with the following differences:
\begin{itemize}
\item Initial learning rates $\eta_\phi$ and $\eta_\theta$ are both 5e-4.
\item Since the avenues and streets are both one-directional, the number of actions of each agent are adjusted accordingly.
\end{itemize}
\end{document}
\section{Conclusion}
In this paper, we proposed a decentralized reinforcement learning framework, EMVLight, to facilitate the efficient passage of EMVs and reduce traffic congestion at the same time.
Leveraging the multi-agent A2C framework, agents incorporate dynamic routing and cooperatively control traffic signals to reduce EMV travel time and average travel time of non-EMVs.
Evaluated on both synthetic and real-world map, EMVLight significantly outperforms the existing methods.
Future work will explore more realistic microscopic interaction between EMV and non-EMVs, efficient passage of multiple EMVs and closing the sim-to-real gap.
\section{Experimentation}
In this section, we demonstrate our RL framework using Simulation of Urban MObility (SUMO) \cite{lopez2018microscopic}
SUMO is an open-source traffic simulator capable of simulating both microscopic and macroscopic traffic dynamics, suitable for capturing the EMV's impact on the regional traffic as well as monitoring the overall traffic flow. A pipeline is established between the proposed RL framework and SUMO, i.e., the agents collects observations from SUMO and preferred signal phases are fed back into SUMO.
\subsection{Datasets and Maps Descriptions}
We conduct the following experiments based on both synthetic and real-world map.
\paragraph{Synthetic $\text{Grid}_{5\times 5}$} We synthesize a $5 \times 5$ traffic grid, where intersections are connected with bi-directional links. Each link contains two lanes. We design 4 configurations, listed in Table \ref{tab_synthetic_configuration}.
The origin (O) and destination (D) of the EMV are labelled in Fig.~\ref{fig_synthetic_map}.
The traffic for this map has a time span of 1200s. We dispatch the EMV at $t =600s$ to ensure the roads are compacted when it starts travel.
\begin{figure}[h]
\centering
\includegraphics[width=0.9\linewidth]{images/fig_synthetic_map.png}
\caption{\emph{Left}: the synthetic $\text{grid}_{5\times 5}$. \emph{Right}: an intersection illustration in SUMO, the teal area are inductive loop detected area. Origin and destination for EMV are labeled.}
\label{fig_synthetic_map}
\end{figure}
\begin{table}[h]
\centering
\fontsize{9.0pt}{10.0pt} \selectfont
\begin{tabular}{@{}ccccc@{}}
\toprule[1pt]
\multicolumn{1}{c}{\multirow{2}{*}{Config}} & \multicolumn{2}{l}{Traffic Flow (veh/lane/hr)} & \multirow{2}{*}{Origin} & \multirow{2}{*}{Destination} \\ \cmidrule(lr){2-3}
\multicolumn{1}{c}{} & Non-peak & Peak & & \\
\cmidrule{1-5}
1 & 200 & 240 & \multirow{2}{*}{N,S} & \multirow{2}{*}{E,W} \\
\cmidrule{1-3}
2 & 160 & 320 & & \\
\cmidrule{1-5}
3 & 200 & 240 & \multicolumn{2}{c}{Randomly} \\
\cmidrule{1-3}
4 & 160 & 320 & \multicolumn{2}{c}{generated} \\ \bottomrule[1pt]
\end{tabular}
\caption{Configuration for Synthetic $\text{Grid}_{5\times 5}$. Peak flow is assigned from 400s to 800s and non-peak flow is assigned out of this period. For Config. 1 and 2, the vehicles enter the grid from North and South, and exit toward East and West.}
\label{tab_synthetic_configuration}
\end{table}
\paragraph{$\text{Manhattan}_{16\times 3}$}
This is a $16 \times 3$ traffic network extracted from Manhattan Hell's Kitchen area (Fig.~\ref{fig_manhattan}) and customized for demonstrating EMV passage. In this traffic network, intersections are connected
by 16 one-directional streets and 3 one-directional avenues. We assume each avenue contains four lanes and each street contains two lanes so that the right-of-way of EMVs and pre-emption can be demonstrated. The traffic flow for this map is generated from open-source NYC taxi data. Both the map and traffic flow data are publicly available.\footnote{https://traffic-signal-control.github.io/}
The origin and destination of EMV are set to be far away as shown in Fig.~\ref{fig_manhattan}
\begin{figure}[h]
\centering
\includegraphics[width=\linewidth]{images/fig_Manhattan_map.png}
\caption{Manhattan map: a 16-by-3 traffic network in Hell's Kitchen area. Origin and destination for the EMV dispatching are labeled.}
\label{fig_manhattan}
\end{figure}
\begin{table*}[t]
\centering
\fontsize{9.0pt}{10.0pt} \selectfont
\setlength\tabcolsep{3.4pt}
\begin{tabular}{@{}cccccc|ccccc@{}}
\toprule[1pt]
\multirow{2}{*}{Method
} & \multicolumn{5}{c|}{EMV Travel Time $T_{\textrm{EMV}}$ [s]} & \multicolumn{5}{c}{Average Travel Time $T_{\textrm{avg}}$ [s]} \\ \cmidrule(l){2-11}
& Config 1 & Config 2 & Config 3 & Config 4 & $\text{Manhattan}_{16\times 3}$ & Config 1 & Config 2 & Config 3 & Config 4 & $\text{Manhattan}_{16\times 3}$ \\ \midrule
FT w/o EMV & N/A & N/A & N/A & N/A & N/A & 353.43 & 371.13 & 314.25 & 334.10 & 1649.64 \\ \midrule
W + Static + FT & 257.20 & 272.00 & 259.20 & 243.80 & 487.20 & 372.19 & 389.13 & 342.49 & 355.05 & 1811.03 \\
W + Static + MP & 255.00 & 269.00 & 261.20 & 245.40 & 461.80 & 349.38 & 352.54 & 307.91 & 322.68 & 708.13 \\
W + Static + CL & 281.20 & 286.20 & 289.80 & 277.80 & 492.20 & 503.35 & 524.26 & 488.12 & 509.55 & 2013.54 \\
W + Static + PL & 276.00 & 282.20 & 271.40 & 275.00 & 476.00 & 358.18 & 369.45 & 332.98 & 338.95 & 1410.76 \\ \midrule
W + dynamic + FT & 229.60 & 231.20 & 228.60 & 227.20 & 442.20 & 370.09 & 393.40 & 330.13 & 345.50 & 1699.30 \\
W + dynamic + MP & 226.20 & 234.60 & 224.20 & 217.60 & 438.80 & 345.45 & 348.43 & 313.26 & 325.72 & 721.32 \\
W + dynamic + CL & 273.40 & 269.60 & 281.00 & 270.80 & 450.20 & 514.29 & 536.78 & 502.12 & 542.63 & 1987.86 \\
W + dynamic + PL & 251.20 & 257.80 & 247.00 & 268.80 & 436.20 & 359.31 & 342.59 & 340.11 & 349.20 & 1412.12 \\ \midrule
EMVLight & \textbf{198.60} & \textbf{192.20} & \textbf{199.20} & \textbf{196.80} & \textbf{391.80} & \textbf{322.40} & \textbf{318.76} & \textbf{301.90} & \textbf{321.02} & \textbf{681.23} \\ \bottomrule[1pt]
\end{tabular}%
\caption{Performance comparison of different methods evaluated in the four configurations of the synthetic traffic grid as well as Manhattan Map. For both metrics, the lower value indicates better performance. The lowest values are highlighted in bold. The average travel time of Manhattan map (1649.64) is retrieved from data.
}
\label{tab_performance_review}
\end{table*}
\subsection{Baselines}
Due to the lack of existing RL methods for efficient EMV passage, we select traditional methods and RL methods for each subproblem and combine them to set up baselines.
For traffic signal pre-emption, the most intuitive and widely used approach is extending green light period for EMV passage at each intersection which results in a \emph{Green Wave} \cite{corman2009evaluation}.
\textbf{Walabi (W)} \cite{bieker2019modelling} is
an effective rule-based method that implemented Green Wave for EMVs in SUMO environment. We integrate Walabi with combinations of routing and traffic signal control strategies introduced below as baselines.
\emph{Routing baselines:}
\begin{itemize}
\item \textbf{Static} routing is performed when EMV is dispatched and the route remains fixed as the EMV travels. We adopt A* search as the baseline since it is an powerful extension to the Dijkstra's shortest path algorithm and is used in many real-time applications because of its optimality. \footnote{Our implementation of A* search employs a Manhattan distance as the heuristic function.}
\item \textbf{Dynamic} routing relies on real-time information of traffic conditions. To set up the baseline, we run A* every 50s as EMV travels. This is because running the full A* to update optimal route is not as efficient as our proposed dynamic Dijkstra's algorithm.
\end{itemize}
\emph{Traffic signal control baselines:}
\begin{itemize}
\item \textbf{Fixed Time (FT)}: Cyclical fixed time traffic phases with random offset \cite{roess2004traffic} is a policy that split all phases with an predefined green ratio.
It is the default strategy in real traffic signal control.
\item \textbf{Max Pressure (MP)}: The state-of-the-art (SOTA) network-level signal control strategy based on pressure \cite{varaiya2013max}. It aggressively select the phase with maximum pressure to smooth congestion.
\item \textbf{Coordinated Learner (CL)}: A Q-learning based coordinator which directly learns joint local value functions for adjacent intersections \cite{van2016coordinated}.
\item \textbf{PressLight (PL)}: A RL method aiming to optimize the pressure at each intersection\cite{wei2019presslight}.
\end{itemize}
\subsection{Results}
We evaluate performance of models under two metrics: \emph{EMV travel time}, which reflects routing and pre-emption ability, and \emph{average travel time}, which indicates the ability of traffic signal control for efficient vehicle passage. The performance of our EMVLight and the baselines in both the synthetic and the Manhattan map is shown in Table \ref{tab_performance_review}.
The results of all methods are averaged over five independent runs and RL methods are tested with random seeds. We observe that EMVLight outperforms all baseline models under both metrics.
In terms of EMV travel time $T_{\textrm{EMV}}$, the dynamic routing baseline performs better than static routing baselines. This is expected since dynamic routing considers the time-dependent nature of traffic conditions and update optimal route accordingly. EMVLight further reduces EMV travel time by 18\% in average as compared to dynamic routing baselines. This advantage in performance can be attributed to the design of secondary pre-emption agents. This type of agents learn to ``reserve a link" by choosing signal phases that help clear the vehicles in the link to encourage high speed EMV passage (Eqn.~\eqref{eqn:reward}).
As for average travel time $T_{\textrm{avg}}$, we first notice that the traditional pre-emption technique (W+Static+FT) indeed increases the average travel time by around 10\% as compared to a traditional Fix Time strategy without EMV (denoted as ``FT w/o EMV" in Table \ref{tab_performance_review}), thus decreasing the efficiency of vehicle passage. Different traffic signal control strategies have a direct impact on overall efficiency. Fixed Time is designed to handle steady traffic flow. Max Pressure, as a SOTA traditional method, outperforms Fix Time and, surprisingly, outperforms both RL baselines in terms of overall efficiency. This shows that pressure is an effective indicator for reducing congestion and this is why we incorporate pressure in our reward design. Coordinate Learner performs the worst probably because its reward is not based on pressure. PressLight doesn't beat Max Pressure because it has a reward design that focuses on smoothing vehicle densities along a major direction, e.g. an arterial. Grid networks with the presence of EMV make PressLight less effective. Our EMVLight improves its pressure-based reward design to encourage smoothing vehicle densities of all directions for each intersection. This enable us to achieve an advantage of 5\% over our best baselines (Max Pressure).
\subsubsection{Ablation study on pressure and agent types}
We propose three types of agents and design their rewards (Eqn.~\eqref{eqn:reward}) based on our improved pressure definition and heuristics.
In order to see how our improved pressure definition and proposed special agents influence the results, we (1) replace our pressure definition by that defined in PressLight, (2) replace secondary pre-emption agents with normal agents and (3) replace primary pre-emption agents with normal agents.
\begin{table}[b]
\centering
\fontsize{9.0pt}{10.0pt} \selectfont
\begin{tabular}{@{}cccc|c@{}}
\toprule[1pt]
Ablations & (1) & (2) & (3) & EMVLight\\ \midrule
$T_{\text{EMV}}$ [s] & \textbf{197} & 289 & 320 & 199 \\
$T_{\text{avg}}$ [s] & 361.05 & 347.13 & 359.62 & \textbf{322.40} \\ \bottomrule[1pt]
\end{tabular}
\caption{Ablation study on pressure and agent types. Experiments are conducted on the Config 1 synthetic $\text{grid}_{5 \times 5}$.}
\label{tab_ablation_reward}
\end{table}
Table \ref{tab_ablation_reward} shows the results of these ablations: (1) PressLight-style pressure (see Appendix) yields a slightly smaller EMV travel time but significantly increases the average travel time; (2) Without secondary pre-emption agents, EMV travel time increases by 45\% since almost no ``link reservation" happened; (3) Without primary pre-emption agents, EMV travel time increases significantly, which shows the importance of pre-emption.
\subsubsection{Ablation study on fingerprint}
In multi-agent RL, fingerprint has been shown to stabilize training and enable faster convergence.
In order to see how fingerprint affects training in EMVLight, we remove the fingerprint design, i.e., policy and value networks are changed from $\pi_{\theta_i}(a_i^t|s^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i})$ and $V_{\phi_i}(\Tilde{s}^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i})$ to $\pi_{\theta_i}(a_i^t|s^t_{\mathcal{V}_i})$ and $V_{\phi_i}(\Tilde{s}^t_{\mathcal{V}_i})$, respectively.
Fig.~\ref{fig_FP_comparison} shows the influence of fingerprint on training. With fingerprint, the reward converges faster and suffers from less fluctuation, confirming the effectiveness of fingerprint.
\begin{figure}[ht]
\centering
\includegraphics[width=0.9\linewidth]{images/fig_FP_comparison.jpeg}
\caption{Reward convergence with and without fingerprint. Experiments are conducted on Config 1 synthetic $\text{grid}_{5 \times 5}$.}
\label{fig_FP_comparison}
\end{figure}
\section{Introduction}
Emergency vehicles (EMVs) are vehicles including ambulances, fire trucks, and police cars, which respond to critical events such as medical emergencies, fire disasters, and criminal activities. Emergency response time is the key indicator of a city's emergency management capability. Reducing response time saves lives and prevents property loss. For instance, the survivor rate from a sudden cardiac arrest without treatment drops 7\% - 10\% for every second elapsed, and there is barely any chance to survive after 8 minutes. EMV travel time, the time interval for an EMV to travel from a rescue station to an incident site, accounts for a major portion of the emergency response time. However, overpopulation and urbanization have been exacerbating road congestion, making it more and more challenging to reduce the average EMV travel time. Records \cite{end-to-end-response-times} have shown that even with a decline in average emergency response time, the average EMV travel time increases from 7.2 minutes in 2015 to 10.1 minutes in 2021 in New York City. Needless to say, there is a severe urgency and significant benefit for shortening the average EMV travel time on increasingly crowded roads.
Existing works have studied strategies to reduce the travel time of EMVs by route optimization and traffic signal pre-emption. Route optimization usually refers to the search for a time-based shortest path. The traffic network (e.g., city road map) is modeled as a graph with intersections as nodes and road segments between intersections as edges. Based on the time a vehicle needs to travel through each edge (road segment), route optimization calculates an optimal route such that an EMV can travel from the rescue station to the incident site in the least amount of time. In addition, as the EMV needs to be as fast as possible, the law in most places requires non-EMVs to yield to emergency vehicles sounding sirens, regardless of the traffic signals at intersections. Even though this practice gives the right-of-way to EMVs, it poses safety risks for vehicles and pedestrians at the intersections. To address this safety concern, existing methods have also studied traffic signal pre-emption which refers to the process of deliberately altering the signal phases at each intersection to prioritize EMV passage.
However, as the traffic condition constantly changes, an optimal route returned by route optimization can potentially become suboptimal as an EMV travels through the network. Moreover, traffic signal pre-emption has a significant impact on the traffic flow, which would change the fastest route as well. Thus, the optimal route should be updated with real-time traffic flow information, i.e., the route optimization should be solved in a dynamic (time-dependent) way. As an optimal route can change as an EMV travels through the traffic network, the traffic signal pre-emption would need to adapt accordingly. In other words, the subproblems of route optimization and traffic signal pre-emption are coupled and should be solved simultaneously in real-time. Existing approaches does not address this coupling.
In addition, most of the existing models on emergency vehicle service have a single objective of reducing the EMV travel time. As a result, their traffic signal control strategies have an undesirable effect of increasing the travel time of non-EMVs, since only EMV passage is optimized. In this paper, we aim to perform route optimization and traffic signal pre-emption to not only reduce EMV travel time but also to reduce the average travel time of non-EMVs. In particular, we address the following two key challenges:
\begin{itemize}[noitemsep]
\item \textbf{How to dynamically route an EMV to a destination under time-dependent traffic conditions in a computationally efficient way?} As the congestion level of each road segment changes over time, the routing algorithm should be able to update the remaining route as the EMV passes each intersection. Running the shortest-path algorithm each time the EMV passes through an intersection is not efficient. A computationally efficient dynamic routing algorithm is desired.
\item \textbf{How to coordinate traffic signals to not only reduce EMV travel time but reduce the average travel time of non-EMVs as well?} To reduce EMV travel time, only the traffic signals along the route of the EMV need to be altered. However, to further reduce average non-EMV travel time, traffic signals in the whole traffic network need to be operated cooperatively.
\end{itemize}
To tackle these challenges, we propose \textbf{EMVLight}, a decentralized multi-agent reinforcement learning framework with a dynamic routing algorithm to control traffic signal phases for efficient EMV passage. Our experimental results demonstrate that EMVLight outperforms traditional traffic engineering methods and existing RL methods under two metrics - EMV travel time and the average travel time of all vehicles - on different traffic configurations.
\section{Dynamic Routing}
Dijkstra's algorithm is an algorithm that finds shortest path between a given node and every other nodes in a graph, which has been used for EMV routing. The EMV travel time along each link is estimated based on the number of vehicles on that link. We refer to it as the \emph{intra-link travel time.} Dijkstra's algorithm takes as input the traffic graph, the intra-link travel time and a destination, and can return the time-based shortest path as well as estimated travel time from each intersection to the destination. The latter is usually referred to as the \emph{estimated time of arrival} (ETA) of each intersection.
However, traffic conditions are constantly changing and so does EMV travel time along each link. Moreover, EMV pre-emption techniques alters traffic signal phases, which will significantly change the traffic condition as the EMV travels. The pre-determined shortest path might become congested due to stochasticity and pre-emption. Thus, updating the optimal route dynamically can facilitate EMV passage. In theory we can run Dijkstra's algorithm frequently as the EMV travels through the network to take into account the updated EMV intra-link travel time, but this is inefficient.
To achieve dynamics routing, we extend Dijkstra's algorithm to efficiently update the optimal route based on the updated intra-link travel times. As shown in Algorithm~\ref{alg:ETA_prepopulation}, first a prepopulation process is carried out where a (static) Dijkstra's algorithm is run to get the ETA from each intersection to the destination. For each intersection, the next intersection along the shortest path is also calculated and stored. We assume this process can be done before the EMV starts to travel. This is reasonable since a sequence of processes, including call-taker processing, are performed before the EMVs are dispatched. Once the pre-population process is finished, we can update $\mathsf{ETA}$ and $\mathsf{Next}$ for each intersection efficiently in parallel, since the update only depends on information of neighboring intersections. Please see Appendix for how intra-link travel time is estimated in real time.
\begin{algorithm}[t]
\caption{Dynamic Dijkstra's for EMV routing}
\label{alg:ETA_prepopulation}
\SetEndCharOfAlgoLine{}
\SetKwInOut{Input}{Input}
\SetKwInOut{Output}{Output}
\SetKwData{ETA}{ETA}
\SetKwData{Next}{Next}
\SetKwFor{ParrallelForEach}{foreach}{do (in parallel)}{endfor}
\Input{\\\hspace{-3.7em}
\begin{tabular}[t]{l @{\hspace{3.3em}} l}
$G=(\mathcal{V}, \mathcal{E})$ & traffic map as a graph \\
$T^t = [T_{ij}^t]$ & intra-link travel time at time $t$ \\
$i_d$ & index of the destination
\end{tabular}
}
\Output{\\\hspace{-3.7em}
\begin{tabular}[t]{l @{\hspace{1.5em}} l}
$\mathsf{ETA}^t = [\mathsf{ETA}^t_i]$ & ETA of each intersection \\
$\mathsf{Next}^t = [\mathsf{Next}^t_i]$ & next intersection to go \\
& from each intersection
\end{tabular}
}
\tcc{pre-population}
$\mathsf{ETA}^0, \mathsf{Next}^0$ $=$ \texttt{Dijkstra}$(G, T^0, i_d)$\;
\tcc{dynamic routing}
\For{$t = 0 \to T$}{
\ParrallelForEach{$i \in \mathcal{V}$}{
$\mathsf{ETA}_i^{t+1} \gets \min_{(i, j)\in \mathcal{E}} (\mathsf{ETA}_j^t + T_{ji}^t)$\;
$\mathsf{Next}_i^{t+1} \gets \arg\min_{\{j|(i, j)\in \mathcal{E}\}}(\mathsf{ETA}_j^{t} + T_{ji}^t$)\;}}
\end{algorithm}
\begin{remark}
In static Dijkstra's algorithm, the shortest path is obtained by repeatedly query the $\mathsf{Next}$ attribute of each node from the origin until we reach the destination. In our dynamic Dijkstra's algorithm, since the shortest path changes, at a intersection $i$, we only care about the immediate next intersection to go to, which is exactly $\mathsf{Next}_i$.
\end{remark}
\section{Preliminaries}
\begin{figure}[b]
\includegraphics[width=\linewidth]{images/fig_traffic_movements_pressure.png}
\centering
\caption{Traffic movements illustration and an example pressure calculation for incoming lane \#2.}
\label{fig_movements}
\end{figure}
\begin{definition}[traffic map, link, lane]
A traffic map can be represented by a graph $G(\mathcal{V}, \mathcal{E})$, with intersections as nodes and road segments between intersections as edges. We refer to a one-directional road segment between two intersections as a link. A link has a fixed number of lanes, denoted as $h(l)$ for lane $l$. Fig.~\ref{fig_movements} shows 8 links and each link has 2 lanes.
\end{definition}
\begin{definition}[Traffic movements]
A traffic movement $(l,m)$ is defined as the traffic traveling across an intersection from an incoming lane $l$ to an outgoing lane $m$. The intersection shown in Fig.~\ref{fig_movements} has 24 permissible traffic movements. The set of all permissible traffic movements of an intersection is denoted as $\mathcal{M}$.
\end{definition}
\begin{definition}[Traffic signal phase]
A traffic signal phase is defined as the set of permissible traffic movements.
As shown in Fig.~\ref{fig_phases}, an intersection with 4 links has 8 phases.
\end{definition}
\begin{figure}[t]
\includegraphics[width=\linewidth]{images/fig_both_phases.png}
\centering
\caption{\emph{Top}: 8 signal phases; \emph{Left}: phase \#2 illustration; \emph{Right}: phase \#5 illustration.
}
\label{fig_phases}
\end{figure}
\begin{definition}[Pressure of an incoming lane]
The pressure of an incoming lane $l$ measures the unevenness of vehicle density between lane $l$ and corresponding out going lanes in permissible traffic movements. The vehicle density of a lane is $x(l)/x_{max}(l)$, where $x(l)$ is the number of vehicles on lane $l$ and $x_{max}(l)$ is the vehicle capacity on lane $l$, which is related to the length of a lane. Then the pressure of an incoming lane $l$ is
\begin{equation}
w(l) = \left|\frac{x(l)}{x_{max}(l)} - \sum_{\{m|(l, m)\in \mathcal{M}\}}\frac{1}{h(m)}\frac{x(m)}{x_{max}(m)}\right|,
\label{eqn:lane_pressure}
\end{equation}
where $h(m)$ is the number of lanes of the outgoing link which contains $m$. In Fig.~\ref{fig_movements}, $h(m)=2$ for all the outgoing lanes. An example for Eqn.~\eqref{eqn:lane_pressure} is shown in Fig.~\ref{fig_movements}.
\end{definition}
\begin{definition}[Pressure of an intersection]\label{def_intersection_pressure}
The pressure $P$ of an intersection is the average of the pressure of all incoming lanes.
\end{definition}
The pressure of an intersection indicates the unevenness of vehicle density between incoming and outgoing lanes in an intersection. Intuitively, reducing the pressure leads to more evenly distributed traffic, which indirectly reduce congestion and average travel time of vehicles.
\section{Reinforcement Learning Formulation}
While dynamic routing directs the EMV to the destination, it does not take into account the possible waiting times for red lights at the intersections. Thus, traffic signal pre-emption is also required for the EMV to arrive at the destination in the least amount of time. However, since traditional pre-emption only focuses on reducing the EMV travel time, the average travel time of non-EMVs can increase significantly. Thus, we set up traffic signal control for efficient EMV passage as a decentralized RL problem. In our problem, an RL agent controls the traffic signal phases of an intersection based on local information. Multiple agents coordinate the control signal phases of intersections cooperatively to \textbf{(1)} reduce EMV travel time and \textbf{(2)} reduce the average travel time of non-EMVs. First we design 3 agent types. Then we present agent design and multi-agent interactions.
\subsection{Types of agents for EMV passage}
When an EMV is on duty, we distinguish 3 types of traffic control agents based on EMV location and routing (Fig.~\ref{fig_secondary}). An agent is a \emph{primary pre-emption agent} $i_p$ if an EMV is on one of its incoming links. The agent of the next intersection $i_s = \mathsf{Next}_{i_p}$ is refered to as a \emph{secondary pre-emption agent}.
The rest of the agents are \emph{normal agents}. We design these types since different agents have different local goals, which is reflected in their reward designs.
\subsection{Agent design}
\begin{itemize}
\item \textbf{State}: The state of an agent $i$ at time $t$ is denoted as $s^t_i$ and it includes the number of vehicles on each outgoing lanes and incoming lanes, the distance of the EMV to the intersection, the estimated time of arrival ($\mathsf{ETA}$), and which link the EMV will be routed to ($\mathsf{Next}$), i.e.,
\begin{equation}
s^t_i = \{x^t(l), x^t(m), d^t_{\text{EMV}}[L_{ji}], \mathsf{ETA}^{t'}_i, \mathsf{Next}^{t'}_i \}
\end{equation}
where $L_{ji}$ represents the links incoming to intersection $i$, and with a slight abuse of notation $l$ and $m$ denote the set of incoming and outgoing lanes, respectively. For the intersection shown in Fig.~\ref{fig_movements}, $d^t_{\text{EMV}}$ is a vector of four elements. For primary pre-emption agents, one of the elements represents the distance of EMV to the intersection in the corresponding link. The rest of the elements are set to -1. For all other agents, $d^t_{\text{EMV}}$ are padded with -1.
\item \textbf{Action}: Prior work has focused on using phase switch, phase duration and phase itself as actions. In this work, we define the action of an agent as one of the 8 phases in Fig.~\ref{fig_phases}; this enables more flexible signal patterns as compared to the traditional cyclical patterns.
Due to safety concerns, once a phase has been initiated, it should remain unchanged for a minimum amount of time, e.g. 5 seconds. Because of this, we set our MDP time step length to be 5 seconds to avoid rapid switch of phases.
\item \textbf{Reward}: PressLight has shown that minimizing the pressure is an effective way to encourage efficient vehicle passage, we adopt similar idea for normal agents. For secondary pre-emption agents we additionally encourage less vehicle on the link where the EMV is about to enter in order to encourage efficient EMV passage. For primary pre-emption agents, we simply assign a unit penalty at each time step to encourage fast EMV passage. Thus, depending on the agent type, the local reward for agent $i$ at time $t$ is
\end{itemize}
\begin{equation}
\label{eqn:reward}
r_{i}^{t} = \begin{cases}
-P_{i_p}^{t} & i \notin \{i_p, i_s\},\\
- \beta P_{i_s}^{t} - \frac{1-\beta}{|L_{i_pi_s}|}\sum\limits_{l\in L_{i_pi_s}} \frac{x(l)}{x_{max}(l)} & i=i_s,\\
-1 & i=i_p.
\end{cases}
\end{equation}
\begin{figure}[t]
\centering
\includegraphics[width=\linewidth]{images/fig_agent_types.png}
\caption{Three types of agents.}
\label{fig_secondary}
\end{figure}
\textbf{Justification of agent design.} The quantities in local agent state can be obtained at each intersection using various technologies. Numbers of vehicles on each lane $(x^t(l), x^t(m))$ can be obtained by vehicle detection technologies, such as inductive loop \cite{gajda2001vehicle} based on the hardware installed underground. The distance of the EMV to the intersection $d^t_{EMV}[L_{ji}]$ can be obtained by \emph{vehicle-to-infrastructure} technologies such as VANET\cite{buchenscheit2009vanet}, which broadcasts the real-time position of a vehicle to an intersection. Prior work by \citet{wang2013design} and \citet{noori2016connected} have explored these technologies for traffic signal pre-emption.
The dynamic routing algorithm (Algorithm~\ref{alg:ETA_prepopulation}) can provide $(\mathsf{ETA}, \mathsf{Next})$ for each agent at every time step. However, due to the stochastic nature of traffic flows, updating the route too frequently might confuse the EMV driver, since the driver might be instructed a new route, say, every 5 seconds.
There are many ways to ensure reasonable frequency. One option is to inform the driver only once while the EMV is travels in a single link. We implement it by updating the state of an RL agent $(\mathsf{ETA}^{t'}_i, \mathsf{Next}^{t'}_i)$ at the time step when the EMV travels through half of a link. For example, if the EMV travels through a link to agent $i$ from time step 11 to 20 in constant speed, then dynamic routing information in $s_i^{16}$ to $s_i^{20}$ are the same, which is $(\mathsf{ETA}_i^{15}, \mathsf{Next}_i^{15})$, i.e., $t'=15$.
As for the reward design, one might wonder how an agent can know its type. As we assume an agent can observe the state of its neighbors, agent type can be inferred from the observation. This will become clearer below.
\section{Related Work}\label{sec_related_work}
\textbf{Conventional routing optimization and traffic signal pre-emption for EMVs.}
Although, in reality, routing and pre-emption are coupled, the existing methods usually solve them separately. Many of the existing approaches leverage Dijkstra's shortest path algorithm to get the optimal route \cite{wang2013development, Mu2018Route, kwon2003route, JOTSHI20091}. An A* algorithm for ambulance routing has been proposed by \citet{nordin2012finding}. However, as this line of work assumes that the routes and traffic conditions are fixed and static, they fail to address the dynamic nature of real-world traffic flows. Another line of work has considered the change of traffic flows over time. \citet{ziliaskopoulos1993time} have proposed a shortest-path algorithm for time-dependent traffic networks, but the travel time associated with each edge at each time step is assumed to be known in prior. \citet{musolino2013travel} propose different routing strategies for different times in a day (e.g., peak/non-peak hours) based on traffic history data at those times. However, in the problem of our consideration, routing and pre-emption strategies can significantly affect the travel time associated with each edge during the EMV passage, and the existing methods cannot deal with this kind of real-time changes. \citet{haghani2003optimization} formulated the dynamic shortest path problem as a mixed-integer programming problem. \citet{koh2020real} have used RL for real-time vehicle navigation and routing. However, both of these studies have tackled a general routing problem, and signal pre-emption and its influence on traffic have not been modeled.
Once an optimal route for the EMV has been determined, traffic signal pre-emption is deployed. A common pre-emption strategy is to extend the green phases of green lights to let the EMV pass each intersection along a fixed optimal route \cite{wang2013development, bieker2019modelling}. \citet{Asaduzzaman2017APriority} have proposed pre-emption strategies for multiple EMV requests.
Please refer to \citet{Lu2019Literature} and \citet{humagain2020systematic} for a thorough survey of conventional routing optimization and traffic signal pre-emption methods. We would also like to point out that the conventional methods prioritize EMV passage and have significant disturbances on the traffic flow which increases the average non-EMV travel time.
\textbf{RL-based traffic signal control.}
Traffic signal pre-emption only alters the traffic phases at the intersections where an EMV travels through. However, to reduce congestion, traffic phases at nearby intersections also need to be changed cooperatively. The coordination of traffic signals to mitigate traffic congestion is referred to as traffic signal control which has been addressed by leveraging deep RL in a growing body of work. Many of the existing approaches use Q-learning \cite{abdulhai2003reinforcement, prashanth2010reinforcement, wei2019presslight, wei2019colight, zheng2019frap, ThousandLights}. \citet{Zang_Yao_Zheng_Xu_Xu_Li_2020} leverage meta-learning algorithms to speed up Q-learning for traffic signal control. Another line of work has used actor-critic algorithms for traffic signal control \cite{el2013multiagent, aslani2017adaptive, chu2019multi}. \citet{xu2021hierarchically} propose a hierarchical actor-critic method to encourage cooperation between intersections. Please refer to \citet{wei2019survey} for a review on traffic signal control methods. However, these RL-based traffic control methods focus on reducing the congestion in the traffic network and are not designed for EMV pre-emption. In contrast, our RL framework is built upon state-of-the-art ideas such as max pressure and is designed to reduce both EMV travel time and overall congestion.
\subsection{Multi-agent Advantage Actor-critic}
We adopt a multi-agent advantage actor-critic (MA2C) framework similar to \citet{chu2019multi}. The difference is that our local state includes dynamic routing information and our local reward encourages efficient passage of EMV. Here we briefly introduce the MA2C framework. Please refer to \citet{chu2019multi} for additional details.
In a multi-agent network $G(\mathcal{V}, \mathcal{E})$, the neighborhood of agent $i$ is denoted as $\mathcal{N}_i = \{ j | ji\in \mathcal{E} \textrm{ or } ij\in \mathcal{E}\}$. The local region of agent $i$ is $\mathcal{V}_i = \mathcal{N}_i \cup i$. We define the distance between two agents $d(i, j)$ as the minimum number of edges that connect them. For example, $d(i, i) = 0$ and $d(i, j)=1, \forall j \in \mathcal{N}_i$. In MA2C, each agent learns a policy $\pi_{\theta_i}$ (actor) and the corresponding value function $V_{\phi_i}$ (critic), where ${\theta_i}$ and ${\phi_i}$ are learnable neural network parameters of agent $i$.
\textbf{Local Observation.} In an ideal setting, agents can observe the states of every other agent and leverage this global information to make a decision. However, this is not practical in our problem due to communication latency and will cause scalability issues. We assume agents can observe its own state and the states of its neighbors, i.e., $s^t_{\mathcal{V}_i} = \{s^t_j|j\in \mathcal{V}_i\}$. The agents feed this observation to its policy network $\pi_{\theta_i}$ and value network $V_{\phi_i}$.
\textbf{Fingerprint.} In multi-agent training, each agent treats other agents as part of the environment, but the policy of other agents are changing over time. \citet{foerster2017stabilising} introduce \emph{fingerprints} to inform agents about the changing policies of neighboring agents in multi-agent Q-learning. \citet{chu2019multi} bring fingerprints into MA2C. Here we use the probability simplex of neighboring policies $\pi^{t-1}_{\mathcal{N}_i} = \{\pi^{t-1}_j|j\in \mathcal{N}_i\}$ as fingerprints, and include it into the input of policy network and value network. Thus, our policy network can be written as $\pi_{\theta_i}(a_i^t|s^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i})$ and value network as $V_{\phi_i}(\Tilde{s}^t_{\mathcal{V}_i}, \pi^{t-1}_{\mathcal{N}_i})$, where $\Tilde{s}^t_{\mathcal{V}_i}$ is the local observation with spatial discount factor, which is introduced below.
\textbf{Spatial Discount Factor and Adjusted Reward.} MA2C agents cooperatively optimize a global cumulative reward. We assume the global reward is decomposable as $r_t = \sum_{i\in \mathcal{V}} r^t_i$, where $r^t_i$ is defined in Eqn.~\eqref{eqn:reward}. Instead of optimizing the same global reward for every agent, \citet{chu2019multi} propose a spatial discount factor $\alpha$ to let each agent pay less attention to rewards of agents far away. The adjusted reward for agent $i$ is
\begin{equation}
\Tilde{r}_i^t = \sum_{d=0}^{D_i}\Big( \sum_{j\in\mathcal{V}|d(i, j)=d} (\alpha)^d r^t_j\Big),
\end{equation}
where $D_i$ is the maximum distance of agents in the graph from agent $i$. When $\alpha > 0$, the adjusted reward include global information, it seems this is in contradiction to the local communication assumption. However, since reward is only used for offline training, global reward information is allowed. Once trained, the RL agents can control traffic signal without relying on global information.
\textbf{Temporal Discount Factor and Return.}
The local return $\Tilde{R}^t_i$ is defined as the cumulative adjusted reward $\Tilde{R}^t_i := \sum_{\tau=t}^T \gamma^{\tau-t} \Tilde{r}^\tau_i$, where $\gamma$ is the temporal discount factor and $T$ is the length of an episode. we can estimate the local return using value function,
\begin{equation}
\Tilde{R}^t_i = \Tilde{r}^t_i + \gamma V_{\phi_i^-}(\Tilde{s}^{t+1}_{\mathcal{V}_i}, \pi^{t}_{\mathcal{N}_i}|\pi_{\theta_{-i}^-}),
\end{equation}
where $\phi_i^-$ means parameters $\phi_i$ are frozen and $\theta_{-i}^-$ means the parameters of policy networks of all other agents are frozen.
\textbf{Network architecture and training.} As traffic flow data are spatial temporal, we leverage a long-short term memory (LSTM) layer along with fully connected (FC) layers for policy network (actor) and value network (critic). Our multi-agent actor-critic training pipeline is similar to that in \citet{chu2019multi}. We provide neural architecture details, policy loss expression, value loss expression as well as a training pseudocode in the Appendix.
| {'timestamp': '2022-06-29T02:08:39', 'yymm': '2109', 'arxiv_id': '2109.05429', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05429'} | arxiv |
\section{Introduction}
\begin{figure}[!t]
\centering
\includegraphics[width=0.47\textwidth]{figs/fig1-example.pdf}
\caption{An example document-level drug-gene-mutation relation.
\textbf{\emph{\textcolor{drug}{cobimetinib}}} never co-occurs with \textbf{\emph{\textcolor{gene}{MAP2K1}}} or \textbf{\emph{\textcolor{variant}{K57T}}} in any paragraph.}
\label{fig:motivating-example}
\end{figure}
Prior work on information extraction tends to focus on binary relations within sentences. However, practical applications often require extracting complex relations across large text spans.
This is especially important in high-value domains such as biomedicine, where obtaining high recall of the latest findings is crucial.
For example, \autoref{fig:motivating-example} shows a ternary (drug, gene, mutation) relation signifying that a tumor with MAP2K1 mutation K57T is sensitive to cobimetinib, yet the entities never co-occur in any single paragraph. Such precision oncology knowledge is key for determining personalized treatment for cancer patients, but it is scattered among a vast biomedical literature of more than 30 million papers, with over 1 million being added each year\footnote{\url{http://www.ncbi.nlm.nih.gov/pubmed}}.
Recently, there has been increasing interest in cross-sentence relation extraction, but most existing work still focuses on short text spans. \citet{quirk-poon-2017-distant} and \citet{peng-etal-2017-cross} restrict extraction to three consecutive sentences and \citet{verga-etal-2018-simultaneously} to abstracts.
DocRED~\cite{yao-etal-2019-docred}, a popular document-level relation extraction dataset, consists of Wikipedia introduction sections, each with only eight sentences on average. Further, half of the relation instances reside in a single sentence, all effectively in a single paragraph.
\begin{figure*}[!t]
\centering
\includegraphics[width=0.97\textwidth]{figs/formulation.pdf}
\caption{Decomposing document-level $n$-ary relation extraction into relation detection and argument resolution.}
\label{fig:formulation}
\end{figure*}
To the best of our knowledge, \citet{jia-etal-2019-document} is the first to consider relation extraction in full-text articles, which is considerably more challenging. They use the CKB dataset \cite{patterson2016clinical} for evaluation where each document contains, on average, 174 sentences, spanning 39 paragraphs.
Additionally, while prior work focuses mainly on binary relations, \citet{jia-etal-2019-document} follows \citet{peng-etal-2017-cross} to extract ternary relations.
However, while \citet{jia-etal-2019-document} admits relation instances for which the three arguments never co-occur in a paragraph, it still requires that the two arguments for each binary subrelation co-occur at least once in a paragraph, leaving one fifth of findings out of reach for their method.
All this prior work considers document-level relation extraction as a single monolithic problem, which presents major challenges in both inference and learning. Despite recent progress, there are still significant challenges in modeling long text spans using state-of-the-art neural architectures, such as LSTM and transformer. Moreover, direct supervision is scarce and task-specific self-supervision, such as distance supervision, becomes extremely noisy when applied beyond short text spans.
In this paper, we explore an alternative paradigm by decomposing document-level relation extraction into local relation detection and global reasoning over argument resolution.
Specifically, we represent $n$-ary relation using Davidsonian semantics and combine paragraph-level relation classification with discourse-level argument resolution using global reasoning rules (e.g., transitivity over argument resolution). Each component problem resides in short text spans and their corresponding self-supervision is much less error-prone.
Our approach takes inspiration from modular neural networks \cite{andreas2016neural} and neural logic programming \cite{rocktaschel&riedel16} in decomposing a complex task into local neural learning and global structured integration.
However, instead of learning from end-to-end direct supervision, we admit modular self-supervision for the component problems, which is more readily available. Our method can thus be viewed as applying deep probabilistic logic \cite{wang-poon-2018-deep} to combine modular self-supervision and joint inference with global reasoning rules.
This modular approach enables us to not only handle long text spans such as full-text articles like \citet{jia-etal-2019-document}, but also expand extraction to the significant portion of cross-paragraph relations that are out of reach to all prior methods.
We conduct a thorough evaluation in biomedical machine reading for precision oncology, where such cross-paragraph relations are especially prevalent.
Our method outperforms prior state of the art such as multiscale learning \cite{jia-etal-2019-document} and graph neural networks~\cite{zeng-etal-2020-double} by over 20 absolute F1 points. The gain is particularly pronounced among the most challenging relations whose arguments never co-occur in a paragraph.
\section{Document-Level Relation Extraction}
Let $E_1,\dotsc,E_n$ be entities that co-occur in a document $D$. Relation extraction amounts to classifying whether a relation $R$ holds for $E_1,\dotsc,E_n$ in $D$.
For example, in \autoref{fig:formulation}, $R$ is the relation of precision cancer drug response, and $E_1, E_2, E_3$ represent drug cobimetinib, gene MAP2K1, mutation K57T, respectively.
The relation mention spans multiple paragraphs and dozens of sentences. Direct extraction is challenging and ignores the elaborate underlying linguistic phenomena. The drug-response relation is explicitly mentioned in the last paragraph, though it is between ``\emph{MEK inhibitors}'' and ``\emph{MAP2K1 mutations}''. Meanwhile, the top paragraph states the $\tt ISA$ relation between ``\emph{cobimetinib}'' and ``\emph{MEK inhibitors}'', as apparent from the apposition. From the middle paragraph one can infer the $\tt ISA$ relation between ``\emph{K57T}'' and ``\emph{MAP2K1 mutations}''. Finally, ``\emph{MAP2K1 mutants}'' in the last paragraph can be resolved with ``\emph{MAP2K1 mutations}'' in the middle based on semantic similarity.
Combining these, we can conclude that the drug-response relation holds for (cobimetinib, MAP2K1, K57T) in this document (\autoref{fig:formulation}), even though cobimetinib never co-occurs with MAP2K1 or K57T in any paragraph.
Formally, we represent $n$-ary relation extraction by neo-Davidsonian semantics \cite{parsons}:
\begin{multline*}
R_D(E_1,\cdots,E_n) \doteq \exists T\in D~\exists r.\\
[R_T(r)\wedge A_1(r,E_1)\wedge \cdots\wedge A_n(r,E_n)
\end{multline*}
Here, $T$ is a text span in $D$, $r$ is a reified event variable introduced to represent relation $R$, and the arguments are represented by binary relations with the event variable. The distributed nature of this representation makes it suitable for arbitrary $n$-ary relations and does not require drastic changes when arguments are missing or when new arguments are added.
Given this representation, document-level relation extraction is naturally decomposed into local relation detection (e.g., classifying if $R_T(r)$ holds for some paragraph $T$) and global argument resolution (e.g., classifying $A_i(r,E_i)$).
Entity-level argument resolution can be reduced to mention-level argument resolution $A(r,E) \doteq \exists e.~[{\tt Mention}(e,E) \wedge A(r,e)]$, where ${\tt Mention}(e,E)$ signifies that $e$ is an entity mention of $E$. Additionally, the transitivity rule applies: \[A(r,e) \wedge {\tt Resolve}(r,e,e') \implies A(r,e')\]
Here, ${\tt Resolve}(r,e,e')$ signifies that the mentions $e,e'$ are interchangeable in the context of relation mention $r$.
For brevity, in this paper we drop the relation context $r$ and simply consider ${\tt Resolve}(e,e')$.
If $e,e'$ are coreferent or semantically equivalent, as in (MAP2K1 mutations, MAP2K1 mutants), $\tt Resolve$ obviously holds. More generally, $\tt ISA$ (e.g., K57T and MAP2K1 mutations) and $\tt PartOf$ (e.g., a mutation and a cell line containing it) may also signify resolution:
\begin{align*}
{\tt Coref}(e,e')\implies {\tt Resolve}(e,e')\\
{\tt ISA}(e,e')\implies {\tt Resolve}(e,e')\\
{\tt PartOf}(e,e')\implies {\tt Resolve}(e,e')
\end{align*}
Also, transitivity generally holds for $\tt Resolve$:
\begin{multline*}
{\tt Resolve}(e,e')\wedge {\tt Resolve}(e',e'')\\
\implies {\tt Resolve}(e,e'')
\end{multline*}
\section{Modular Self-Supervision}
\label{sec:modular}
\begin{table}[!t]
\small
\centering
\begin{tabular}{@{}ccl@{}}
\toprule
& \multicolumn{2}{c}{\bf Modular Self-Supervision} \\ \midrule
\makecell[l]{\textbf{Relation}\\\textbf{Detection}} & \makecell[c]{Distant Supervision} & \makecell[l]{CIVC, GDKD,\\OncoKB} \\ \midrule
\multirow{2}{*}{\makecell[l]{\textbf{Argument}\\ \textbf{Resolution}}} & \makecell[c]{Data Programming} & \makecell[l]{Identical mentions,~~\\apposition} \\ \cmidrule(l){2-3}
& \makecell[c]{Joint Inference} & Transitivity \\ \bottomrule
\end{tabular}
\caption{Modular self-supervision for relation detection and argument resolution.}
\label{tab:ssl}
\end{table}
Our problem formulation makes it natural to introduce modular self-supervision for relation detection and argument resolution (Table \ref{tab:ssl}).
\paragraph{Relation Detection} The goal is to train a classifier for $R_T(r)$. In this paper, we consider paragraphs as candidates for $T$ and use distant supervision \cite{mintz-etal-2009-distant} for self-supervision. Specifically, knowledge bases (KBs) with known relation instances for $R$ are used to annotate examples from unlabeled text. Co-occurring mention tuples of known relations are annotated as positive examples and those not known to have relations are sampled as negative examples. These examples are then used to train a paragraph-level relation classifier. Here, we leverage the fact that paragraph-level distant supervision is much less noise-prone, but document-level relation mentions still observe similar textual patterns as paragraph-level ones, as can be seen in \autoref{fig:formulation}.
\paragraph{Argument Resolution} The goal is to train a classifier for ${\tt Resolve}(e,e')$ based on local context for entity mentions $e,e'$. As stated in the prior section, $\tt Resolve$ is strictly more general than coreference and may involve $\tt ISA$ and $\tt PartOf$ relations. For self-supervision, we introduce data programming rules that capture identical mentions and appositives.
These are used as seed self-supervision to annotate high-precision resolution instances. In turn, additional instances in the same document can be generated by applying the transitivity rule. E.g., in \autoref{fig:formulation}, by deriving ${\tt Resolve}$(cobimetinib, MEK inhibitor) in the top paragraph based on the apposition, we may annotate additional $\tt Resolve$ instances between ``\emph{cobimetinib}'' and ``\emph{MEK inhibitors}'' in the bottom paragraph. As in distant supervision, there will be noise, but on balance, such joint inference helps learn more general resolution patterns.
\section{Our Model}
\eat{
\begin{figure*}[!t]
\centering
\includegraphics[width=0.95\textwidth]{figs/model.pdf}
\caption{Neural architectures for relation detection and argument resolution.}
\label{fig:model}
\end{figure*}
}
\autoref{fig:architecture} shows our document-level relation extraction system, which uses deep probabilistic logic \cite{wang-poon-2018-deep} to incorporate modular self-supervision and joint inference.
\begin{figure}[!t]
\centering
\includegraphics[width=0.43\textwidth]{figs/dpl.pdf}
\caption{Our approach for document-level relation extraction applies deep probabilistic logic to incorporate modular self-supervision and joint inference for relation detection and argument resolution.}
\label{fig:architecture}
\end{figure}
\paragraph{Prediction Module} The prediction module comprises transformer-based neural models~\cite{transformer} for local relation detection and global argument resolution.
For relation detection, let $(m_1,\cdots,m_n)$ be a candidate co-occurring mention tuple in a paragraph $T$. We input $T$ to a transformer-based relation classifier, with mentions $m_i$ dummified.\footnote{Alternatively, we can add entity markers for each mention.}
For argument resolution, let $(m, m')$ be a candidate mention pair. We compute the contextual representation using a transformer model for both mentions and classify the pair using a comparison network. The input concatenates contextual representations of the entities as well as their element-wise multiplication.
For the detailed neural architectures, see Appendix \ref{sec:neural-architecture}.
\paragraph{Supervision Module} As described in the previous section, the supervision module incorporates the relation KBs and resolution data programming rules as seed self-supervision, as well as reasoning rules such as resolution transitivity for joint inference. Note that these self-supervision rules can be noisy, but for simplicity we still treat them as hard constraints. Deep probabilistic logic offers a principled way to soften them and model their noisiness, which can be investigated in future work.
\paragraph{Learning} The prediction and supervision modules define a joint probabilistic distribution
\[P(K,Y|X)\propto \prod_{v\in K}~\Phi_{v}(X, Y)\cdot\prod_i~\Psi(X_i, Y_i)\]
Here, $K$ represents the self-supervision and $(X_i, Y_i)$ the input-output pairs of relation detection and argument resolution. $\Phi, \Psi$ are the supervision and prediction modules, respectively.
Learning is done via variational EM. In the E-step, we compute a variational approximation $q(Y)\propto P(Y|K,X)$ using loopy belief propagation, based on current $\Phi,\Psi$. In the M-step, we treat $q(Y)$ as the probabilistic labels and refine parameters of $\Phi,\Psi$.
As aforementioned, we treat the self-supervision in $\Phi$ as hard constraints, so the M-step simplifies to fine-tuning the transformer-based models for relation detection and argument resolution, treating $q(Y)$ as probabilistic labels.
\paragraph{Inference} After learning, given a test document and candidate entities and mentions, it is straightforward to run the neural modules for relation detection and argument resolution. Additionally, we would incorporate joint inference for argument resolution as in self-supervision (e.g., transitivity) using loopy belief propagation.
\eat{
we assemble our model using specialized modules, akin to \citet{andreas2016neural}.
These modules are specialized in relation detection and argument resolution respectively.
\Cref{fig:modular-network} illustrates the assembly of our modular network for document-level \emph{ternary} relation extraction,
where we compose \emph{binary} \textcolor{relation-classification}{subrelation detection} modules for ternary relation detection,
and apply \textcolor{argument-resolution}{argument resolution} modules separately for each argument.
\begin{figure}[!ht]
\centering
\includegraphics[width=0.48\textwidth]{figs/modular-network.pdf}
\caption{Assembly of our modular network.
Modules in \textcolor{relation-classification}{blue} are specialized in subrelation detection.
Modules in \textcolor{argument-resolution}{green} are specialized in argument resolution.
The subrelation module $R_{23}$ is not used in this case.}
\label{fig:modular-network}
\end{figure}
\subsection{Subrelation Detection}
We decompose the $n$-ary relation $R$ into binary subrelations $R_{ij}$ ($1\leq i,j\leq n$).\footnote{
Subrelations of other arities are also possible.}
Given a discourse unit $d_{ij}$ that contains entity mentions $x_i$ and $x_j$,
the subrelation detection module computes the following probability of $R_{ij}$ as below:
\begin{equation}
P(\exists e.R_{ij}(e,x_i,x_j)|d_{ij},x_i,x_j;\bm{\theta}_{ij})
\end{equation}
where $\bm{\theta}_{ij}$ are learned parameters.
The module architecture is illustrated in \Cref{fig:model}(a).
Motivated by the superior contextual modeling capabilities of transformer-based models~\cite{transformer},
we utilize a pre-trained transformer encoder~\cite{pubmedbert} and fine-tune it for subrelation detection.
The module input is a discourse unit where a \texttt{[CLS]} token is prepended.
We replace mentions $x_i$ and $x_j$ with special tokens \texttt{[X$_i$]} and \texttt{[X$_j$]},
to prevent the module from overfitting to memorizing the mentions.
The last-layer hidden state $\bm{h}_\texttt{[CLS]}$ is passed to a feed-forward classifier to compute the probability:
\begin{equation}
\text{classifier}(\bm{h})=\text{sigmoid}(\text{MLP}(\bm{h}))
\end{equation}
where MLP is a multilayer perceptron, the details of which are given in the Appendix.
\begin{figure*}[!t]
\centering
\includegraphics[width=0.9\textwidth]{figs/model.pdf}
\caption{Architecture of modules for
\textcolor{relation-classification}{\bf subrelation classification} and \textcolor{argument-resolution}{\bf argument resolution}
used in our network.}
\label{fig:model}
\end{figure*}
\subsection{Argument Resolution}
The core of argument resolution is classify whether two entity mentions have one of the semantic relations, such as \emph{coreference} and \emph{is-a} relations.
Instead of building the whole argument resolution module from scratch,
we utilize an unsupervised coreference system
and extend it by incorporating a neural component,
which is self-trained for improving coverage of the semantic relations.
\begin{equation}
P(I_i(m_i,x_i)|D,m_i,x_i,\bm{\phi}_i)
\end{equation}
The unsupervised coreference system is a multi-sieve pass system~\cite{raghunathan-etal-2010-multi,lee-etal-2011-stanfords}.
It applies tiers of deterministic resolution models one at a time from highest to lowest precision,
to classify whether two mentions corefer.
For example, the first sieve (i.e., highest precision) requires an exact string match between two mentions,
whereas the last one (i.e., lowest precision) implements pronominal coreference resolution.
Each tier builds on predictions of previous tiers in the sieve, guaranteeing
that stronger features are given precedence over weaker ones.\footnote{We refer the reader to \citet{raghunathan-etal-2010-multi,lee-etal-2011-stanfords} for full details.}
We extend this system by replacing a core sieve, Precise Constructs, with a neural model.
Precise Constructs use a set of hand-crafted syntactic features to link two mentions
(e.g., appositive, relative pronoun, predicate nominative).
While Precise Constructs are highly precise, their coverage is relatively low, and adding new features requires high expertise.
We replace them with a neural model which we will show captures more syntactic patterns while remaining highly precise.
Concretely, for two mentions $(m,n)$,
we adopt a BERT-based model to compute $P(I(m,n)|D,\bm{\psi})$.
The architecture is similar to the one used in \citet{joshi-etal-2020-spanbert} for coreference resolution.
An example is shown in \Cref{fig:model}(b): given two mentions \emph{PIK3CA mutation} and \emph{H1047R},
the model encodes the context of two mentions into hidden states.
For each mention span, the model averages last-layer hidden states of mention tokens to generate a contextual representation.
Contextual representations of two mentions are then passed to a pairwise feed-forward network to compute the probability.
Our resolution component utilizes the extended multi-sieve pass system to construct document-level resolution graphs
and derives resolution evidences for mention pairs in each document.
Lastly, our approach combines relation and resolution components to compute joint probability of relation and resolution evidences in \Cref{eq:model}.
With a search over all choices of $S_i(a_i,b_i)$ in $D$,
our approach not only is capable of computing the target relation probability $P(R(d,v))$ in \Cref{eq:formulation},
but also provides evidences $Z_i,X_i,Y_i$ to support the prediction.
These evidences are especially important for assisted curation.
\section{Learning}\label{sec:learning}
In this section,
we describe how to leverage distant supervision and variational EM to learn parameters for our model components,
when human annotations are not available.
\subsection{Distant Supervision for Relation Component}
Distant supervision uses an existing knowledge base (KB) and unlabeled text to generate training examples,
which can be extremely noisy for entities that are \emph{not} in the same paragraph.
However, for our relation evidence model, since we restrict the input to a consecutive text segment,
we can still leverage distant supervision to generate training examples.
Specifically, if a entity pair $(a,b)$ is known to have the relation in the KB,
we generate positive examples by (i) extracting all text segments from a document in which the entity mention pair $(a, b)$ co-occur,
(ii) prepending a \texttt{[CLS]} token to each segment,
(iii) and then replacing mentions $(a,b)$ with corresponding special tokens \texttt{[X]} and \texttt{[Y]}.
We randomly sample co-occurring entity mention pairs not known to have the relation to generate negative examples.
To further reduce the noise in generated examples,
we add two restrictions:
(1) we require that a segment contains a limited number of sentences and should not span across paragraphs;
(2) we only keep positive examples for an entity pair if the number of extracted segments from a document is above a threshold.
We will shown in Sec. that these restrictions lead to better performance.
The generated examples are divided into training and development sets.
During training, a weighted sampler is used to generate mini batches so that the overall positive and negative training samples are balanced.
Parameters $\bm{\theta}$ in $P(Z_i|S_i(a_i,b_i),\bm{\theta})$ are learned via minimization of cross-entropy loss.
We train the model until the best performance is achieved on the dev set.
\subsection{Variational EM for Resolution Component}
Learning the resolution component involves finding parameters $\bm{\psi}$ and
mention pair resolution links $\textbf{I}=\{I(m_1,n_1),...,I(m_i,n_i),...\}$ which are likely under the posterior distribution
$P(\bm{\psi},\textbf{I}|D)$.
We approximate the posterior using a simple factored representation.
Our variational approximation takes the following form:
\begin{equation}
Q(\bm{\psi},\textbf{I})=\left( \prod_i q_i(I(m_i,n_i)) \right)\delta(\bm{\psi})
\end{equation}
Inspired by \citet{haghighi-klein-2010-coreference},
we use a mean field approach to update each of the RHS factors in turn to minimize the KL-divergence
between the current variational posterior and the true model posterior.
\noindent\textbf{Updating parameters} $\delta(\bm{\psi})$:
This factor places point estimates on a single value, just as in hard EM.
Updating it involves finding the value which maximizes the model (expected) log-likelihood under other factors.
Given the variational posteriors $\{q_i(\cdot)\}$ for mention resolution links,
$\delta(\bm{\psi})$ is a point estimate and is updated with:
\begin{equation}
\delta(\bm{\psi})=\argmax_{\bm{\psi}} \mathbb{E}_{Q_{-\delta}}\ln{P(\bm{\psi},\textrm{I}|D)}
\end{equation}
where $Q_{-\delta}$ denotes all factors of the variational approximation except for the factor being updated.
\noindent\textbf{Updating resolution links} $\{q_i(I(m_i,n_i))\}$:
Each mention resolution link factor $q_i(I(m_i,n_i))$ maintains a soft approximation,
and is updated with the standard mean field form:
\begin{equation}
q_i(I(m_i,n_i))\propto\exp\{\mathbb{E}_{Q_{-q_i}}\ln{P(\bm{\psi},\textrm{I}|D)}\}
\end{equation}
Since there is no direct supervision, it is impractical to learn all mention resolution links $\textbf{I}=\{...,I(m_i,n_i),...\}$ at once.
We instead introduce a curriculum learning algorithm as described in \Cref{algo:learn-resolution-component}.
Given a set of entity mentions $M$ in document $D$, we first initialize \textsc{seed\_links} between mentions
using high-precision resolution models (e.g. exact string match).
If two entities have a linked mention pair,
we add distant supervised links (\textsc{ds\_links}) to their other mention pairs that co-occur in a sentence.
With \textsc{seed\_links} and \textsc{ds\_links}, we alternately update parameters $\delta^t(\bm{\psi})$ and learn new resolution links $\Delta$, holding approximations to the other fixed.
These newly learned links are used to generate more distant supervised links,
and to existing links for the next iteration.
The details of \textsc{seed\_links} and \textsc{ds\_links} are provided in Appendices.
\begin{algorithm}[!t]
\SetAlgoCaptionSeparator{}
\SetAlCapNameFnt{\small}
\SetAlCapFnt{\small}
\DontPrintSemicolon
\small
\SetKwInOut{Input}{Input}
\SetKwInOut{Output}{Output}
\Input{Document $D$ and entity mentions $M$.}
\Output{Learned parameters $\delta^*(\bm{\psi})$ and mention resolution links $\textbf{I}^*$.}
$\textbf{I}^0\leftarrow \textsc{seed\_links}(M\times M)$\;
$\textbf{I}^0\leftarrow \textbf{I}^0\cup \textsc{ds\_links}(\textbf{I}^0, M\times M)$\;
\For{$t=1:T$}{
$\delta^t(\bm{\psi})\leftarrow\argmax_{\bm{\psi}}\mathbb{E}_{Q_{-\delta}}\ln{P(\bm{\psi},\textrm{I}^{t-1}|D)}$\;
$\Delta\leftarrow\varnothing$\;
\For{$(m_i,n_i) \in M\times M-\textrm{\bf I}^{t-1}$}{
$\widetilde{\textbf{I}}\leftarrow \textbf{I}^{t-1}\cup\{I(m_i,n_i)\}$\;
$q_i\propto\exp\{\mathbb{E}_{Q_{-q_i}}\ln{P(\bm{\psi},\widetilde{\textbf{I}}|D)}\}$\;
\uIf{$q_i> \text{threshold}$}{
$\Delta\leftarrow\Delta\cup\{I(m_i,n_i)\}$\;
}
}
$\textbf{I}^t\leftarrow\textbf{I}^{t-1}\cup\Delta$\;
$\textbf{I}^t\leftarrow \textbf{I}^t\cup \textsc{ds\_links}(\textbf{I}^t, M\times M)$\;
}
\Return $\delta^*(\bm{\psi})=\delta^t(\bm{\psi}), \textbf{I}^*=\textbf{I}^t$ \;
\caption{Resolution Component Learning\label{algo:learn-resolution-component}}
\end{algorithm}
\section{Inference}
To find out whether an entity pair $(e_1, e_2)$ in a document $D$ has the relation $R(e_1, e_2)$, we adopt a two-stage process.
First, given a set of entity mentions $M$ in $D$,
the resolution component $P(I(m,n)|D,\bm{\psi})$ predicts the resolution link between each mention pair $(m,n)$,
which is used to construct the document-level resolution graph.
Second, we search the document-level resolution graph for any mention pair $(a_i, b_i)$ that satisfies the following conditions:
(1) $I(a_i, e_1)\wedge I(b_i,e_2)$; (2) $a_i$ and $b_i$ co-occur in a $k$-sentence segment $S_i(a_i,b_i)$.
Given the segment $S_i(a_i,b_i)$,
if the relation evidence $Z_i$ is true according the prediction of relation component $P(Z_i|S_i(a_i,b_i),\bm{\theta})$,
then the entity pair $(e_1,e_2)$ has the relation $R(e_1, e_2)$.
}
\eat{
Formally, we propose to represent n-ary relation using Davidsonian semantics and model document-level relation extraction by combining paragraph-level relation classification with discourse-level argument resolution using global reasoning rules (e.g., transitivity over argument resolution). Each component problem resides in short text spans and can be effectively solved by training transformer-based neural networks using the corresponding self-supervision, which is much less error-prone.
Our approach takes inspiration from modular neural networks \cite{andreas2016neural} and neural logic programming \cite{rocktaschel&riedel16} in decomposing a complex end problem into component neural learning and global combination (via syntactic parse in modular neural networks and backward chaining in neural logic programming).
However, instead of learning from end-to-end direct supervision, we admit modular self-supervision for the component problems, which is more readily available. Our method can thus be viewed as applying deep probabilistic logic \cite{wang-poon-2018-deep} to combine modular self-supervision and joint inference with global reasoning rules.
}
\section{Experiments}
\begin{table}[!t]
\small
\centering
\begin{tabular}{@{}lrrr@{}}
\toprule
& CKB & ~~~~CKB$^{\tt HARD}$\xspace & DocRED \\ \midrule
\textbf{Documents} & 430 & 391~ & 1000 \\
\textbf{Relations} & 1904 & 332~ & 12323 \\
\textbf{Candidates} & 17744 & 12122~ & 198395 \\
\multicolumn{4}{l}{\hspace{-0.62em}\textbf{Document-level statistics (mean)}} \\
~~~~Words & 5480.1 & 5576.2~ & 200.7 \\
~~~~Sentences & 170.6 & 173.6~ & 8.1 \\
~~~~Paragraphs & 38.9 & 39.3~ & 1.0 \\
\multicolumn{4}{l}{\textbf{\hspace{-0.62em}Minimal span for relations (mean)}} \\
~~~~Words & 161.8 & 717.7~ & 30.9 \\
~~~~Sentences & 5.7 & 22.6~ & 2.2 \\
~~~~Paragraphs & 1.7 & 4.8~ & 1.0 \\ \bottomrule
\end{tabular}
\caption{Comparison of statistics among CKB, CKB$^{\tt HARD}$\xspace, and DocRED (validation; test annotations are not publicly available). DocRED comprises short Wikipedia introduction sections, whereas CKB features full-text articles. CKB also features relations spanning much longer text, especially in the CKB$^{\tt HARD}$\xspace subset.
}
\label{tab:test-data-statistics}
\end{table}
In this section, we study how our modular self-supervision approach performs in document-level relation extraction. A popular dataset is DocRED~\cite{yao-etal-2019-docred}, which features Wikipedia introduction sections and general-domain relations. However, upon close inspection, DocRED does not have many truly long-range relation instances. As \autoref{tab:test-data-statistics} shows, each DocRED document contains only eight sentences in average, most within a single paragraph. About half of relations (49\%) can be extracted from a single sentence, per evidence annotation. Consequently, there is very little room to explore the more challenging scenario where relations span multiple paragraphs in large text spans.
In fact,
\citet{huang-etal-2021-three} finds that over 95\% instances in DocRED require no more than three sentences as supporting evidence, and 87\% requires no more than two sentences. \citet{ye-etal-2020-coreferential} shows that a simple BERT-based system (a special case of our approach with just local relation detection) yields 60.06\% F1 on DocRED test (Table 3 in their paper), very close to the state-of-the-art results of 62.76\% by GAIN~\cite{zeng-etal-2020-double}.
We thus focus on biomedical machine reading, where there is a pressing need for comprehensive extraction of the latest findings from full-text articles, and cross-paragraph relation mentions are prevalent. Following \citet{peng-etal-2017-cross,jia-etal-2019-document}, we consider the problem of extracting precision oncology knowledge from PubMed Central full-text articles, which is critical for molecular tumor boards and other precision health applications. Concretely, the goal is to extract drug-gene-mutation relations as shown in \autoref{fig:motivating-example}: given a drug, gene, mutation, and document in which they are mentioned, determine whether the document asserts that the mutation in the gene affects response to the drug.
\subsection{Datasets}
\begin{table}[!t]
\small
\centering
\begin{tabular}{@{}lrrr@{}}
\toprule
& Documents & Positive ex. & Negative ex. \\ \midrule
Train & 5563 & 5019 & 12367 \\
Dev & 2400 & 5539 & 6582 \\ \bottomrule
\end{tabular}
\caption{Distant supervision for relation detection.}
\label{tab:train-dev-data-for-relation-dectection}
\end{table}
\paragraph{Self-Supervision} For training and development, we use unlabeled documents from the PubMed Central Open Access Subset (PMC-OA)\footnote{\url{www.ncbi.nlm.nih.gov/pmc/}}. For relation detection, we derive distant supervision from three knowledge bases (KBs) with manually-curated drug-gene-mutation relations: CIVIC\footnote{\url{civicdb.org/home}}, GDKD~\cite{dienstmann2015database}, OncoKB~\cite{chakravarty2017oncokb}.
We randomly split the generated examples into training and development sets and ensure no overlap of documents.
\autoref{tab:train-dev-data-for-relation-dectection} summarizes their statistics.
For argument resolution, we use the global reasoning rules such as transitivity, as well as data programming rules capturing two anaphoric phenomena: identical mentions, apposition.
\paragraph{Evaluation} Following \citet{jia-etal-2019-document}, we
use CKB CORE\texttrademark\xspace from the Clinical Knowledgebase (CKB;~\citealt{patterson2016clinical})\footnote{\url{ckbhome.jax.org}} as our gold-standard test set.
\mbox{CKB}\xspace contains high-quality document-level annotations of drug-gene-mutation interactions, which are manually curated from PubMed articles by The Jackson Laboratory (JAX), an NCI-designated cancer center.
\mbox{CKB}\xspace has minimal overlap with the three KBs used in training and development. To avoid contamination, we remove CKB entries whose documents are used in our training and development. See \autoref{tab:test-data-statistics} for statistics.
Note that compared to the version used in \citet{jia-etal-2019-document}, the latest dataset (accessed in Oct. 2020) contains substantially more relations from recent findings.
For about one fifth of annotated relations (17.4\%), the key entities such as drug and mutation never co-occur in the same paragraph. These relations are out of scope in \citet{jia-etal-2019-document}.
We denote this subset as CKB$^{\tt HARD}$\xspace, which comprises particularly challenging instances requiring cross-paragraph discourse modeling.
\subsection{Systems}
\begin{table*}[!t]
\centering
\small
\begin{tabular}{@{}C{2cm}lR{2.2cm}R{2.5cm}R{2.5cm}@{}}
\toprule
Test Set & System & Precision (\%) & Recall (\%) & F1 (\%)~~ \\ \midrule
\multirow{4}{*}{CKB} & $\tt All Positive$\xspace & 10.7 {\textcolor{white}{\footnotesize $\pm$0.0}} & 100.0 {\textcolor{white}{\footnotesize $\pm$0.0}} & 19.4 {\textcolor{white}{\footnotesize $\pm$0.0}}~~ \\
& $\tt Multiscale$\xspace~\cite{jia-etal-2019-document} & 21.2 {\footnotesize$\pm$0.5} & 59.3 {\footnotesize$\pm$0.2} & 31.2 {\footnotesize$\pm$0.5}~~ \\
& $\tt GAIN$\xspace~\cite{zeng-etal-2020-double} & 42.3 {\footnotesize$\pm$2.0} & 33.5 {\footnotesize$\pm$1.5} & 37.3 {\footnotesize$\pm$0.2}~~ \\
& $\tt Modular$\xspace (Ours) & 49.9 {\footnotesize$\pm$0.3} & 71.5 {\footnotesize$\pm$0.3} & {\bf 58.8} {\footnotesize$\pm$0.1}~~ \\ \midrule
\multirow{4}{*}{~~~CKB$^{\tt HARD}$\xspace} & $\tt All Positive$\xspace & 2.7 {\textcolor{white}{\footnotesize $\pm$0.0}} & 100.0 {\textcolor{white}{\footnotesize $\pm$0.0}} & 5.3 {\textcolor{white}{\footnotesize $\pm$0.0}}~~ \\
& $\tt Multiscale$\xspace~\cite{jia-etal-2019-document} & 4.7 {\footnotesize$\pm$0.2} & 42.8 {\footnotesize$\pm$0.9} & 8.5 {\footnotesize$\pm$0.3}~~ \\
& $\tt GAIN$\xspace~\cite{zeng-etal-2020-double} & 7.9 {\footnotesize$\pm$0.4} & 13.7 {\footnotesize$\pm$1.4} & 10.0 {\footnotesize$\pm$0.4}~~ \\
& $\tt Modular$\xspace (Ours) & 22.6 {\footnotesize$\pm$0.1} & 46.1 {\footnotesize$\pm$0.4} & {\bf 30.3} {\footnotesize$\pm$0.1}~~ \\ \bottomrule
\end{tabular}
\caption{Comparison of test results on \mbox{CKB}\xspace and CKB$^{\tt HARD}$\xspace. Relations in CKB$^{\tt HARD}$\xspace are particularly challenging as key entity pairs such as drug and mutation never co-occur in a paragraph. All systems were trained using the same three KBs for distant supervision, with no overlap with \mbox{CKB}\xspace. We report results from three random runs.}
\label{tab:main-results}
\end{table*}
We implemented our modular self-supervision method ($\tt Modular$\xspace) using PyTorch~\cite{pytorch}.
We conducted variational EM for eight iterations, which appear to work well in preliminary experiments.
In the M-step, we incorporate early stopping to identify the best checkpoint based on the development performance for fine-tuning the relation detection and argument resolution neural modules.
We initialized the encoding layers in both modules with PubMedBERT~\cite{pubmedbert}, which has been pretrained from scratch on PubMed articles and demonstrated superior performance in a wide range of biomedical NLP applications.
We follow \citet{wang-poon-2018-deep,jia-etal-2019-document} to conduct standard data preprocessing and entity linking.
We used the AdamW optimizer~\cite{loshchilov2017decoupled}.
For training, we set the mini-batch size to 32 and the learning rate 5e-5 with 100 warm-up steps and 0.01 weight decay. The drop-out rate is 0.1 for transformer-based encoders, and 0.5 for other layers. The hidden size is 765 for transformer-based encoders, and 128 for all other feed-forward networks. We generate checkpoints at every 4096 steps. Three random seeds are tried in our experiments: [7, 12, 17].
For self-supervised relation detection, following \citet{jia-etal-2019-document}, we further decompose it into classifying drug-mutation relations and then augmenting them with high-precision gene-mutation associations.
As stated in Section \ref{sec:modular}, at training time, only named entities such as drug, gene, mutation are considered, whereas at inference time, in principle any co-occurring noun phrases within a paragraph would be considered (see \autoref{fig:formulation}, bottom paragraph). In practice, however, this would incur too much computation, most of which wasted on irrelevant candidates. Therefore, we employ the following heuristics to leverage argument resolution results for filtering candidates: In argument resolution, we focus on resolving candidate mentions with drugs, genes, mutations. We also stipulate that a candidate mention must contain within it some relevant biomedical entity mentions (e.g., cell lines, genes, etc., as in ``MEK inhibitors'' that contains gene reference ``MEK'').
In relation detection, we only consider candidate mentions that are classified as resolving with entities among drugs, genes, mutations, based on current prediction module.
We compare $\tt Modular$\xspace with the following baselines:
$\tt All Positive$\xspace is a recall-friendly baseline that always predicts positive;
$\tt Multiscale$\xspace~\cite{jia-etal-2019-document} is a state-of-the-art approach that combines local mention-level representations into an entity-level representation over the entire document;
$\tt GAIN$\xspace~\cite{zeng-etal-2020-double} is another state-of-the-art approach that constructs mention-level graphs and applies graph convolutional network~\cite{kipf2017semi} to model interdependencies among intra- and inter-sentence mentions, attaining top performance on DocRED.
For fair comparison, we replaced the encoders in $\tt Multiscale$\xspace and $\tt GAIN$\xspace with the state-of-the-art PubMedBERT as in our approach, which helped improve the performance (Appendix \ref{sec:Jia-pubmedbert}).
The original $\tt Multiscale$\xspace encodes each paragraph separately using LSTM, so it's straightforward to replace that with PubMedBERT. $\tt GAIN$\xspace, on the other hand, encodes the entire input text all at once. This is feasible in DocRED, where each ``document'' is actually a Wikipedia introduction section, thus more like a paragraph (average only eight sentences long). But it doesn't work in \mbox{CKB}\xspace, where each document is a full-text article. Even the minimal text span covering given entities is often too long to encode using a transformer. Therefore, we ran the encoder on individual paragraphs.
Note that the original version of $\tt Multiscale$\xspace can't make prediction for any instances where key entity pairs such as drug and mutation never co-occur in a paragraph. We implemented a natural extension that would generate local mention-level representations even for singleton mentions (i.e., only one relevant entity shows up in a paragraph).
\subsection{Main Results}
\label{sec:results}
\Cref{tab:main-results} compares various approaches for document-level relation extraction on \mbox{CKB}\xspace.
Our modular self-supervision approach ($\tt Modular$\xspace) substantially outperforms all other methods, gaining more than 20 absolute F1 points compared to prior state of the art such as multiscale learning and graph neural networks.
This demonstrates the superiority in leveraging less noise-prone modular self-supervision as well as fine-grained discourse modeling in argument resolution.
Note that the results for $\tt Multiscale$\xspace are different than that in \citet{jia-etal-2019-document} as we used the latest \mbox{CKB}\xspace which contains considerably more cross-paragraph relations.
Compared to multiscale learning ($\tt Multiscale$\xspace), the graph-neural-network approach ($\tt GAIN$\xspace) attains significantly better precision, as it incorporates more elaborate graph-based reasoning among entities across sentences. However, this comes with substantial expense at recall. Our approach outperforms both substantially in precision and recall.
On the most challenging subset CKB$^{\tt HARD}$\xspace, the contrast is particularly pronounced, as all other systems could only attain single-digit precision. The graph-neural-network approach also suffers heavily in recall. Our approach attains much better precision and recall, and more than triples the F1.
\begin{table}[!t]
\centering
\small
\begin{tabular}{@{}lrrr@{}}
\toprule
& Prec. & Recall & F1 \\ \midrule
$\tt Modular$\xspace (Ours) & 22.6 & 46.1 & {\bf 30.3} \\
\makecell[bl]{$\triangleright$~Replace relation detection\\~~~with $\tt All Positive$\xspace} & 13.7 & 66.1 & 22.7 \\
\makecell[bl]{$\triangleright$~Replace argument resolution\\~~~with Multi-Sieve Pass} & 11.0 & 42.8 & 17.5 \\
\makecell[bl]{$\triangleright$~Replace argument resolution\\~~~with SpanBERT Coref} & 60.2 & 1.5 & 2.9 \\
\bottomrule
\end{tabular}
\caption{Ablation study on CKB$^{\tt HARD}$\xspace.}
\label{tab:ablation-study}
\end{table}
\subsection{Ablation Study}
To understand the impact of our modular self-supervision, we conducted an additional ablation study on CKB$^{\tt HARD}$\xspace. See \Cref{tab:ablation-study} for results.
To assess the limitation of our current argument resolution module, we replace self-supervised relation detection with a baseline that always predicts positive for candidate tuples whose components have been resolved with some drug, gene, mutation entities. This yields a maximum recall of 66.1\%, which means that about a third of the especially hard cases of cross-paragraph relations are still out of reach for our method. In some cases, this is because the only hint at the relation resides in figures or appendix, which are currently not in scope for extraction. In other cases, the argument resolution fails to make correct resolution with the corresponding entities. We leave further investigation and improvement to future work.
With self-supervised relation detection, our full model improves both F1 and precision for the end extraction on CKB$^{\tt HARD}$\xspace.
Next, we investigate the impact of our self-supervision for argument resolution by replacing it with state-of-the-art coreference systems: Multi-Sieve Pass~\cite{raghunathan-etal-2010-multi,lee-etal-2011-stanfords},
and SpanBERT Coreference~\cite{joshi-etal-2020-spanbert}.
Multi-Sieve Pass is a rule-based system that incorporates a series of resolution rules with increasing recall but lower precision. SpanBERT Coreference is a state-of-the-art transformer-based system fine-tuned on OntoNotes~\cite{ontonotes}, an annotated corpus with diverse text.
Both result in significant performance drop.
Using Multi-Sieve results in substantial drop in precision, indicating that coreference heuristics suitable for general domains are less effective in biomedicine.
SpanBERT, on the other hand, suffers catastrophic drop in recall. This suggests that argument resolution for document-level relation extraction may involve more general anaphoric phenomena such as $\tt ISA$ and $\tt PartOf$, which are out of scope in standard coreference annotations.
Remarkably, bootstrapping from the simple data programming rules of identical mentions and apposition, our self-supervised module is able to perform much better argument resolution than these state-of-the-art systems for document-level relation extraction.
\begin{table}[!ht]
\centering
\small
\begin{tabular}{@{}clccc@{}}
\toprule
Test Data & Pre-trained Encoder & Prec. & Recall & F1 \\ \midrule
\multirow{2}{*}{\mbox{CKB}\xspace} & PubMedBERT & 49.9 & 71.5 & {\bf 58.8} \\
& BERT & 49.5 & 68.6 & 57.5 \\ \midrule
\multirow{2}{*}{~~CKB$^{\tt HARD}$\xspace} & PubMedBERT & 22.6 & 46.1 & {\bf 30.3} \\
& BERT & 21.8 & 39.2 & 28.1 \\ \bottomrule
\end{tabular}
\caption{Domain-specific pretraining improves test performance over general-domain pretraining.}
\label{tab:bert-comp}
\end{table}
Given that our evaluation is in the biomedical domain, it is natural to initialize our self-supervised neural modules with PubMedBERT~\cite{pubmedbert}. \autoref{tab:bert-comp} shows that this is indeed advantageous, with domain-specific pretraining attains significant gain over general-domain pretraining.
\subsection{Discussion}
\paragraph{Interpretability} We envision that machine reading is used not as standalone automation, but as assisted curation to help expert curators attain significant speed-up \cite{peng-etal-2017-cross}. For extraction within short text spans, human experts can validate the results by simply reading through the provenance text. For document-level relation extraction, as in \citet{jia-etal-2019-document}, this can be challenging, as the intervening text span is long and validation may require a significant amount of reading that is not much faster than curation from scratch. Our modular approach not only enables us to tackle the harder cases of cross-paragraph relations, but also yields a natural explanation for an extraction result with the local relation and chains of argument resolution, all of which can be quickly validated by curators. We leave studying the impact on assisted curation to future work.
\noindent\textbf{Error Analysis}
We focus our error analysis on CKB$^{\tt HARD}$\xspace, which is particularly challenging. An immediate opportunity lies in significant recall miss by argument resolution. As shown in the prior subsection, the maximum recall for our current argument resolution module is 66\%. From preliminary sample analysis, there are three main types of errors. Some relation instances are hinted in figures, tables, or supplements, which are beyond the current scope of extraction. In other cases, the relation statement is vague and scattered, and relation detection requires inference piecing together multiple evidences. However, the bulk of recall errors simply stem from argument resolution failures. Likewise, we found that in the majority of precision errors, relation detection appears to make the right call, but argument resolution is mistaken.
\eat{
\Cref{tab:ablation-study} shows the recall upper bound is 66.06\%,
meaning that about 34\% relations are beyond the reach of our the current setup.
After analyzing false negative samples, we find that most of them can be categorized into three groups:
(a) Relation evidences are only available from text segments that exceeds the maximal segment length.
While increasing the maximal segment length can improve recall, it will also cause a precision drop (\Cref{fig:seg-len-eff}).
(b) Key resolution links between target entities and entities in the relation evidence are missing.
We can improve the resolution component to alleviate this issue, and leave it for future work.
(c) No direct relation evidence can be found in the text.
Oftentimes these relations are expressed in figures, tables, or supplements, beyond the scope of our extraction.
As for precision, it still has room for improvement, especially on CKB$^\diamond$.
According to our analysis on false positive samples,
most of the time the relation component make correct classification, and errors are from the resolution component.
The most common error is caused by exact string match,
which classifies two \emph{gene} mentions as coreference
but in fact they are described in different experiments with focus on different variants.
The resolution component also make some mistakes in classifying \emph{is-a} and \emph{part-of} relations.
In most of the remaining cases, they are actually true relations but are excluded by curators due to additional curation criteria.
}
\begin{figure}[!ht]
\centering
\includegraphics[width=0.43\textwidth]{figs/res-comp-learn.pdf}
\caption{Argument resolution improves during learning as global reasoning rules augment seed self-supervision to raise maximum recall.}
\label{fig:resolution-component-learning}
\end{figure}
\paragraph{Variational EM}
One direction to improve argument resolution is to augment the self-supervision used in the resolution module. \Cref{fig:resolution-component-learning} shows that argument resolution did improve during learning, thanks to the global reasoning rules, at least in terms of expanding maximum recall.
However, we notice that our current mention filtering rules may be overly strict, which limit the room for growth in recall. Additionally, we treat the reasoning rules such as transitivity as hard constraints, whereas in practice they can be noisy. (E.g., qualifiers like ``some MAP2K1 mutations'' or negation are currently not considered in resolution.)
\eat{
\noindent\textbf{Segment Length}
In \Cref{sec:formulation}, we formulate the relation evidence as a template derived from a consecutive text segment,
and set the maximal segment length to 2 sentences in the experiments.
\Cref{fig:seg-len-eff} shows the results on CKB$^\diamond$ when different maximal segment lengths are chosen.
As we increase the maximal segment length, we observe that recall increases while precision drops, resulting a notable drop of F1.
Setting the maximal length to 2 sentences allows us to keep a relatively high recall without losing too much precision.
\begin{figure}[!ht]
\centering
\includegraphics[width=0.45\textwidth]{figs/seg-len-eff.pdf}
\caption{The effect of different maximal segment lengths (i.e. the number of sentences).}
\label{fig:seg-len-eff}
\end{figure}
}
\section{Related Work}
\paragraph{Document-Level Relation Extraction}
Due to the significant challenges in modeling long text spans and obtaining high-quality supervision signals, document-level relation extraction has been relatively underexplored~\cite{surdeanu2014overview}.
Prior work often focuses on simple extensions of sentence-level extraction (e.g., by incorporating coreference annotations or considering special cases when document-level relations reduces to sentence-level attribute classification)~\cite{wick-etal-2006-learning,gerber-chai-2010-beyond,swampillai-stevenson-2011-extracting,yoshikawa2011coreference,koch-etal-2014-type,yang-mitchell-2016-joint}.
Recently, cross-sentence relation extraction has seen increasing interest~\cite{li2016biocreative,quirk-poon-2017-distant,peng-etal-2017-cross,verga-etal-2018-simultaneously,christopoulou-etal-2019-connecting,wu2019renet,yao-etal-2019-docred}, but most efforts are still limited to short text spans, such as consecutive sentences or abstracts.
A notable exception is \citet{jia-etal-2019-document}, which considers full-text articles that comprise hundreds of sentences. However, they still model local text units in isolation and can't effectively handle relations whose arguments never co-occur in a paragraph.
In contrast, we provide the first attempt to systematically explore cross-paragraph relation extraction.
Most prior work focuses on binary relations. We instead follow \citet{peng-etal-2017-cross,jia-etal-2019-document} to study general $n$-ary relation extraction, using precision oncology treatment as a case study.
\paragraph{Discourse Modeling} Given the focus of standard information extraction on short text spans, discourse modeling has not featured prominently in prior work. An exception is coreference resolution, though the focus tends to be improving sentence-level extraction, as in \citet{koch-etal-2014-type}. Here, we show that document-level relation extraction often requires modeling more general anaphoric phenomena. As discussed in the experiment section, many remaining errors lie in argument resolution, which offers an exciting opportunity to study discourse modeling for an important end application.
\paragraph{Self-Supervision} Task-specific self-supervision alleviates the annotation bottleneck by leveraging freely available domain knowledge (as in distant supervision~\cite{craven1999constructing,mintz-etal-2009-distant}) and expert-derived labeling rules (as in data programming~\cite{snorkel}). Unfortunately, such self-supervision becomes extremely noisy when applied to full-text documents, prompting many prior efforts to focus on short text spans~\cite{quirk-poon-2017-distant,peng-etal-2017-cross,verga-etal-2018-simultaneously,yao-etal-2019-docred}. We instead decompose end-to-end document-level extraction into relation detection and argument resolution modules, for each of which we leverage modular self-supervision that is much less error-prone.
\paragraph{Neural-Symbolic NLP} In the past few decades, the dominant paradigm in NLP has swung from logical approaches (rule-based or relational systems) to statistical and neural approaches. However, given the prevalence of linguistic structures and domain knowledge, there has been increasing interest for synergizing the contrasting paradigms to improve inference and learning.
Neural logic programming replaces logical operators with neural representations to leverage domain-specific constraints with end-to-end differentiable learning~\cite{rocktaschel&riedel16}. Similarly, modular neural networks integrate component neural learning along a structured scaffold (e.g., syntactic parse of a sentence for visual question-answering)~\cite{andreas2016neural}.
On the other hand, deep probabilistic logic~\cite{wang-poon-2018-deep} combines probabilistic logic with neural networks to incorporate diverse self-supervision for deep learning. We take inspiration from modular neural networks and neural logic programming, and use deep probabilistic logic to combine relation detection and argument resolution using global reasoning rules for document-level relation extraction.
\section{Conclusion}
We propose to decompose document-level relation extraction into local relation detection and global argument resolution, and apply modular self-supervision and discourse modeling using deep probabilistic logic. On the challenging problem of biomedical machine reading, where cross-paragraph relations are prevalent, our approach substantially outperforms prior state of the art such as multiscale learning and graph neural networks, gaining over 20 absolute F1 points.
Future directions include: improving discourse modeling for argument resolution; studying the impact on assisted curation; applications to other domains.
\section*{Acknowledgements}
We give warm thanks to the Project Hanover team, Michel Galley, and the anonymous reviewers for their helpful comments.
\section{Neural Architectures}
\label{sec:neural-architecture}
\begin{figure}[!ht]
\centering
\includegraphics[width=0.4\textwidth]{figs/model.pdf}
\caption{Neural architectures for relation detection and argument resolution.}
\label{fig:model}
\end{figure}
\begin{table}[!t]
\small
\center
\begin{tabular}{|l|c|ccc|}
\hline
System & AUC & Prec. & Recall & F1 \\ \hline
\hline
\textbf{Base versions} & & & & \\
\textsc{SentLevel} & & & & \\
\quad\citet{jia-etal-2019-document} & 22.4 & 39.3 & 34.7 & 36.9 \\
\quad Our reproduction & {\color[HTML]{CB0000} 22.4} & {\color[HTML]{CB0000} 38.9} & {\color[HTML]{CB0000} 35.5} & {\color[HTML]{CB0000} 37.1} \\
\qquad w. PubMedBERT & {\color[HTML]{3166FF} 24.4} & {\color[HTML]{3166FF} 43.6} & {\color[HTML]{3166FF} 35.1} & {\color[HTML]{3166FF} 38.9} \\ \hline
\textsc{ParaLevel} & & & & \\
\quad\citet{jia-etal-2019-document} & 33.1 & 36.5 & 44.6 & 40.1 \\
\quad Our reproduction & {\color[HTML]{CB0000} 32.8} & {\color[HTML]{CB0000} 35.6} & {\color[HTML]{CB0000} 44.3} & {\color[HTML]{CB0000} 39.5} \\
\qquad w. PubMedBERT & {\color[HTML]{3166FF} 33.2} & {\color[HTML]{3166FF} 49.4} & {\color[HTML]{3166FF} 39.5} & {\color[HTML]{3166FF} 43.9} \\ \hline
\textsc{DocLevel} & & & & \\
\quad\citet{jia-etal-2019-document} & 36.7 & 45.4 & 38.5 & 41.7 \\
\quad Our reproduction & {\color[HTML]{CB0000} 37.0} & {\color[HTML]{CB0000} 43.3} & {\color[HTML]{CB0000} 41.9} & {\color[HTML]{CB0000} 42.6} \\
\qquad w. PubMedBERT & {\color[HTML]{3166FF} 34.9} & {\color[HTML]{3166FF} 47.7} & {\color[HTML]{3166FF} 41.6} & {\color[HTML]{3166FF} 44.5} \\ \hline
\textsc{MultiScale} & & & & \\
\quad\citet{jia-etal-2019-document} & 37.3 & 41.8 & 43.4 & 42.5 \\
\quad Our reproduction & {\color[HTML]{CB0000} 36.9} & {\color[HTML]{CB0000} 38.5} & {\color[HTML]{CB0000} 46.2} & {\color[HTML]{CB0000} 42.0} \\
\qquad w. PubMedBERT & {\color[HTML]{3166FF} 35.9} & {\color[HTML]{3166FF} 43.4} & {\color[HTML]{3166FF} 46.3} & {\color[HTML]{3166FF} 44.8} \\ \hline
\hline
\textbf{+ Noisy-Or} & & & & \\
\textsc{SentLevel} & & & & \\
\quad\citet{jia-etal-2019-document} & 25.3 & 39.3 & 35.3 & 37.2 \\
\quad Our reproduction & {\color[HTML]{CB0000} 25.3} & {\color[HTML]{CB0000} 38.4} & {\color[HTML]{CB0000} 35.9} & {\color[HTML]{CB0000} 37.1} \\
\qquad w. PubMedBERT & {\color[HTML]{3166FF} 26.0} & {\color[HTML]{3166FF} 43.6} & {\color[HTML]{3166FF} 35.2} & {\color[HTML]{3166FF} 39.0} \\ \hline
\textsc{ParaLevel} & & & & \\
\quad\citet{jia-etal-2019-document} & 35.6 & 44.3 & 40.6 & 42.4 \\
\quad Our reproduction & {\color[HTML]{CB0000} 35.5} & {\color[HTML]{CB0000} 45.5} & {\color[HTML]{CB0000} 39.2} & {\color[HTML]{CB0000} 42.1} \\
\qquad w. PubMedBERT & {\color[HTML]{3166FF} 37.3} & {\color[HTML]{3166FF} 51.6} & {\color[HTML]{3166FF} 38.8} & {\color[HTML]{3166FF} 44.2} \\ \hline
\textsc{DocLevel} & & & & \\
\quad\citet{jia-etal-2019-document} & 36.7 & 45.4 & 38.5 & 41.7 \\
\quad Our reproduction & {\color[HTML]{CB0000} 37.0} & {\color[HTML]{CB0000} 43.3} & {\color[HTML]{CB0000} 42.0} & {\color[HTML]{CB0000} 42.6} \\
\qquad w. PubMedBERT & {\color[HTML]{3166FF} 34.9} & {\color[HTML]{3166FF} 47.7} & {\color[HTML]{3166FF} 41.6} & {\color[HTML]{3166FF} 44.5} \\ \hline
\textsc{MultiScale} & & & & \\
\quad\citet{jia-etal-2019-document} & 39.7 & 48.1 & 38.9 & 43.0 \\
\quad Our reproduction & {\color[HTML]{CB0000} 39.6} & {\color[HTML]{CB0000} 48.7} & {\color[HTML]{CB0000} 37.8} & {\color[HTML]{CB0000} 42.6} \\
\qquad w. PubMedBERT & {\color[HTML]{3166FF} 39.5} & {\color[HTML]{3166FF} 46.8} & {\color[HTML]{3166FF} 43.1} & {\color[HTML]{3166FF} 44.9} \\ \hline
\end{tabular}
\caption{Comparison on the original CKB test set: reported results in \citet{jia-etal-2019-document}, results from our reproduction,
and results after replacing LSTM with PubMedBERT as the encoder.}
\label{tab:pubmedbert-vs-lstm}
\end{table}
\Cref{fig:model} shows the neural architectures for relation detection and argument resolution.
For relation detection, we input a paragraph to a transformer-based encoder, with mentions dummified.
The hidden state $\bm{h}_\texttt{[CLS]}$ in the last layer is then passed to a simple feed-forward classifier defined as below:
\begin{equation*}
\text{classifier}(\bm{h})=\text{sigmoid}(\text{FFNN}_1(\bm{h}))\\
\end{equation*}
where FFNN$_1$ is a two-layer feed-forward network using ReLU as activation functions.
For argument resolution, given a candidate mention pair ($m_i,m_j$) and their context,
we first compute their contextual representations using a transformer-based encoder.
If a mention span contains multiple tokens,
we use average pooling to combine their contextual representations (hidden states in the last layer).
The pair of mention representations ($\bm{h}_{m_i}, \bm{h}_{m_j}$) are then passed to a classifier defined as below:
\begin{equation*}
\text{classifier}(\bm{h}_{m_i},\bm{h}_{m_j})=\text{sigmoid}(s(\bm{h}_{m_i}, \bm{h}_{m_j}))\\
\end{equation*}
where $s(\bm{x},\bm{y})$ is a scoring function similar to those used in \citet{lee-etal-2018-higher,joshi-etal-2020-spanbert}:
\begin{gather*}
s(\bm{x},\bm{y})=s_m(\bm{x})+s_m(\bm{y})+s_c(\bm{x},\bm{y})\\
s_m(\bm{x})=\text{FFNN}_2(\bm{x})\\
s_c(\bm{x},\bm{y})=\text{FFNN}_3([\bm{x}, \bm{y}, \bm{x}\circ\bm{y}])
\end{gather*}
where $\circ$ denotes element-wise multiplication.
FFNN$_2$ and FFNN$_3$ are two-layer feed-forward networks using ReLU as activation functions.
\section{Multiscale with PubMedBERT}
\label{sec:Jia-pubmedbert}
Replacing LSTM with PubMedBERT \cite{pubmedbert} as the encoder generally leads to comparable or better performance by the $\tt Multiscale$\xspace system \cite{jia-etal-2019-document}. \Cref{tab:pubmedbert-vs-lstm} shows the results on the original CKB test set as used in \citet{jia-etal-2019-document}. Note that these results shouldn't be compared with the main results in Table \ref{tab:main-results}, as the latter are obtained on the latest \mbox{CKB}\xspace with considerably more cross-paragraph relations.
\eat{
\section{Self-supervision Source}
\autoref{tab:ssl} summarizes the self-supervision sources we use for relation detection and argument resolution.
\begin{table}[!t]
\small
\centering
\begin{tabular}{@{}lll@{}}
\toprule
& \multicolumn{2}{c}{\bf Modular Self Supervision} \\ \midrule
\makecell[l]{\textbf{Relation}\\\textbf{Detection}} & \makecell[l]{Knowledge base} & \makecell[l]{CIVC, GDKD,\\OncoKB} \\ \midrule
\multirow{2}{*}{\makecell[l]{\textbf{Argument}\\ \textbf{Resolution}}} & \makecell[l]{Data Programming} & \makecell[l]{Identical mentions,~~\\apposition} \\ \cmidrule(l){2-3}
& \makecell[l]{Reasoning Rules} & Transitivity \\ \bottomrule
\end{tabular}
\caption{Modular self-supervision for relation detection and argument resolution.}
\label{tab:ssl}
\end{table}
}
\eat{
\section{Dataset Comparison}
\label{sec:dataset-comparison}
\begin{table*}[!t]
\centering
\begin{tabular}{@{}lrrrrlrrrr@{}}
\toprule
\multirow{3}{*}{\textbf{Dataset}} & \multicolumn{4}{c}{\textbf{DocRED}} & & \multicolumn{4}{c}{\textbf{Biomedical Machine Reading}} \\ \cmidrule(lr){2-5} \cmidrule(l){7-10}
& \multicolumn{2}{c}{Train} & \multirow{2}{*}{Validation} & \multirow{2}{*}{Test} & & \multirow{2}{*}{Train} & \multirow{2}{*}{Dev} & \multicolumn{2}{c}{Test} \\ \cmidrule(lr){2-3} \cmidrule(l){9-10}
& W & S & & & & & & CKB & CKB$^\diamond$ \\ \midrule
\textbf{Annotation} & DS & MC & MC & MC & ~~~~ & DS & DS & MC & MC \\
\textbf{Documents} & 101873 & 3053 & 1000 & 1000 & & 15828 & 3948 & 430 & 391 \\
\textbf{Uniq facts} & 881298 & 34715 & 11790 & 12101 & & 631 & 522 & 1566 & 325 \\
\textbf{Positive ex.} & 1505638 & 38180 & 12323 & NA & & 49119 & 12133 & 1904 & 332 \\
\textbf{Negative ex.} & 18056847 & 561145 & 186072 & NA & & 247671 & 57755 & 15840 & 11790 \\
\multicolumn{3}{l}{\hspace{-0.62em}\textbf{In each document}} & & & & & & & \\
~~Avg words & 199.6 & 197.7 & 200.7 & 197.8 & & 3179.2 & 3216.9 & 5480.1 & 5576.2 \\
~~Avg sents & 8.1 & 7.9 & 8.1 & 7.9 & & 101.2 & 102.3 & 170.6 & 173.6 \\
~~Avg paras & NA & NA & NA & NA & & 25.3 & 25.6 & 38.9 & 39.3 \\
\multicolumn{3}{l}{\hspace{-0.62em}\textbf{Between each positive entity pair}} & & & & & & & \\
~~Avg words & 40.4 & 31.6 & 30.9 & NA & & 480.2 & 497.0 & 161.8 & 717.7 \\
~~Avg sents & 1.6 & 1.2 & 1.2 & NA & & 14.4 & 14.8 & 4.7 & 21.6 \\
~~Avg paras & NA & NA & NA & NA & & 2.8 & 3.0 & 0.7 & 3.8 \\ \bottomrule
\end{tabular}
\caption{Data statistics comparison -- DocRED vs. Biomedical Machine Reading.}
\label{tab:cmp-data-statisitcs}
\end{table*}
DocRED~\cite{yao-etal-2019-docred} has two versions of training data.
One is for the weakly-supervised setting (W); the other is for the supervised setting (S).
They are annotated via distant supervision (DS) and manual curation (MC) respectively.
DocRED is created using Wikipedia intro sections, while Biomedical Machine Reading is created using the entire PubMed article.
As shown in \Cref{tab:cmp-data-statisitcs}, DocRED documents have much fewer words/sentences than Biomedical Machine Reading.
And DocRED does not provide paragraph boundaries.
For each positive entity pair, we search for the closest mention pair in the document and compute their distance.
In DocRED, the average distance between positive entity pair is only 40 or 30 words spanning less than 2 sentences.
In sharp contrast, the distance between positive entity pairs in Biomedical Machine Reading is more than 160 words.
In particular, the positive entity pairs in the CKB$^\diamond$ test subset (which contains only cross-paragraph relations)
are on average more than 700 words away, spanning over 21 sentence across several paragraphs.
}
\eat{
\section{Hyperparameter Settings}
\label{sec:hyperparameters}
For training, we set the mini-batch size to 32 and
the learning rate 5e-5 with 100 warm-up steps and 0.01 weight decay.
The drop-out rate is 0.1 for transformer-based encoders, and 0.5 for other layers.
The hidden size is 765 for transformer-based encoders,
and 128 for all other feed-forward networks.
We generate checkpoints at every 4096 steps.
Three random seeds have been tried in our experiments: [7, 12, 17].
}
\section{Experiments}
There are two prominent tasks to validate our approach: DocRED~\cite{yao-etal-2019-docred}
and Biomedical Machine Reading~\cite{quirk-poon-2017-distant,peng-etal-2017-cross,wang-poon-2018-deep,jia-etal-2019-document}.
We compare them in \Cref{sec:dataset-comparison} and find that
while both tasks aim to accelerate document-level relation extraction,
the relation scope in DocRED is often within a few sentences,
and its documents on average contain around 200 words with no paragraph boundaries.\footnote{DocRED is created using the intro section in Wikipedia, not the entire article.}
In contrast, the relation scope in Biomedical Machine Reading is expanded over dozens of sentences and across several paragraphs.
Its documents are the entire article text, containing thousands of words with explicit paragraph boundaries.
Therefore, we choose Biomedical Machine Reading to validate our approach.
See \Cref{sec:dataset-comparison} for the detailed comparison.
\begin{table}[!t]
\centering
\begin{tabular}{@{}lrrrr@{}}
\toprule
\multirow{2}{*}{\textbf{}} & \multirow{2}{*}{Train} & \multirow{2}{*}{Dev} & \multicolumn{2}{c}{Test} \\ \cmidrule(l){4-5}
& & & CKB & CKB$^\diamond$\\ \midrule
\textbf{Source} & DS & DS & MC & MC\\
\textbf{Documents} & 15828 & 3948 & 430 & 391 \\
\textbf{Uniq. facts} & 631 & 522 & 1566 & 325 \\
\textbf{Positive ex.} & 49119 & 12133 & 1904 & 332 \\
\textbf{Negative ex.} & 247671 & 57755 & 15840 & 11790 \\
\multicolumn{4}{l}{\hspace{-0.62em}\textbf{In each document}} & \\
~~Avg words & 3179 & 3217 & 5480 & 5576 \\
~~Avg sents & 101 & 102 & 171 & 174 \\
~~Avg paras & 25 & 26 & 39 & 39 \\
\multicolumn{4}{l}{\hspace{-0.62em}\textbf{Between each positive entity pair}} & \\
~~Avg words & 480 & 497 & 162 & 718 \\
~~Avg sents & 14 & 15 & 5 & 22 \\
~~Avg paras & 3 & 3 & 1 & 4 \\ \bottomrule
\end{tabular}
\caption{Biomedical Machine Reading data statistics. Both training and dev sets are distantly supervised (DS). The test set is manually curated (MC).
The distance between each positive entity pair is measured using their closest mention pair.}
\label{tab:data-statisitcs}
\end{table}
\subsection{Biomedical Machine Reading}
\label{sec:dataset}
Biomedical Machine Reading is a task to
extract drug-mutation interactions from biomedical literature.
Unlike previous work on cross-sentence relation extraction~\cite{peng-etal-2017-cross,jia-etal-2019-document},
we consider a common yet underexplored situation
where the given drug and mutation may never co-occur in the same paragraph.
\citet{jia-etal-2019-document} has shown that
these cross-paragraph drug-mutation pairs account for a significant portion of the overall relational facts,
and in the real world they are often of high value to molecular tumor boards.
For training and development, we use documents from the PubMed Central Open Access Subset (PMC-OA)\footnote{\url{www.ncbi.nlm.nih.gov/pmc/}}.
Distant supervision is from three knowledgebases with hand-curated drug-mutation facts:
CIVIC\footnote{\url{civicdb.org/home}}, GDKD~\cite{dienstmann2015database}, and OncoKB~\cite{chakravarty2017oncokb}.
We randomly split the generated data into training and development sets and ensure no overlap of documents.
\Cref{tab:data-statisitcs} summarizes their statistics.
We use them to train and tune baselines and our approach.
For test, we use CKB CORE\texttrademark, a public subset of the Clinical Knowledgebase (CKB; \citealt{patterson2016clinical})\footnote{\url{ckbhome.jax.org}},
as our gold-standard test set.
CKB CORE\texttrademark~contains high-quality document-level annotations of drug-mutation interactions,
which are manually curated from PubMed articles by The Jackson Laboratory (JAX), an NCI-designated cancer center.
CKB has minimal overlap with the three KBs used for training and dev.
To avoid contamination, we remove CKB entries whose documents are used in our training and dev sets.
See \Cref{tab:data-statisitcs} for statistics.
We also consider a subset of our test data (denoted as CKB$^\diamond$),
where drug-mutation pairs never co-occur in the same paragraph.
While CKB$^\diamond$ contains 332/1904 (17.4\%) positive examples of the entire test set,
its negative example rate is overwhelming.
To our knowledge, CKB CORE\texttrademark~is the only manually curated data that contains a significant portion of cross-paragraph relational facts.
\subsection{Implementation Details}
Our system is implemented using PyTorch~\cite{pytorch}.
We incorporate early stopping to identify the best checkpoint for relation component based on the dev performance.
We set the maximal segment length to derive relation evidences to 2 consecutive sentences.
The resolution component is self-trained with 8 iterations.
All model encoders are initialized with the pretrained PubMedBERT parameters~\cite{pubmedbert},
and are fine-tuned using the AdamW optimizer~\cite{loshchilov2017decoupled}.
We report the detailed hyperparameter setttings in \Cref{sec:hyperparameters}.
We follow \citet{wang-poon-2018-deep,jia-etal-2019-document} to conduct standard data preprocessing and entity linking.
\begin{table*}[!t]
\centering
\begin{tabular}{@{}C{2cm}lR{2.2cm}R{2.5cm}R{2.5cm}@{}}
\toprule
Test Set & System & Precision (\%) & Recall (\%) & F1 (\%)~~ \\ \midrule
\multirow{4}{*}{CKB} & All Positive & 10.73 {\footnotesize $\pm$0.00} & 100.00 {\footnotesize $\pm$0.00} & 19.38 {\footnotesize $\pm$0.00}~~ \\
& Multiscale~\cite{jia-etal-2019-document} & 21.17 {\footnotesize$\pm$0.50} & 59.27 {\footnotesize$\pm$0.16} & 31.19 {\footnotesize$\pm$0.53}~~ \\
& GAIN~\cite{zeng-etal-2020-double} & 42.26 {\footnotesize$\pm$2.03} & 33.48 {\footnotesize$\pm$1.47} & 37.28 {\footnotesize$\pm$0.18}~~ \\
& Modular SSL (Ours) & 49.89 {\footnotesize$\pm$0.27} & 71.54 {\footnotesize$\pm$0.28} & 59.78 {\footnotesize$\pm$0.13}~~ \\ \midrule
\multirow{4}{*}{CKB$^\diamond$} & All Positive & 2.74 {\footnotesize $\pm$0.00} & 100.00 {\footnotesize $\pm$0.00} & 5.33 {\footnotesize $\pm$0.00}~~ \\
& Multiscale~\cite{jia-etal-2019-document} & 4.73 {\footnotesize$\pm$0.18} & 42.80 {\footnotesize$\pm$0.91} & 8.51 {\footnotesize$\pm$0.29}~~ \\
& GAIN~\cite{zeng-etal-2020-double} & 7.99 {\footnotesize$\pm$0.42} & 13.66 {\footnotesize$\pm$1.35} & 10.04 {\footnotesize$\pm$0.36}~~ \\
& Modular SSL (Ours) & 22.62 {\footnotesize$\pm$0.08} & 46.05 {\footnotesize$\pm$0.37} & 30.34 {\footnotesize$\pm$0.11}~~ \\ \bottomrule
\end{tabular}
\caption{Comparison of different systems on CKB and CKB$^\diamond$. We run each system 3 times with different random seeds and report their average and standard deviation.}
\label{tab:main-results}
\end{table*}
\subsection{Results}
\label{sec:results}
We compare our modular self-supervised learning approach (\textbf{Modular SSL}) with the following baselines:
(a) \textbf{All Positive} is a simple baseline which always predicts positive for any given example.
(b) \textbf{Multiscale}~\cite{jia-etal-2019-document} is an entity-centric approach.
It achieves the state of the art on Biomedical Machine Reading
by combining mention-level representations learned over different discourse units and subrelation hierarchy.
(c) \textbf{GAIN}~\cite{zeng-etal-2020-double} constructs heterogeneous mention-level graphs
and utilizes graph convolutional network~\cite{kipf2017semi} to model the interactions among intra- and inter-sentence mentions.
GAIN signifcantly improves the state of the art on DocRED~\cite{yao-etal-2019-docred}.
Note that for fair comparisons, we replace the encoders in Multiscale and GAIN with the same pretrained PubMedBERT used in our approach.
\Cref{tab:main-results} shows the experiment results.
On the entire test set (CKB), our approach substantially outperforms all baselines.
It has the highest precision while maintaining considerably high recall.
Multiscale and GAIN are two representative end-to-end approaches.
With noisy distantly supervised training data, both approaches perform mediocrely:
Multiscale achieves relatively higher recall, and GAIN shows better precision.
On the much more challenging test subset (CKB$^\diamond$), we see an amplified difference between our approach and the baselines.
All baselines fail in distinguishing hundreds of positive cross-paragraph examples from over 30 times larger negative ones.
Only Multiscale shows comparable recall with our approach,
but its precision is extremely low, minimal difference with the All Positive baseline.
In addition to the results above, we also investigate the effect of supervision quality on the performance of end-to-end approaches.
We split a half of the CKB test set to fine-tune a BERT-based Multiscale model, and evaluate it against the other half of the CKB test set.
No significant improvement is observed, which demonstrates the efficiency of our approaches under limited supervision.
\begin{table}[!ht]
\centering
\small
\begin{tabular}{@{}lrrr@{}}
\toprule
& Prec. & Recall & F1 \\ \midrule
Full model & 22.62 & 46.05 & 30.34 \\
\makecell[bl]{$\triangleright$~Replace relation component\\~~~with all positive function} & 13.73 & 66.06 & 22.73 \\
\makecell[bl]{$\triangleright$~Replace resolution component\\~~~with Multi-Sieve Pass} & 10.99 & 42.77 & 17.48 \\
\makecell[bl]{$\triangleright$~Replace resolution component\\~~~with SpanBERT Coref} & 60.19 & 1.48 & 2.89 \\
\makecell[bl]{$\triangleright$~Remove noisy data filter}& 26.09 & 38.76 & 26.35 \\ \bottomrule
\end{tabular}
\caption{Ablation study on CKB$^\diamond$.}
\label{tab:ablation-study}
\end{table}
\subsection{Ablation Study}
We conduct ablation study on CKB$^\diamond$ in \Cref{tab:ablation-study}.
To show the contribution of relation component, we replace it with a function which always predicts positive for any relation evidence.
On one hand, this replacement allows us to see the recall upper bound of our approach (66.06\%).
On the other hand, the drastic precision drop reveals that the relation component succeeds at discarding a significant number of negative examples.
Next, we investigate the contribution of resolution component by
replacing it with two alternates: an unsupervised coreference resolution framework, Multi-Sieve Pass~\cite{raghunathan-etal-2010-multi,lee-etal-2011-stanfords},
and the state-of-the-art coreference resolution model, SpanBERT~\cite{joshi-etal-2020-spanbert}.
Both replacements result in a significant performance drop, which shows the advantage of our resolution component.
Through extensions to Multi-Sieve Pass and self-training,
the resolution component combines the unsupervised framework and the neural coreference resolution model, leading to a substantial improvement.
Lastly, we remove the noisy data filter when training the relation component.
While precision slightly increases, both F1 and recall drop significantly.
\subsection{Analysis}
\noindent\textbf{Self-training}
As described in \Cref{algo:learn-resolution-component},
at each iteration of self-training, new pseudo labels are added to the training data to update the parameters of resolution component,
which in turns generates more pseudo labels.
Since there is no gold resolution labels, we evaluate the resolution component at each iteration on the end task CKB$^\diamond$.
We use an all-positive function as the relation component
such that we can remove potential variance from the relation component and focus on evaluating the resolution component.
\Cref{fig:resolution-component-learning} shows the performance improvement over the self-training process.
We see moderate increases in F1 and precision with steady decreasing of their variance.
More importantly, recall is improved significantly over the process,
which provides higher upper bound for our full model evaluation.
\begin{figure}[!ht]
\centering
\includegraphics[width=0.45\textwidth]{figs/res-comp-learn.pdf}
\caption{The performance improvement of resolution component on CKB$^\diamond$ over the self-training process.}
\label{fig:resolution-component-learning}
\end{figure}
\noindent\textbf{Segment Length}
In \Cref{sec:formulation}, we formulate the relation evidence as a template derived from a consecutive text segment,
and set the maximal segment length to 2 sentences in the experiments.
\Cref{fig:seg-len-eff} shows the results on CKB$^\diamond$ when different maximal segment lengths are chosen.
As we increase the maximal segment length, we observe that recall increases while precision drops, resulting a notable drop of F1.
Setting the maximal length to 2 sentences allows us to keep a relatively high recall without losing too much precision.
\begin{figure}[!ht]
\centering
\includegraphics[width=0.45\textwidth]{figs/seg-len-eff.pdf}
\caption{The effect of different maximal segment lengths (i.e. the number of sentences).}
\label{fig:seg-len-eff}
\end{figure}
\begin{table}[!ht]
\centering
\begin{tabular}{@{}lccc@{}}
\toprule
& Prec. & Recall & F1 \\ \midrule
Our approach & & & \\
~~w/ PubMedBERT & 22.62 & 46.05 & 30.34 \\
~~w/ SpanBERT & 21.91 & 38.76 & 27.99 \\
\bottomrule
\end{tabular}
\caption{Comparison of our approach based different pretrained encoders on CKB$^\diamond$.}
\label{tab:bert-comp}
\end{table}
\noindent\textbf{Pretrained Encoders}
With domain-specific pretraining, PubMedBERT shows the state-of-art performance on biomedical natural language processing~\cite{pubmedbert}.
Therefore, we choose to initialize encoders in our approach with PubMedBERT.
In \Cref{tab:bert-comp}, we compare PubMedBERT with SpanBERT~\cite{joshi-etal-2020-spanbert},
another pretrained language model that outperforms the original BERT on a variety of tasks on the general domain.
Owing to the domain-specific vocabulary and pretraining, PubMedBERT shows better results with a substantial gain on recall.
\noindent\textbf{Error Analysis}
\Cref{tab:ablation-study} shows the recall upper bound is 66.06\%,
meaning that about 34\% relations are beyond the reach of our the current setup.
After analyzing false negative samples, we find that most of them can be categorized into three groups:
(a) Relation evidences are only available from text segments that exceeds the maximal segment length.
While increasing the maximal segment length can improve recall. it will also cause a precision drop (\Cref{fig:seg-len-eff}).
(b) Key resolution links between target entities and entities in the relation evidence are missing.
We can improve the resolution component to alleviate this issue, and leave it for future work.
(c) No direct relation evidence can be found in the text.
Oftentimes these relations are expressed in figures, tables, or supplements, beyond the scope of our extraction.
As for precision, it still has room for improvement, especially on CKB$^\diamond$.
According to our analysis on false positive samples,
most of the time the relation component make correct classification, and errors are from the resolution component.
The most common error is caused by exact string match,
which classifies two \emph{gene} mentions as coreference
but in fact they are described in different experiments with focus on different variants.
The resolution component also make some mistakes in classifying \emph{is-a} and \emph{part-of} relations.
In most of the remaining cases, they are actually true relations but are excluded by curators due to additional curation criteria.
\section{Inference}
To find out whether an entity pair $(e_1, e_2)$ in a document $D$ has the relation $R(e_1, e_2)$, we adopt a two-stage process.
First, given a set of entity mentions $M$ in $D$,
the resolution component $P(I(m,n)|D,\bm{\psi})$ predicts the resolution link between each mention pair $(m,n)$,
which is used to construct the document-level resolution graph.
Second, we search the document-level resolution graph for any mention pair $(a_i, b_i)$ that satisfies the following conditions:
(1) $I(a_i, e_1)\wedge I(b_i,e_2)$; (2) $a_i$ and $b_i$ co-occur in a $k$-sentence segment $S_i(a_i,b_i)$.
Given the segment $S_i(a_i,b_i)$,
if the relation evidence $Z_i$ is true according the prediction of relation component $P(Z_i|S_i(a_i,b_i),\bm{\theta})$,
then the entity pair $(e_1,e_2)$ has the relation $R(e_1, e_2)$.
\section{Learning}\label{sec:learning}
In this section,
we describe how to leverage distant supervision and variational EM to learn parameters for our model components,
when human annotations are not available.
\subsection{Distant Supervision for Relation Component}
Distant supervision uses an existing knowledge base (KB) and unlabeled text to generate training examples,
which can be extremely noisy for entities that are \emph{not} in the same paragraph.
However, for our relation evidence model, since we restrict the input to a consecutive text segment,
we can still leverage distant supervision to generate training examples.
Specifically, if a entity pair $(a,b)$ is known to have the relation in the KB,
we generate positive examples by (i) extracting all text segments from a document in which the entity mention pair $(a, b)$ co-occur,
(ii) prepending a \texttt{[CLS]} token to each segment,
(iii) and then replacing mentions $(a,b)$ with corresponding special tokens \texttt{[X]} and \texttt{[Y]}.
We randomly sample co-occurring entity mention pairs not known to have the relation to generate negative examples.
To further reduce the noise in generated examples,
we add two restrictions:
(1) we require that a segment contains a limited number of sentences and should not span across paragraphs;
(2) we only keep positive examples for an entity pair if the number of extracted segments from a document is above a threshold.
We will shown in Sec. that these restrictions lead to better performance.
The generated examples are divided into training and development sets.
During training, a weighted sampler is used to generate mini batches so that the overall positive and negative training samples are balanced.
Parameters $\bm{\theta}$ in $P(Z_i|S_i(a_i,b_i),\bm{\theta})$ are learned via minimization of cross-entropy loss.
We train the model until the best performance is achieved on the dev set.
\subsection{Variational EM for Resolution Component}
Learning the resolution component involves finding parameters $\bm{\psi}$ and
mention pair resolution links $\textbf{I}=\{I(m_1,n_1),...,I(m_i,n_i),...\}$ which are likely under the posterior distribution
$P(\bm{\psi},\textbf{I}|D)$.
We approximate the posterior using a simple factored representation.
Our variational approximation takes the following form:
\begin{equation}
Q(\bm{\psi},\textbf{I})=\left( \prod_i q_i(I(m_i,n_i)) \right)\delta(\bm{\psi})
\end{equation}
Inspired by \citet{haghighi-klein-2010-coreference},
we use a mean field approach to update each of the RHS factors in turn to minimize the KL-divergence
between the current variational posterior and the true model posterior.
\noindent\textbf{Updating parameters} $\delta(\bm{\psi})$:
This factor places point estimates on a single value, just as in hard EM.
Updating it involves finding the value which maximizes the model (expected) log-likelihood under other factors.
Given the variational posteriors $\{q_i(\cdot)\}$ for mention resolution links,
$\delta(\bm{\psi})$ is a point estimate and is updated with:
\begin{equation}
\delta(\bm{\psi})=\argmax_{\bm{\psi}} \mathbb{E}_{Q_{-\delta}}\ln{P(\bm{\psi},\textrm{I}|D)}
\end{equation}
where $Q_{-\delta}$ denotes all factors of the variational approximation except for the factor being updated.
\noindent\textbf{Updating resolution links} $\{q_i(I(m_i,n_i))\}$:
Each mention resolution link factor $q_i(I(m_i,n_i))$ maintains a soft approximation,
and is updated with the standard mean field form:
\begin{equation}
q_i(I(m_i,n_i))\propto\exp\{\mathbb{E}_{Q_{-q_i}}\ln{P(\bm{\psi},\textrm{I}|D)}\}
\end{equation}
Since there is no direct supervision, it is impractical to learn all mention resolution links $\textbf{I}=\{...,I(m_i,n_i),...\}$ at once.
We instead introduce a curriculum learning algorithm as described in \Cref{algo:learn-resolution-component}.
Given a set of entity mentions $M$ in document $D$, we first initialize \textsc{seed\_links} between mentions
using high-precision resolution models (e.g. exact string match).
If two entities have a linked mention pair,
we add distant supervised links (\textsc{ds\_links}) to their other mention pairs that co-occur in a sentence.
With \textsc{seed\_links} and \textsc{ds\_links}, we alternately update parameters $\delta^t(\bm{\psi})$ and learn new resolution links $\Delta$, holding approximations to the other fixed.
These newly learned links are used to generate more distant supervised links,
and to existing links for the next iteration.
The details of \textsc{seed\_links} and \textsc{ds\_links} are provided in Appendices.
\begin{algorithm}[!t]
\SetAlgoCaptionSeparator{}
\SetAlCapNameFnt{\small}
\SetAlCapFnt{\small}
\DontPrintSemicolon
\small
\SetKwInOut{Input}{Input}
\SetKwInOut{Output}{Output}
\Input{Document $D$ and entity mentions $M$.}
\Output{Learned parameters $\delta^*(\bm{\psi})$ and mention resolution links $\textbf{I}^*$.}
$\textbf{I}^0\leftarrow \textsc{seed\_links}(M\times M)$\;
$\textbf{I}^0\leftarrow \textbf{I}^0\cup \textsc{ds\_links}(\textbf{I}^0, M\times M)$\;
\For{$t=1:T$}{
$\delta^t(\bm{\psi})\leftarrow\argmax_{\bm{\psi}}\mathbb{E}_{Q_{-\delta}}\ln{P(\bm{\psi},\textrm{I}^{t-1}|D)}$\;
$\Delta\leftarrow\varnothing$\;
\For{$(m_i,n_i) \in M\times M-\textrm{\bf I}^{t-1}$}{
$\widetilde{\textbf{I}}\leftarrow \textbf{I}^{t-1}\cup\{I(m_i,n_i)\}$\;
$q_i\propto\exp\{\mathbb{E}_{Q_{-q_i}}\ln{P(\bm{\psi},\widetilde{\textbf{I}}|D)}\}$\;
\uIf{$q_i> \text{threshold}$}{
$\Delta\leftarrow\Delta\cup\{I(m_i,n_i)\}$\;
}
}
$\textbf{I}^t\leftarrow\textbf{I}^{t-1}\cup\Delta$\;
$\textbf{I}^t\leftarrow \textbf{I}^t\cup \textsc{ds\_links}(\textbf{I}^t, M\times M)$\;
}
\Return $\delta^*(\bm{\psi})=\delta^t(\bm{\psi}), \textbf{I}^*=\textbf{I}^t$ \;
\caption{Resolution Component Learning\label{algo:learn-resolution-component}}
\end{algorithm}
\section{Model}
Rather than relying on a monolithic network to extract document-level relations in an end-to-end manner,
we assemble our model using specialized modules, akin to \citet{andreas2016neural}.
These modules are specialized in relation detection and argument resolution respectively.
\Cref{fig:modular-network} illustrates the assembly of our modular network for document-level \emph{ternary} relation extraction,
where we compose \emph{binary} \textcolor{relation-classification}{subrelation detection} modules for ternary relation detection,
and apply \textcolor{argument-resolution}{argument resolution} modules separately for each argument.
\begin{figure}[!ht]
\centering
\includegraphics[width=0.48\textwidth]{figs/modular-network.pdf}
\caption{Assembly of our modular network.
Modules in \textcolor{relation-classification}{blue} are specialized in subrelation detection.
Modules in \textcolor{argument-resolution}{green} are specialized in argument resolution.
The subrelation module $R_{23}$ is not used in this case.}
\label{fig:modular-network}
\end{figure}
\subsection{Subrelation Detection}
We decompose the $n$-ary relation $R$ into binary subrelations $R_{ij}$ ($1\leq i,j\leq n$).\footnote{
Subrelations of other arities are also possible.}
Given a discourse unit $d_{ij}$ that contains entity mentions $x_i$ and $x_j$,
the subrelation detection module computes the following probability of $R_{ij}$ as below:
\begin{equation}
P(\exists e.R_{ij}(e,x_i,x_j)|d_{ij},x_i,x_j;\bm{\theta}_{ij})
\end{equation}
where $\bm{\theta}_{ij}$ are learned parameters.
The module architecture is illustrated in \Cref{fig:model}(a).
Motivated by the superior contextual modeling capabilities of transformer-based models~\cite{transformer},
we utilize a pre-trained transformer encoder~\cite{pubmedbert} and fine-tune it for subrelation detection.
The module input is a discourse unit where a \texttt{[CLS]} token is prepended.
We replace mentions $x_i$ and $x_j$ with special tokens \texttt{[X$_i$]} and \texttt{[X$_j$]},
to prevent the module from overfitting to memorizing the mentions.
The last-layer hidden state $\bm{h}_\texttt{[CLS]}$ is passed to a feed-forward classifier to compute the probability:
\begin{equation}
\text{classifier}(\bm{h})=\text{sigmoid}(\text{MLP}(\bm{h}))
\end{equation}
where MLP is a multilayer perceptron, the details of which are given in the Appendix.
\begin{figure*}[!t]
\centering
\includegraphics[width=0.9\textwidth]{figs/model.pdf}
\caption{Architecture of modules for
\textcolor{relation-classification}{\bf subrelation classification} and \textcolor{argument-resolution}{\bf argument resolution}
used in our network.}
\label{fig:model}
\end{figure*}
\subsection{Argument Resolution}
The core of argument resolution is classify whether two entity mentions have one of the semantic relations, such as \emph{coreference} and \emph{is-a} relations.
Instead of building the whole argument resolution module from scratch,
we utilize an unsupervised coreference system
and extend it by incorporating a neural component,
which is self-trained for improving coverage of the semantic relations.
\begin{equation}
P(I_i(m_i,x_i)|D,m_i,x_i,\bm{\phi}_i)
\end{equation}
The unsupervised coreference system is a multi-sieve pass system~\cite{raghunathan-etal-2010-multi,lee-etal-2011-stanfords}.
It applies tiers of deterministic resolution models one at a time from highest to lowest precision,
to classify whether two mentions corefer.
For example, the first sieve (i.e., highest precision) requires an exact string match between two mentions,
whereas the last one (i.e., lowest precision) implements pronominal coreference resolution.
Each tier builds on predictions of previous tiers in the sieve, guaranteeing
that stronger features are given precedence over weaker ones.\footnote{We refer the reader to \citet{raghunathan-etal-2010-multi,lee-etal-2011-stanfords} for full details.}
We extend this system by replacing a core sieve, Precise Constructs, with a neural model.
Precise Constructs use a set of hand-crafted syntactic features to link two mentions
(e.g., appositive, relative pronoun, predicate nominative).
While Precise Constructs are highly precise, their coverage is relatively low, and adding new features requires high expertise.
We replace them with a neural model which we will show captures more syntactic patterns while remaining highly precise.
Concretely, for two mentions $(m,n)$,
we adopt a BERT-based model to compute $P(I(m,n)|D,\bm{\psi})$.
The architecture is similar to the one used in \citet{joshi-etal-2020-spanbert} for coreference resolution.
An example is shown in \Cref{fig:model}(b): given two mentions \emph{PIK3CA mutation} and \emph{H1047R},
the model encodes the context of two mentions into hidden states.
For each mention span, the model averages last-layer hidden states of mention tokens to generate a contextual representation.
Contextual representations of two mentions are then passed to a pairwise feed-forward network to compute the probability.
Our resolution component utilizes the extended multi-sieve pass system to construct document-level resolution graphs
and derives resolution evidences for mention pairs in each document.
Lastly, our approach combines relation and resolution components to compute joint probability of relation and resolution evidences in \Cref{eq:model}.
With a search over all choices of $S_i(a_i,b_i)$ in $D$,
our approach not only is capable of computing the target relation probability $P(R(d,v))$ in \Cref{eq:formulation},
but also provides evidences $Z_i,X_i,Y_i$ to support the prediction.
These evidences are especially important for assisted curation.
\section{Problem Formulation}
\begin{figure*}[!t]
\centering
\includegraphics[width=1.0\textwidth]{figs/formulation.pdf}
\caption{Problem Formulation.}
\label{fig:formulation}
\end{figure*}
\label{sec:formulation}
Let $m_1, ..., m_n$ be entity mentions in a document $D$.
The goal of document-level $n$-ary relation extraction ($n\ge 2$) is to classify whether an $n$-ary relation $R$ holds for $m_1, ..., m_n$ in $D$, i.e.,
\begin{equation}
R(m_1,...,m_n)
\end{equation}
In this paper, we decompose it into two types of sub-problems: Relation Detection and Argument Resolution,
which is illustrated in \Cref{fig:formulation}.
\noindent\textbf{Relation Detection} is to classify whether the event of $R$ is triggered in $D$.
We represent relation detection in Davidsonian semantics~\cite{Davidson1967-DAVTLF}:
\begin{equation}
\label{eq:relation-detection}
\exists e.[A_1(e,x_1)\wedge...\wedge A_n(e,x_n)]
\end{equation}
where the event variable $e$ is a \emph{reification} of the $R$ event.
Variables $x_1,...,x_n$ are arguments of $R$.
The subscript $i$ in $x_i$ and $A_i$ implies its role in the $n$-ary relation.
The Davidsonian approach enables a decomposition of the relation $R$ into subrelations over subsets of entities.
Each subrelation is more likely to be expressed in a single discourse unit (e.g., a few consecutive sentences).
An example is underlined in \Cref{fig:formulation}, where the discourse unit
"\emph{Expression of the \textbf{MAP2K1 mutants} ... remained sensitive to \textbf{MEK inhibitors}}" expresses
$\exists e.[A_1(e, x_1)\wedge A_3(e, x_3)]$,
which is a binary relation between the drugs "\emph{MEK inhibitors}" and the mutations \emph{"MAP2K1 mutants"}.
The binary relation is a subrelation of the more general ternary treating relation $R$ among (\emph{drug}, \emph{gene}, \emph{mutation}).
\noindent\textbf{Argument Resolution} for each entity mention $m_i$ is
to classify whether we can substitute the argument $x_i$ in $A_i$ for $m_i$.
We denote argument resolution between $m_i$ and $x_i$ as a binary relation $I_i(m_i, x_i)$.
$I_i$ has the following property:
\begin{equation}
\exists e.[I_i(m_i, x_i)\wedge A_i(e,x_i)\rightarrow A_i(e,m_i)]
\end{equation}
There are several semantic relations that validate argument resolution, including \emph{coreference} and \emph{is-a} relations.
For instance, in the underlined sentence in \Cref{fig:formulation},
we can substitute "\emph{MAP2K1 mutants}" for "\emph{p.K57T}" and the resulted statement is still true.
This is because we infer from the document that "\emph{p.K57T is a kind of MAP2K1 mutant}" (i.e. the \emph{is-a} relation).
Since \emph{coreference} and \emph{is-a} are both transitive relations, and \emph{coreference} is symmetric,
we have the following additional properties regarding $I_i$:
\begin{align}
I_i(a,b)\wedge I_i(b,c)\rightarrow I_i(a,c)\\
I_i(a,b)\wedge \emph{coref}(c,b)\rightarrow I_i(a,c)
\end{align}
Using these properties, we can derive $I_i$ relations between entities across longer text spans.
For example, in \Cref{fig:formulation}, $I_i$(\emph{p.K57T}, \emph{MAP2K1 mutants}) is derived from
$I_i$(\emph{p.K57T}, \emph{MAP2K1 mutations}) and \emph{coref}(\emph{MAP2K1 mutations}, \emph{MAP2K1 mutants}).
Argument resolution enables us to incorporate explicit discourse modeling.
Similar ideas have been explored by \citet{koch-etal-2014-type},
who use an off-the-shelf coreference system~\cite{lee-etal-2011-stanfords} to improve distance supervision.
Later in the experiments (\Cref{sec:results}),
we will show in \Cref{tab:ablation-study} that an off-the-shelf coreference system is not enough to achieve comparable results with our approach.
\section{Related Work}
{\bf += Coref}
Similar ideas have been explored by \citet{koch-etal-2014-type},
who use an off-the-shelf coreference system~\cite{lee-etal-2011-stanfords} to improve distance supervision.
Later in the experiments (\Cref{sec:results}),
we will show in \Cref{tab:ablation-study} that an off-the-shelf coreference system is not enough to achieve comparable results with our approach.
\noindent\textbf{Document-level relation extraction}
Traditional relation extraction focuses on binary relational facts between entities co-occurring within a sentence~\cite{surdeanu2014overview}.
There are also early research efforts to expand relation extraction across sentence boundaries
\cite{wick-etal-2006-learning,gerber-chai-2010-beyond,swampillai-stevenson-2011-extracting,yoshikawa2011coreference,koch-etal-2014-type,yang-mitchell-2016-joint}, most of which
rely on explicit coreference annotations or assume a single event in the document.
With the success of neural models on sentence-level relation extraction~\cite{zeng-etal-2014-relation,nguyen-grishman-2015-relation},
recent work begins to explore more general cross-sentence relation extraction~\cite{li2016biocreative,quirk-poon-2017-distant},
spurring a diverse array of model architecture improvements
(\citealt{peng-etal-2017-cross,verga-etal-2018-simultaneously,christopoulou-etal-2019-connecting,nan-etal-2020-reasoning}; inter alia).
However, the scope of relation extraction is still within a paragraph,
mostly a few consecutive sentences~\cite{quirk-poon-2017-distant},
paper abstracts~\cite{wu2019renet},
or Wikipedia intro sections~\cite{yao-etal-2019-docred}.
\citet{jia-etal-2019-document} expand the scope to the entire document
and focus on more general $n$-ary relation extraction.
They decompose $n$-ary relations into subrelations,
and require each subrelation be completely contained within a sentence or a paragraph.
Unlike \citet{jia-etal-2019-document}, we go one step further to tackle relations, including subrelations,
whose arguments (entities) may never co-occur within a paragraph.
\noindent\textbf{Distant supervision}
By aligning knowledge bases with text, distant supervision automatically generates large-scale but potentially noisy labeled data
\cite{craven1999constructing,mintz-etal-2009-distant,hoffmann-etal-2011-knowledge,riedel2010modeling}.
Noise from distant supervision increases as extraction scope expands beyond single sentences, motivating a variety of indirect supervision approaches~\cite{quirk-poon-2017-distant,wang-poon-2018-deep,jia-etal-2019-document}.
Our approach differs from the previous ones by decomposing document-level relation extraction into subproblems
where distant supervision can be used to generate higher-quality labeled data.
\noindent\textbf{Self-training}
As one of the semi-supervised learning approaches~\cite{chapelle2009semi},
self-training trains a base model on a small amount of labeled data;
applies it to pseudo-label unlabeled data; and uses pseudo-labeled data to augment the labeled data
to re-trains the base model in an iterative manner.
Self-training has been shown to obtain state-of-the-art performance in image classification~\cite{yalniz2019billion},
sequence generation~\cite{He2020Revisiting}, and speech recognition~\cite{kahn2020self}.
Similar to \citet{hearst-1992-automatic,brin1998extracting,10.1145/336597.336644},
our self-training approach uses a very small number of seed patterns to do bootstrap learning.
But unlike their approaches, we jointly leverage pseudo labels and distant supervision at each iteration to augment the labeled data.
| {'timestamp': '2021-09-14T02:16:41', 'yymm': '2109', 'arxiv_id': '2109.05362', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05362'} | arxiv |
\section{INTRODUCTION}
During the past decade, visual sensors are very popular due to the properties of low cost and rich information, and various kinds of frameworks are designed for visual SLAM \cite{svo,DVO,orbslam2}. However, most of these works only utilize low-level features such as points \cite{svo}, lines \cite{svo-l} or planes \cite{planar slam} and neglect the high-level features such as objects which contain strong geometric constraints \cite{high level}.
High-level features have many advantages over low-level features, including broader perspective loop closures, longer feature tracking and considering the intrinsic constraints among low-level features \cite{high level,semantic slam}. Deep learning boosts the front-end techniques including the detection of high-level features. And the back-end estimation algorithms based on those need to be further investigated.
The early SLAM works considering the object features include \cite{slam++,mono-obj-slam}, where their efforts are focusing on recognizing object features via traditional methods. Recent works utilize neural networks to detect the object features and optimization methods to estimate the poses of both the objects and the robot \cite{cubeslam, fusion++,quadricslam}. However, optimization-based methods require much more computation than filter-based methods when the trajectory of robot is very long. Thus they are not suitable for deployment on lightweight platforms. Therefore, developing filter based methods are important. Nevertheless, to the best of our knowledge, works focused on the filter-based SLAM frameworks that consider the object features are still blank. One of the reasons is that the conventional filter-based SLAM (like standard EKF) usually suffers from the problem of inconsistency. And a consistent filter-based estimator requires elaborate modelling and algorithmic design.
An inconsistent filter-based SLAM system will underestimate the uncertainty of the estimated state, which gradually leads to poor results and even makes the algorithm diverge. The discovery of inconsistency of point feature based EKF SLAM can date back to 2001 \cite{i1}. In the last decades, many works focus on analyzing the cause of inconsistency and proposing improvement algorithms to alleviate the inconsistency of the system \cite{i1,i3,i7,i8,i10}. According to \cite{i8}, the explanation of such phenomena is that EKF linearizes the system model at the latest estimated values so that Jacobians of the process and observation functions are not estimated at the same state. Furthermore, \cite{i10} analyzes the observability of the system and argues that the ever-changing linearization points break the unobservable subspace of the system, therefore spurious information along the unobservable direction is introduced to the system, which makes the estimate inconsistent. To solve this problem, first Jacobian estimate (FEJ) \cite{i11} and observability constraint (OC) \cite{oc} methods are proposed.
On the contrary, instead of adding artificial constraint into the estimator, algorithms designed by Lie group theory are found to have the potential to naturally handle invariance including observability constraints in point feature based SLAM algorithms \cite{a10,i14,i15}. Exploiting the properties of invariant tangent vector field, Lie group theory generates the invariant-EKF methodology
\cite{c1,c4,c6}, which is firstly applied to EKF-SLAM in \cite{c6}. Recently, EKF designed on Lie groups has become popular in filter based SLAM
\cite{i15,i16,i20,i21}, as many such algorithms perform well in terms of consistency and convergence.
Based on a specific Lie group representation, \cite{i14} proposed right invariant EKF (RI-EKF) algorithm for 2D point feature based SLAM to alleviate the inconsistency and make the state estimates obtained more accurate. Furthermore, the convergence and consistency for RI-EKF point feature based SLAM in 3D environment are analyzed in \cite{a10}, showing the advantages of the invariant algorithms for SLAM problems.
However, all filter-based SLAM methods mentioned above only consider the point features, and how to fuse the object features (poses) consistently is still an untouched problem. In this paper, we propose a consistent EKF algorithm for object based SLAM. To be specific, the contributions of this paper are shown as follows:
\begin{itemize}
\item An invariant EKF is designed on a new Lie group for SLAM with object features.
\item The observability analysis of our proposed EKF SLAM with object features, showing it can naturally maintain the correct unobservable subspace.
\item The effectiveness of our proposed algorithm is validated via simulations and real-data experiments.
\end{itemize}
\noindent\textbf{Notations:} In this paper, bold lower-case and upper-case letters are reserved for vectors and matrices/elements in the Lie group, respectively. The notation $\mathbb {SO}(3)$ represents 3D special rotation group, consisting of all rotation transformations in $\mathbb{R}^3$. $\mathfrak {so}(3)$ is the Lie algebra of $\mathbb {SO}(3)$, containing all $3\times 3$ skew symmetric matrices. $(\cdot)^{\land}$ represents the skew symmetric operator that transforms a 3-dimensional vector into a skew symmetric matrix. $\exp^G$ represents the exponential map on a Lie group $G$. $\log^G$ is the inverse of exponential map on a Lie group $G$. $N(\textbf{0},\textbf{P})$ represents a zero mean Gaussian distribution with covariance $\textbf{P}$.
\section{Object based SLAM Problem}
An object feature considered in this work is represented as a 3D pose of the object in the environment. A robot moves in an unknown 3D environment and observes some object features. The object based SLAM focuses on estimating the current robot pose and the poses of all the object features using the process model and observation model.
\subsubsection{State Space}
An object feature is defined as
\begin{equation}
(\textbf{R}^f,\textbf{p}^f),
\end{equation}
where $\textbf{R}^f \in \mathbb {SO}(3)$ and $\textbf{p}^f \in \mathbb{R}^3$ are the rotation and position of feature, respectively.
The set consists of all states combining with the robot pose and $K$ observed features is denoted as $\mathcal G_K$, where
\begin{equation}
\begin{aligned}
\mathcal G_K=\left\{(\textbf{R}^r,\textbf{R}^{f_1},\cdots,\textbf{R}^{f_K},\textbf{p}^r,\textbf{p}^{f_1},\cdots,\textbf{p}^{f_K})\right.\\|\textbf{R}^r, \textbf{R}^{f_j}\in \mathbb{SO}(3),\ \textbf{p}^r, \textbf{p}^{f_j}\in \mathbb{R}^3 \},
\end{aligned}
\end{equation}
$\textbf{R}^r,\textbf{R}^{f_j} \in \mathbb{SO}(3)$ represent the rotations of robot and the $j$-th feature respectively, and $\textbf{p}^r,\textbf{p}^{f_j} \in \mathbb{R}^3$ represent the position of robot and the $j$-th feature respectively, all described in the global coordinate system\footnote{Sometimes we use the notation $\mathcal G$ instead of $\mathcal G_K$ for brevity. Also, in the remaining of this paper, without losing generality, we assume that there is only one object feature, i.e. $K=1$, to simplify the equations.}.
\subsubsection{Process Model and Observation Model}
Since $ \mathbb{R}^3 \cong \mathfrak {so}(3)$, for simplification, we can define the exponential map of $\mathbb {SO}(3)$ as follows: For $\bm{\xi} \in \mathbb{R}^3$,
\begin{equation}
\begin{array}[c]{cccc}
\exp^{\mathbb {SO}(3)}: &\mathbb{R}^3& \rightarrow &\mathbb {SO}(3)\\
&\bm{\xi}&\rightarrow&\sum_{k=0}^{\infty}\frac{(\bm{\xi}^{\land})^k}{k!}.
\end{array}
\end{equation}
The following first-order integration scheme of discrete noisy process model is widely used \cite{i11,i14}:
\begin{equation}
\begin{array}{lll}
\textbf{X}_{n+1}=f(\textbf{X}_n,\textbf{U}_n,\textbf{w}_n)\\
=(\textbf{R}^r_{n}\exp^{\mathbb{SO}(3)}(\textbf{w}_n^R)\textbf{R}^u_n,\textbf{R}^{f}_{n},\textbf{p}^r_{n}+\textbf{R}^r_{n}(\textbf{p}^u+\textbf{w}_n^p),\textbf{p}^f_{n}),
\end{array}
\label{ProcessModel}
\end{equation}
where $\textbf{X}_{i}=(\textbf{R}^r_{i},\textbf{R}_{i}^{f},\textbf{p}^r_{i},\textbf{p}^f_{i})$ is the state at time step $i,\ i=n,n+1$, $\textbf{U}_n=(\textbf{R}^u_n,\textbf{p}^u_n)$ is the odometry, $\textbf{w}_n=((\textbf{w}^R_n)^T,(\textbf{w}^p_n)^T)^T(\in \mathbb{R}^6)\sim N(\textbf{0},\mathbf{\Sigma}_n)$ is the odometry noise.
After the object detection and matching from the SLAM front-end, the observation can be regarded as relative poses of object features in the current robot frame. Then the observation model for the object feature, $(\textbf{R}^f,\textbf{p}^f)$, in the $n+1$-th robot frame, $(\textbf{R}^r_{n+1},\textbf{p}^r_{n+1})$, is constructed as
\begin{equation}
\textbf{Z}=h(\textbf{X}_{n+1},\textbf{v}_{n+1})=(\textbf{R}^z,\textbf{p}^z),
\label{ObsModel}
\end{equation}
where
$$\begin{array}{rl}
\textbf{R}^z=&\exp^{\mathbb{SO}(3)}(\textbf{v}^R_{n+1})(\textbf{R}^r_{n+1})^T\textbf{R}_{n+1}^f,\\
\textbf{p}^z=&(\textbf{R}^r_{n+1})^T(\textbf{p}^f_{n+1}-\textbf{p}^r_{n+1})+\textbf{v}^p_{n+1},
\end{array}$$ and
$\textbf{v}_{n+1}=((\textbf{v}^R_{n+1})^T, (\textbf{v}^p_{n+1})^T)^T(\in \mathbb{R}^6) \sim N(\textbf{0},\bm{\Omega_{n+1}})$ is the observation noise.
\section{RI-EKF for Object based SLAM}
\subsection{RI-EKF framework for object based SLAM}
\subsubsection{A novel Lie group structure on state space}
For all $(\textbf{R}_i,\textbf{R}^{f}_i,\textbf{p}^r_i,\textbf{p}^{f}_i) \in \mathcal G$, $i=1,2$, an operator $\oplus$ is defined by
\begin{equation}
\begin{aligned}
(\textbf{R}^r_1,\textbf{R}^{f}_1,\textbf{p}^r_1,\textbf{p}^{f}_1) \oplus (\textbf{R}^r_2,\textbf{R}^{f}_2,\textbf{p}^r_2,\textbf{p}^{f}_2)=\\(\textbf{R}^r_1\textbf{R}^r_2,\textbf{R}^{f}_1\textbf{R}^{f}_2,\textbf{R}^r_1\textbf{p}^r_2+\textbf{p}^r_1,\textbf{R}^r_1\textbf{p}^{f}_2+\textbf{p}^{f}_1).
\end{aligned}
\label{Lie_action}
\end{equation}
Then we can check that equiped with $\oplus$ defined in (\ref{Lie_action}), the state space $\mathcal G$ becomes a Lie group and is isomotric to $\mathbb{SE}_{K+1}(3) \times (\mathbb{SO}(3))^K$, where $K$ (set as 1 for simplicity) is the number of observed features. The Lie group $\mathbb{SE}_{K+1}(3)$, defined in \cite{a10,i14}, plays a significant role in RI-EKF for point feature based SLAM. The notation $\ominus$, the minus of $\oplus$, is defined by $\textbf{X}_a\ominus \textbf{X}_b=\textbf{X}_a\oplus \textbf{X}_b^{-1}$ and $\textbf{X}_b\oplus\textbf{X}_b^{-1}=\textbf{X}_b^{-1}\oplus\textbf{X}_b=(\textbf{I},\textbf{I},\textbf{0},\textbf{0})$.
Denote $\mathfrak{g}$ as the Lie algebra of $\mathcal G$. And we have $\mathfrak{g}\cong se_{K+1}(3)\times (so(3))^K \cong \mathbb{R}^{6+6K}$.
Therefore, the form of an element $\bm{\xi}$ in Lie algebra $\mathfrak{g}$ can be constructed as
\begin{equation}\label{eq:nonlinear_error}
\bm{\xi}^T=((\bm{\xi}^{R^r})^T,(\bm{\xi}^{R^f})^T,(\bm{\xi}^{p^r})^T,(\bm{\xi}^{p^f})^T),
\end{equation}
where $\bm{\xi}^{R^r},\bm{\xi}^{R^f},\bm{\xi}^{p^r},\bm{\xi}^{p^f} \in \mathbb{R}^3$.
The exponential map $\exp^{\mathcal G}$ on this Lie group can be defined by
\begin{equation}
\begin{aligned}
\exp^{\mathcal G}(\bm{\xi})=&(\exp^{\mathbb {SO}(3)}(\bm{\xi}^{R^r}),\exp^{\mathbb {SO}(3)}(\bm{\xi}^{R^f})\\& J_l(\bm{\xi}^{R^r})\bm{\xi}^{p^r},J_l(\bm{\xi}^{R^r})\bm{\xi}^f),
\end{aligned}
\end{equation}
where \begin{equation}
J_l(\bm{\xi}^{R^r})=\sum_{k=0}^{\infty}\frac{((\bm{\xi}^{R^r})^{\land})^k}{(k+1)!}.
\end{equation}
Then an error state $\bm{\xi}$ for an estimated state $\hat{\textbf{X}}$ satisfies
\begin{equation}
\textbf{X}=\exp^{\mathcal G}(\bm{\xi})\oplus\hat{\textbf{X}},
\end{equation}
where $\textbf{X}$ represents the true state.
\subsubsection{Propagation}
Based on the Lie group structure introduced above, the process model (\ref{ProcessModel}) becomes
\begin{equation}
\begin{aligned}
\textbf{X}_{n+1}=\textbf{X}_n\oplus (\exp^{\mathbb{SO}(3)}(\textbf{w}_n^R)\textbf{R}^u_n,\textbf{I}_3,\textbf{p}^u_n+\textbf{w}^p_n,\textbf{0}_{3\times1}).
\end{aligned}
\end{equation}
The predicted state, $\textbf{X}_{n+1|n}$, by propagation is computed by
\begin{equation}
\textbf{X}_{n+1|n}=(\textbf{R}^r_{n|n}\textbf{R}^u_n,\textbf{R}^{f}_{n|n},\textbf{R}^r_{n|n}\textbf{p}^u_n+\textbf{p}^r_{n|n},\textbf{p}^f_{n|n}).
\end{equation}
where $\textbf{X}_{n|n}=(\textbf{R}^r_{n|n},\textbf{R}^{f}_{n|n},\textbf{p}^r_{n|n},\textbf{p}^f_{n|n})$ is the updated state at time $n$.
And the estimated error $\bm{\xi}_{n+1|n}$ by propagation is
\begin{equation}
\begin{array}{lll}
\bm{\xi}_{n+1|n}&\dot{=}\log(\textbf{X}_{n+1}\ominus \textbf{X}_{n+1|n})\\
&\approx \textbf{F}_n\bm{\xi}_{n|n}+\textbf{G}_n{\textbf{w}}_n,
\end{array}
\end{equation}
where $\bm{\xi}_{n|n} \sim N(\textbf{0},\bm{P}_n)$ is the estimation error for $\textbf{X}_{n|n}$, ${\textbf{w}}_n=((\textbf{w}^R_n)^T,(\textbf{w}^p_n)^T)^T$ is the odometry noise, the coefficient matrices $\textbf{F}_n$ and $\textbf{G}_n$ in RI-EKF are
\begin{equation}
\begin{array}{lll}
\textbf{F}_n=\textbf{I}_{6+6K},\\
\textbf{G}_n=\left[
\begin{array}{cccc}
\textbf{R}^r_{n|n}& \textbf{0}_{3\times 3}\\ \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
(\textbf{p}^r_{n|n}+\textbf{R}^r_{n|n}\textbf{p}^u_n)^{\land}\textbf{R}^r_{n|n}&\textbf{R}^r_{n|n}\\
(\textbf{p}^f_{n|n})^{\land}\textbf{R}^r_{n|n}& \textbf{0}_{3\times 3}
\end{array}
\right].\\
\end{array}
\label{FG}
\end{equation}
Then, the covariance matrix of the state $\textbf{X}_{n+1|n}$ by propagation is
\begin{equation}
\textbf{P}_{n+1|n}={\textbf{{F}}}_{n} {\textbf{P}}_n {\textbf{{F}}}^{T}_{n} + {\textbf{{G}}}_n{\bm{\Sigma}}_{n} {\textbf{{G}}}^{T}_{n}.
\end{equation}
\subsubsection{Update}
Suppose $\textbf{Z}$ is an observation in (\ref{ObsModel}). By introducing a new minus operator $\boxminus$ for the observation, innovation $y$ is defined as
\begin{equation}
\begin{array}{lll}
&\textbf{y}=\left[
\begin{array}{ccc}
\textbf{y}^R\\
\textbf{y}^p\\
\end{array}
\right]=\textbf{Z}\boxminus [(\hat{\textbf{R}}^r)^T\hat{\textbf{R}}^f,(\hat{\textbf{R}}^r)^T(\hat{\textbf{p}}^f-\hat{\textbf{p}}^r)]\\
&\doteq\left[
\begin{array}{ccc}
\log^{\mathbb{SO}(3)}(\exp^{\mathbb{SO}(3)}((\textbf{v}^R)^{\land})(\textbf{R}^r)^T\textbf{R}^f(\hat{\textbf{R}}^f)^T\hat{\textbf{R}}^r)\\ (\textbf{R}^r)^T(\textbf{p}^f-\textbf{p}^r)+\textbf{v}^p-[(\hat{\textbf{R}}^r)^T(\hat{\textbf{p}}^f-\hat{\textbf{p}}^r)]\\
\end{array}
\right],
\end{array}
\label{Y}
\end{equation}
where $\textbf{y}^R, \textbf{y}^p\in \mathbb{R}^3$.
The linearization of $\textbf{y}^R$ is obtained by
\begin{equation}
\begin{array}{lll}
\textbf{I}_3+(\textbf{y}^R)^{\land}&\approx \exp^{\mathbb{SO}(3)}((\textbf{y}^R)^{\land})\\
&=\exp^{\mathbb{SO}(3)}((\textbf{v}^R)^{\land})(\textbf{R}^r)^T\textbf{R}^f(\hat{\textbf{R}}^f)^T\hat{\textbf{R}}^r\\
&\approx \textbf{I}_3-((\hat{\textbf{R}}^r)^T\bm{\xi}^{R^r})^{\land}\\&\ \ \ +((\hat{\textbf{R}}^r)^T\bm{\xi}^{R^f})^{\land}+(\textbf{v}^R)^{\land}.
\end{array}
\end{equation}
Then, by omitting the second-order small quantities, we have
\begin{equation}
\begin{array}{lll}
\textbf{y}^R=-(\hat{\textbf{R}}^r)^T\bm{\xi}^{R^r}+(\hat{\textbf{R}}^r)^T\bm{\xi}^{R^f}+\textbf{v}^R.
\end{array}
\end{equation}
The linearization of $\textbf{y}^p$ can be derived directly from point feature RI-EKF SLAM in \cite{a10,i14}. For the innovation at time step $(n+1)$, we have
\begin{equation}
\begin{array}{lll}
\textbf{y}_{n+1}=\textbf{H}_{n+1}\bm{\xi}_{n+1|n}+\textbf{v}_{n+1},\\
\end{array}
\label{H}
\end{equation}
where
\begin{equation}
\textbf{H}_{n+1}=\left[
\begin{array}{cccc}
\textbf{H}^{R,R^r}_{n+1}& \textbf{H}^{R,R^f}_{n+1}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{H}^{p,p^r}_{n+1}& \textbf{H}^{p,p^f}_{n+1}\\
\end{array}
\right],
\end{equation}
$$\begin{aligned}
&\textbf{H}^{R,R^r}_{n+1}=\textbf{H}^{p,p^r}_{n+1}=-({\textbf{R}}_{n+1|n}^r)^T,\\
&\textbf{H}^{R,R^f}_{n+1}=\textbf{H}^{p,p^f}_{n+1}=({\textbf{R}}_{n+1|n}^r)^T,
\end{aligned}$$ and
$\textbf{v}_{n+1}\sim N(\textbf{0},\bm{\Omega}_{n+1})$ is the observation noise.
Then the state is updated by
\begin{equation}
\textbf{X}_{n+1|n+1}=\exp^{\mathcal{G}}(\bm{\xi}_{n+1|n+1})\oplus \textbf{X}_{n+1|n},
\end{equation}
where $\bm{\xi}_{n+1|n+1}={\textbf{K}}_{n+1}{\textbf{y}}_{n+1}$ is the update state error vector, and
$${\textbf{K}}_{n+1}={\textbf{P}}_{n+1|n} {{\textbf{H}}}_{n+1}^{T} ({{\textbf{H}}}_{n+1} {\textbf{P}}_{n+1|n}{{\textbf{H}}}_{n+1}^{T}+{\bm{\Omega}}_{n+1})^{-1}.$$
Its covariance is updated as
\begin{equation}
{{\textbf{P}}}_{n+1} = ({\textbf{I}}-{{\textbf{K}}}_{n+1}{{\textbf{H}}}_{n+1}){\textbf{P}}_{n+1|n}.
\end{equation}
The whole process of RI-EKF integrating object features can be summarized in \textbf{Algorithm \ref{Alg:RI-EKF}}.
\begin{algorithm}[H]
$\textbf{F}_n$, $\textbf{G}_n$, $\textbf{H}_{n+1}$ are given in (\ref{FG}) and (\ref{H}).\\
\hspace*{0.02in} {\bf Input:} $\textbf{X}_{n|n}$, ${\textbf{P}}_n$, ${\textbf{U}}_n$, ${\textbf{Z}}_{n+1}$\\
\hspace*{0.02in} {\bf Output:} $\textbf{X}_{n+1|n+1}$, ${\textbf{P}}_{n+1}$\\
\hspace*{0.02in} {\bf Propagation:} \\
$ \textbf{X}_{n+1|n} \leftarrow \textbf{X}_{n|n}\oplus \textbf{U}_n$ \\
${\textbf{P}}_{n+1|n} \leftarrow {{\textbf{F}}}_{n} {\textbf{P}}_n {{\textbf{F}}}^{T}_{n} + {{\textbf{G}}}_n \bm{\Sigma}_{n} {{\textbf{G}}}^{T}_{n} $\\
\hspace*{0.02in} {\bf Update:} \\
${{\textbf{K}}}_{n+1} \leftarrow {\textbf{P}}_{n+1|n} {{\textbf{H}}}_{n+1}^{T} ({{\textbf{H}}}_{n+1} {\textbf{P}}_{n+1|n}{\textbf{{H}}}_{n+1}^{T}+\bm{\Omega}_{n+1} )^{-1} $\\
${\textbf{y}}_{n+1} \leftarrow {\textbf{Z}}_{n+1}\boxminus h_{n+1}(\textbf{X}_{n+1|n}, {\textbf{0}} )$ \\
$\textbf{X}_{n+1|n+1} \leftarrow \exp^{\mathcal{G}}({{\textbf{K}}}_{n+1}{\textbf{y}}_{n+1})\oplus \textbf{X}_{n+1|n}$\\
${{\textbf{P}}}_{n+1} \leftarrow ({\textbf{I}}-{{\textbf{K}}}_{n+1}{{\textbf{H}}}_{n+1}){\textbf{P}}_{n+1|n}$\\
\caption{RI-EKF for Object based SLAM}
\label{Alg:RI-EKF}
\end{algorithm}
\subsection{New Feature Initialization}\label{sec:initialization}
Besides propagation and updating, another indispensable procedure is object feature initialization. This subsection will propose the method to augment the estimated state $\textbf{X} \in \mathcal{G}$ and the covariance matrix $\textbf{P}$ when the robot observes a new object feature with the observation $\textbf{Z}=(\textbf{R}^z,\textbf{p}^z) \in \mathbb{SO}(3)\times \mathbb{R}^3$
Suppose the state error $\bm{\xi} \in \mathfrak{g}\cong \mathbb{R}^{6K+6}$ is of the form
\begin{equation}
\begin{array}{lll}
\bm{\xi}&=\left[
\begin{array}{llll}
\bm{\xi}^{R}\\
\bm{\xi}^{p}\end{array} \right]
=\log^{\mathcal{G}}(\textbf{X}\ominus \hat{\textbf{X}}),
\end{array}
\label{xi_form}
\end{equation}
where $$\bm{\xi}^{R}=((\bm{\xi}^{R^r})^T,(\bm{\xi}^{R^{f}})^T)^T$$ is the rotation part, and $$\bm{\xi}^{p}=((\bm{\xi}^{p^r})^T,(\bm{\xi}^{p^{f}})^T)^T$$
is the position part.
\iffalse
Hence the statistical model of a state $\textbf{X}$ is
\begin{equation}
\textbf{X}=\exp^{\mathcal{G}}(\bm{\xi})\oplus \hat{\textbf{X}},
\end{equation}
where $\hat{\textbf{X}} \in \mathcal{G}$ is the expectation (or called estimation) of $\textbf{X}$, $\bm{\xi}\sim N(\textbf{0},\textbf{P})$ is the ``Gaussian" noise with covariance $\textbf{P}$.
\fi
Suppose the error $\bm{\xi}\sim N(\textbf{0},\textbf{P})$. Then by the mathematical derivation in Appendix A,
the expectation of the new object feature, $(\hat{\textbf{R}}^{f_{\text{new}}},\hat{\textbf{p}}^{f_{\text{new}}})$, related to the observation $\textbf{Z}$ is given by
\begin{equation}
\begin{array}{rll}
\hat{\textbf{R}}^{f_{\text{new}}}&=\hat{\textbf{R}}^r\textbf{R}^z,\\
\hat{\textbf{p}}^{f_{\text{new}}}&=\hat{\textbf{p}}^r+\hat{\textbf{R}}^r\textbf{p}^z.
\end{array}\label{expectations}
\end{equation}
And the augmented covariance $\textbf{P}_{\text{aug}}$ is computed as
\begin{equation}
\textbf{P}_{\text{aug}}=\left[
\begin{array}{cccccc}
\textbf{P}^{R,R}& \textbf{P}^{R,R}\textbf{M}_1^{T}& \textbf{P}^{R,p}& \textbf{P}^{R,p}\textbf{M}_2^{T}\\
\textbf{M}_1P^{R,R}& \textbf{P}_f^{R,R}& \textbf{M}_1\textbf{P}^{R,p}& \textbf{P}_f^{R,p}\\
\textbf{P}^{p,R}& \textbf{P}^{p,R}\textbf{M}_1^{T}& \textbf{P}^{p,p}& \textbf{P}^{p,p}\textbf{M}_2^{T}\\
\textbf{M}_2\textbf{P}^{p,R}& (\textbf{P}_f^{R,p})^T& \textbf{M}_2\textbf{P}^{p,p}& \textbf{P}_f^{p,p}\\
\end{array}
\right],
\label{Pnew}
\end{equation}
where
\begin{equation}
\begin{array}{rll}
\textbf{M}_1&=[\textbf{I}_3 \ \textbf{0}_{3,3K}],\\
\textbf{M}_2&=[\textbf{I}_3 \ \textbf{0}_{3,3K}],\\
\textbf{P}_f^{R,R}&=\textbf{M}_1\textbf{P}^{R,R}\textbf{M}_1^{T}+\hat{\textbf{R}}^r\bm{\Omega}^{R,R}(\hat{\textbf{R}}^r)^T,\\
\textbf{P}_f^{R,p}&=\textbf{M}_1\textbf{P}^{R,p}\textbf{M}_2^{T}+\hat{\textbf{R}}^r\bm{\Omega}^{R,p}(\hat{\textbf{R}}^r)^T,\\
\textbf{P}_f^{p,p}&=\textbf{M}_2\textbf{P}^{p,p}\textbf{M}_2^{T}+\hat{\textbf{R}}^r\bm{\Omega}^{p,p}(\hat{\textbf{R}}^r)^T.
\end{array}
\end{equation}
\iffalse
Note that
\begin{equation}
\begin{array}{rll}
\exp(\bm{\xi}^{R^r})&=\textbf{R}^r(\hat{\textbf{R}}^r)^T,\\
\exp(\bm{\xi}^{R^{f}})&=\textbf{R}^{f}(\hat{\textbf{R}}^{f})^T,\\
\bm{\xi}^{p^r}&\approx \textbf{p}^r-\exp(\bm{\xi}^{R^r})\hat{\textbf{p}}^r,\\
\bm{\xi}^{p^{f}}&\approx \textbf{p}^{f}-\exp(\bm{\xi}^{R^r})\hat{\textbf{p}}^{f}.
\end{array}
\end{equation}
And considering the observation model of the new feature, $(\textbf{R}^{f_{\text{new}}},\textbf{p}^{f_{\text{new}}})$,
\begin{equation}\label{eq:obs_model}
\begin{array}{rll}
\textbf{R}^z&=\exp^{\mathbb{SO}(3)}((\textbf{v}^R)^{\land})(\textbf{R}^r)^T\textbf{R}^{f_{\text{new}}},\\
\textbf{p}^z&= (\textbf{R}^r)^T(\textbf{p}^{f_{\text{new}}}-\textbf{p}^r)+\textbf{v}^p,
\end{array}
\end{equation}
we have
\begin{equation}
\begin{array}{rll}
\textbf{R}^{f_{\text{new}}}&=\textbf{R}^r\exp^{\mathbb{SO}(3)}((-\textbf{v}^R)^{\land})\textbf{R}^z\\
&=\exp^{\mathbb{SO}(3)}((\bm{\xi}^{R^r})^{\land})\hat{\textbf{R}}^r\exp^{\mathbb{SO}(3)}((-\textbf{v}^R)^{\land})\textbf{R}^z\\
&\approx\exp^{\mathbb{SO}(3)}((\bm{\xi}^{R^r}-\hat{\textbf{R}}^r\textbf{v}^R)^{\land})\hat{\textbf{R}}^r\textbf{R}^z\\
\end{array}
\label{initialRp}
\end{equation}
and
\begin{equation}
\begin{array}{rll}
\textbf{p}^{f_{\text{new}}}&=\textbf{p}^r+\textbf{R}^r\textbf{p}^z-\textbf{R}^r\textbf{v}^p\\&\approx\exp^{\mathbb{SO}(3)}(\bm{\xi}^R)\hat{\textbf{p}}^r\\
&\ \ +\bm{\xi}^{p^r}+\exp^{\mathbb{SO}(3)}(\bm{\xi}^{R^r})\hat{\textbf{R}}^r\textbf{p}^z-\hat{\textbf{R}}^r\textbf{v}^p.
\end{array}
\label{initialp}
\end{equation}
Since $\bm{\xi}\sim N(\textbf{0},\textbf{P})$ and $\textbf{v}\sim N(\textbf{0},\bm{\Omega})$, the expectation (or called estimation) of the new object feature, $(\hat{\textbf{R}}^{f_{\text{new}}},\hat{\textbf{p}}^{f_{\text{new}}})$, related to the observation $\textbf{Z}$ is given by
\begin{equation}
\begin{array}{rll}
\hat{\textbf{R}}^{f_{\text{new}}}&=\hat{\textbf{R}}^r\textbf{R}^z,\\
\hat{\textbf{p}}^{f_{\text{new}}}&=\hat{\textbf{p}}^r+\hat{\textbf{R}}^r\textbf{p}^z.
\end{array}\label{expectations}
\end{equation}
For their covariance, denote $\bm{\xi}^{R^{f_{\text{new}}}}$ and $\bm{\xi}^{p^{f_{\text{new}}}}$ as the corresponding components for $\textbf{R}^{f_{\text{new}}}$ and $\textbf{p}^{f_{\text{new}}}$ in the new error state vector, respectively. Notice that by the proposed Lie group structure, we have
\begin{equation}
\begin{array}{rll}
\exp^{\mathbb{SO}(3)}(\bm{\xi}^{R^{f_{\text{new}}}})&=\textbf{R}^{f_{\text{new}}}(\hat{\textbf{R}}^{f_{\text{new}}})^T,&\\
\bm{\xi}^{p^{f_{\text{new}}}}&\approx
\textbf{p}^{f_{\text{new}}}-\exp^{\mathbb{SO}(3)}(\bm{\xi}^{R^r})\hat{\textbf{p}}^{f_{\text{new}}}.\\
\end{array}\label{initialxi1}
\end{equation}
Then, combining equations (\ref{initialRp}), (\ref{initialp}), (\ref{expectations}), and (\ref{initialxi1}), we obtain
\begin{equation}
\begin{array}{rll}
\bm{\xi}^{R^{f_{\text{new}}}}\approx \bm{\xi}^{R^r}-\hat{\textbf{R}}^r\textbf{v}^R\\
\end{array}
\end{equation}
and
\begin{equation}
\begin{array}{rll}
\bm{\xi}^{p^{f_{\text{new}}}}\approx\bm{\xi}^{p^r}-\hat{\textbf{R}}^r\textbf{v}^p.
\end{array}
\end{equation}
Therefore, consider the state covariance before augmentation,
$$\textbf{P}=\left[
\begin{array}{ccc}
\textbf{P}^{R,R}& \textbf{P}^{R,p}\\
\textbf{P}^{p,R}& \textbf{P}^{p,p}
\end{array}
\right],$$ where $\textbf{P}^{i,j}=\text{Cov}(\bm{\xi}^i,\bm{\xi}^j)$, $\bm{\xi}^i,\bm{\xi}^j\in\{\bm{\xi}^R,\bm{\xi}^p\}$ in (\ref{xi_form}). And the covariance of an observation $$\bm{\Omega}=\left[
\begin{array}{ccc}
\bm{\Omega}^{R,R}& \bm{\Omega}^{R,p}\\
\bm{\Omega}^{p,R}& \bm{\Omega}^{p,p}
\end{array}
\right], $$ $\bm{\Omega}^{i,j}=\text{Cov}(\textbf{v}^i,\textbf{v}^j),\ \textbf{v}^i,\textbf{v}^j\in\{\textbf{v}^R,\textbf{v}^p\}$. Then the augmented covariance $\textbf{P}_{\text{aug}}$ is computed as
\begin{equation}
\textbf{P}_{\text{aug}}=\left[
\begin{array}{cccccc}
\textbf{P}^{R,R}& \textbf{P}^{R,R}\textbf{M}_1^{T}& \textbf{P}^{R,p}& \textbf{P}^{R,p}\textbf{M}_2^{T}\\
\textbf{M}_1P^{R,R}& \textbf{P}_f^{R,R}& \textbf{M}_1\textbf{P}^{R,p}& \textbf{P}_f^{R,p}\\
\textbf{P}^{p,R}& \textbf{P}^{p,R}\textbf{M}_1^{T}& \textbf{P}^{p,p}& \textbf{P}^{p,p}\textbf{M}_2^{T}\\
\textbf{M}_2\textbf{P}^{p,R}& (\textbf{P}_f^{R,p})^T& \textbf{M}_2\textbf{P}^{p,p}& \textbf{P}_f^{p,p}\\
\end{array}
\right],
\label{Pnew}
\end{equation}
where
\begin{equation}
\begin{array}{rll}
\textbf{M}_1&=[\textbf{I}_3 \ \textbf{0}_{3,3K}],\\
\textbf{M}_2&=[\textbf{I}_3 \ \textbf{0}_{3,3K}],\\
\textbf{P}_f^{R,R}&=\textbf{M}_1\textbf{P}^{R,R}\textbf{M}_1^{T}+\hat{\textbf{R}}^r\bm{\Omega}^{R,R}(\hat{\textbf{R}}^r)^T,\\
\textbf{P}_f^{R,p}&=\textbf{M}_1\textbf{P}^{R,p}\textbf{M}_2^{T}+\hat{\textbf{R}}^r\bm{\Omega}^{R,p}(\hat{\textbf{R}}^r)^T,\\
\textbf{P}_f^{p,p}&=\textbf{M}_2\textbf{P}^{p,p}\textbf{M}_2^{T}+\hat{\textbf{R}}^r\bm{\Omega}^{p,p}(\hat{\textbf{R}}^r)^T.
\end{array}
\end{equation}
\fi
The whole process to augment the state is summarized in \textbf{Algorithm \ref{Alg:InitialMethod}}.
\begin{algorithm}[H]
\hspace*{0.02in} {\bf Input:} \\
The state and its covariance before augmentation: \\
$\hat{\textbf{X}}=\left[
\begin{array}{cccccccc}
\hat{\textbf{R}}^r& \hat{\textbf{R}}^{f}&\hat{\textbf{p}}^r& \hat{\textbf{p}}^f\\
\end{array}
\right]$\\
${\textbf{P}}=\left[
\begin{array}{ccc}
\textbf{P}^{R,R}& \textbf{P}^{R,p}\\
\textbf{P}^{p,R}& \textbf{P}^{p,p}
\end{array}
\right]$\\
The observation of new feature: $\textbf{Z}=(\textbf{R}^z,\textbf{p}^z)\in \mathbb{SO}(3)\times \mathbb{R}^3$\\
The covariance of observation noise: $\bm{\Omega}=\left[
\begin{array}{ccc}
\bm{\Omega}^{R,R}& \bm{\Omega}^{R,p}\\
\bm{\Omega}^{p,R}& \bm{\Omega}^{p,p}
\end{array}
\right]$\\ \\
\hspace*{0.02in} {\bf Output:}
The augmented state and its covariance:\\
$\hat{\textbf{X}}_{\text{aug}}=\left[
\begin{array}{cccccccccc}
\hat{\textbf{R}}^r& \hat{\textbf{R}}^{f}& \hat{\textbf{R}}^r\textbf{R}^z& \hat{\textbf{p}}^r& \hat{\textbf{p}}^f& \hat{\textbf{p}}^r+\hat{\textbf{R}}^r\textbf{p}^z\\
\end{array}
\right]$\\ \\
${\textbf{P}}_{\text{aug}
$ is obtained by (\ref{Pnew})
\caption{New Feature Initialization}
\label{Alg:InitialMethod}
\end{algorithm}
\section{Observability Analysis}\label{Ob_anal}
Based on previous research about inconsistency \cite{i7,i8,i10,i11,oc,i14}, the EKF SLAM inconsistency is mainly caused by the violation of the observability constraints. A consistent EKF SLAM estimator should satisfy the following observability constraints: the unobservable subspace for the system model of the estimator is the same as that of the real system (the ideal case where the Jacobians are evaluated at the true state). In this section, we prove that our RI-EKF for object based SLAM can automatically maintain the observability constraints. On the contrary, standard EKF for object based SLAM briefly introduced is unable to maintain the observability constraints. These explain the better performance by our algorithms in terms of consistency in the following experiments.
\begin{myDef}
The unobservable subspace $\mathcal {\hat{N}}$
based on the state estimates
is the null space of the corresponding observability matrix $\mathcal{\hat{\mathbf{O}}}$,
where \begin{equation}
\mathcal{\hat{\mathbf{O}}}=\left[
\begin{array}{cccccc}
\hat{\textbf{H}}_0\\
\hat{\textbf{H}}_1\hat{\textbf{F}}_{0,0}\\
\vdots\\
\hat{\textbf{H}}_{n+1}\hat{\textbf{F}}_{n,0}
\end{array}
\right],
\end{equation}
$\hat{\textbf{H}}_{i}$ is the Jacobian matrix for the $i$-th step observation model evaluated at the state estimate $\hat{\textbf{X}}_{i}$, and $\hat{\textbf{F}}_{i,0}=\hat{\textbf{F}}_i\hat{\textbf{F}}_{i-1}\cdots \tilde{\textbf{F}}_0$, $\hat{\textbf{F}}_j$ is the Jacobian matrix for the $j$-th step propagation model of the estimator evaluated at the state $\hat{\textbf{X}}_j$, $j=0,\cdots,i$.
If the models are linearized at the ground truth,
The unobservable subspace based on the true states is denoted by $\mathcal {\breve{N}}$, and the corresponding observability matrix is denoted by $\mathcal{\breve{\mathbf{O}}}$.
\end{myDef}
\subsection{Observability Analysis for RI-EKF}
\begin{myTheo}
For RI-EKF, the unobservable subspace $\mathcal{\hat{N}}^{RI}$ is the same as $\mathcal{\breve{N}}^{RI}$, where
\begin{equation}
\mathcal{\hat{N}}^{RI}=\mathcal{\breve{N}}^{RI}=\mathop{\text{span}} _{col.}\left[
\begin{array}{cccccc}
\textbf{I}_{3}& \textbf{0}_{3,3}\\
\textbf{I}_{3}& \textbf{0}_{3,3}\\
\textbf{0}_{3,3}& \textbf{I}_{3}\\
\textbf{0}_{3,3}& \textbf{I}_{3}
\end{array}
\right],
\end{equation}
and $\dim(\mathcal{\hat{N}}^{RI})=\dim(\mathcal{\breve{N}}^{RI})=6$.
\label{RI_OC}
\end{myTheo}
\begin{proof}
See Appendix B.
\iffalse
The observabilty matrix of the real system model (the ideal case: evaluated at the groundtruth) for RI-EKF is shown as
\iffalse
\begin{equation}
\begin{array}{rl}
&\mathcal{O}(\breve{X}^{RI})=\left[
\begin{array}{cccccc}
\breve{H}^{RI}_0\\
\breve{H}^{RI}_1\breve{F}^{RI}_{1,0}\\
\vdots\\
\breve{H}^{RI}_{n+1}\breve{F}^{RI}_{n+1,0}
\end{array}
\right]\\
&=\left[
\begin{array}{cccccc}
-{R}^T_{0}& {R}^T_{0}& 0_{3\times 3}& 0_{3\times 3}\\
0_{3\times 3}& 0_{3\times 3}& -{R}^T_{0}& {R}^T_{0}\\
\vdots& \vdots& \vdots& \vdots\\
-{R}^T_{n+1}& {R}^T_{n+1}& 0_{3\times 3}& 0_{3\times 3}\\
0_{3\times 3}& 0_{3\times 3}& -{R}^T_{n+1}& {R}^T_{n+1}\\
\end{array}
\right],
\end{array}
\end{equation}
\fi
\begin{equation}
\begin{array}{rl}
&\mathcal{O}(\breve{\textbf{X}}^{RI})=\left[
\begin{array}{cccccc}
\breve{\textbf{H}}^{RI}_0\\
\breve{\textbf{H}}^{RI}_1\breve{\textbf{F}}^{RI}_{0,0}\\
\vdots\\
\breve{\textbf{H}}^{RI}_{n+1}\breve{\textbf{F}}^{RI}_{n,0}
\end{array}
\right]\\
&=\left[
\begin{array}{cccccc}
\breve{\textbf{H}}^{R,R^r}_0& \breve{\textbf{H}}^{R,R^f}_0& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \breve{\textbf{H}}^{p,p^r}_0& \breve{\textbf{H}}^{p,p^f}_0\\
\vdots& \vdots& \vdots& \vdots\\
\breve{\textbf{H}}^{R,R^r}_{n+1}& \breve{\textbf{H}}^{R,R^f}_{n+1}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}&\breve{\textbf{H}}^{p,p^r}_{n+1}& \breve{\textbf{H}}^{p,p^f}_{n+1}\\
\end{array}
\right],
\end{array}
\end{equation}
where $$\begin{aligned}
&\breve{\textbf{H}}^{RI}_0=\left[
\begin{array}{cccccc}
-({\textbf{R}}_{0}^r)^T& ({\textbf{R}}_{0}^r)^T& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& -({\textbf{R}}_{0}^r)^T& ({\textbf{R}}_{0}^r)^T
\end{array}
\right],\\
&\breve{\textbf{H}}^{R,R^r}_{i+1}=\breve{\textbf{H}}^{p,p^r}_{i+1}=-({\textbf{R}}_{i+1}^r)^T,\ \forall i=0,\cdots, n,\\
&\breve{\textbf{H}}^{R,R^f}_{i+1}=\breve{\textbf{H}}^{p,p^f}_{i+1}=({\textbf{R}}_{i+1}^r)^T,\ \forall i=0,\cdots, n,\\
\end{aligned}$$
$\breve{\textbf{H}}^{RI}_{i+1}$ is the Jacobian matrix for the $(i+1)$-th step observation model evaluated at the true state $\breve{\textbf{X}}^{RI}_{i+1}$, and $\breve{\textbf{F}}^{RI}_{i,0}=\breve{\textbf{F}}^{RI}_i\breve{\textbf{F}}^{RI}_{i-1}\cdots \breve{\textbf{F}}^{RI}_0$ is the identity matrix, $\breve{\textbf{F}}^{RI}_j$ is the Jacobian matrix for the $j$-th step propagation model evaluated at the true state $\breve{\textbf{X}}^{RI}_j$, $ j=0,\cdots, i$.
Based on the linearization method of RI-EKF introduced above, and $\mathcal{O}(\breve{\textbf{X}}^{RI})\mathcal{\breve{N}}^{RI}=\textbf{0}$, we can obtain the unobservable subspace $\mathcal{\breve{N}}^{RI}$ by
\begin{equation}
\mathcal{\breve{N}}^{RI}=\mathop{\text{span}} _{col.}\left[
\begin{array}{cccccc}
\textbf{I}_{3}& \textbf{0}_{3,3}\\
\textbf{I}_{3}& \textbf{0}_{3,3}\\
\textbf{0}_{3,3}& \textbf{I}_{3}\\
\textbf{0}_{3,3}& \textbf{I}_{3}
\end{array}
\right],
\label{nullspace}
\end{equation}
whose dimension is 6.
Then consider the observabilty matrix $\mathcal{O}(\hat{\textbf{X}}^{RI})$ evaluated by RI-EKF estimations $\hat{\textbf{X}}^{RI}$,
\iffalse
\begin{equation}
\begin{array}{rl}
&\mathcal{O}(\hat{\textbf{X}}^{RI})=\left[
\begin{array}{cccccc}
\hat{\textbf{H}}^{RI}_0\\
\hat{\textbf{H}}^{RI}_1\hat{\textbf{F}}^{RI}_{1,0}\\
\vdots\\
\hat{\textbf{H}}^{RI}_{n+1}\hat{\textbf{F}}^{RI}_{n+1,0}
\end{array}
\right]\\
&=\left[
\begin{array}{cccccc}
-(\hat{R}^r_{1|0})^T& (\hat{R}^r_{1|0})^T& 0_{3\times 3}& 0_{3\times 3}\\
0_{3\times 3}& 0_{3\times 3}& -(\hat{R}^r_{1|0})^T& (\hat{R}^r_{1|0})^T\\
\vdots& \vdots& \vdots& \vdots\\
-(\hat{R}^r_{n+1|n})^T& (\hat{R}^r_{n+1|n})^T& 0_{3\times 3}& 0_{3\times 3}\\
0_{3\times 3}& 0_{3\times 3}& -(\hat{R}^r_{n+1|n})^T& (\hat{R}^r_{n+1|n})^T\\
\end{array}
\right],
\end{array}
\end{equation}
where
\fi
\begin{equation}
\begin{array}{rl}
&\mathcal{O}(\hat{\textbf{X}}^{RI})=\left[
\begin{array}{cccccc}
\hat{\textbf{H}}^{RI}_0\\
\hat{\textbf{H}}^{RI}_1\hat{\textbf{F}}^{RI}_{0,0}\\
\vdots\\
\hat{\textbf{H}}^{RI}_{n+1}\hat{\textbf{F}}^{RI}_{n,0}
\end{array}
\right]\\
&=\left[
\begin{array}{cccccc}
\hat{\textbf{H}}^{R,R^r}_0& \hat{\textbf{H}}^{R,R^f}_0& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \hat{\textbf{H}}^{p,p^r}_0& \hat{\textbf{H}}^{p,p^f}_0\\
\vdots& \vdots& \vdots& \vdots\\
\hat{\textbf{H}}^{R,R^r}_{n+1}& \hat{\textbf{H}}^{R,R^f}_{n+1}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}&\hat{\textbf{H}}^{p,p^r}_{n+1}& \hat{\textbf{H}}^{p,p^f}_{n+1}\\
\end{array}
\right],
\end{array}
\end{equation}
where $$\begin{aligned}
&\hat{\textbf{H}}^{RI}_0=\left[
\begin{array}{cccccc}
-(\hat{\textbf{R}}^r_{0|0})^T& (\hat{\textbf{R}}^r_{0|0})^T& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& -(\hat{\textbf{R}}^r_{0|0})^T& (\hat{\textbf{R}}^r_{0|0})^T\\
\end{array}\right],\\
&\hat{\textbf{H}}^{R,R^r}_{i+1}=\hat{\textbf{H}}^{p,p^r}_{i+1}=-(\hat{\textbf{R}}_{i+1|i}^r)^T,\ \forall i=0,\cdots, n,\\
&\hat{\textbf{H}}^{R,R^f}_{i+1}=\hat{\textbf{H}}^{p,p^f}_{i+1}=(\hat{\textbf{R}}_{i+1|i}^r)^T,\ \forall i=0,\cdots, n,\\
\end{aligned}$$
$\hat{\textbf{H}}^{RI}_{i+1}$ is the Jacobian matrix for the $(i+1)$-th step observation model evaluated at the estimated state $\hat{\textbf{X}}^{RI}_{i+1|i}$, and $\hat{\textbf{F}}^{RI}_{i,0}=\hat{\textbf{F}}^{RI}_i\hat{\textbf{F}}^{RI}_{i-1}\cdots \hat{\textbf{F}}^{RI}_0$, $\hat{\textbf{F}}_j$ is the Jacobian matrix for the $j$-th step propagation model evaluated at the estimated state $\hat{\textbf{X}}^{RI}_{j|j}$, $j=0,\cdots i$. The unobservable space $\mathcal{\hat{N}}^{RI}$ is spanned by the right null space of $\mathcal{O}(\hat{\textbf{X}}^{RI})$, which is the same as (\ref{nullspace}). \fi
\end{proof}
Therefore, Theorem \ref{RI_OC} shows that RI-EKF automatically maintains the correct unobservable subspace, which will significantly improve the consistency.
\subsection{Standard EKF for Object based SLAM}
The standard EKF (Std-EKF) for object based SLAM is $\mathbb{SO}(3)$-EKF, whose state space is isomorphic to $(\mathbb{SO}(3))^{K+1}\times (\mathbb{R}^3)^{K+1}$. Suppose there is only one feature in the state vector, an error state $\bm{\eta}\in (\mathfrak{so}(3))^{K+1}\times(\mathbb{R}^3)^{K+1}$, $K=1$, in standard EKF is obtained by
\begin{equation}
\begin{array}{ll}
\bm{\eta}&=(\bm{\eta}^{R^r},\bm{\eta}^{R^f},\bm{\eta}^{p^r},\bm{\eta}^{p^f})\\
&=(log^{\mathbb{SO}(3)}(\textbf{R}^r(\hat{\textbf{R}}^r)^T),log^{\mathbb{SO}(3)}(\textbf{R}^f(\hat{\textbf{R}}^f)^T),\\
&\ \ \ \ \ \textbf{p}^r-\hat{\textbf{p}}^r,\textbf{p}^f-\hat{\textbf{p}}^f),
\end{array}
\end{equation}
where $(\textbf{R}^r,\textbf{p}^r)$ and $(\hat{\textbf{R}}^r,\hat{\textbf{p}}^r)$ are the true and the estimated robot poses, $(\textbf{R}^f,\textbf{p}^f)$ and $(\hat{\textbf{R}}^f,\hat{\textbf{p}}^f)$ are the true and the estimated object features, respectively.
Based on this linearization method above, the Jacobians of considered system are
\begin{equation}
\begin{array}{lll}
\textbf{F}^{Std}_n=\left[
\begin{array}{cccc}
\textbf{I}_3& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{I}_3& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
-(\textbf{R}^r_{n|n}\textbf{p}^{u})^{\land}& \textbf{0}_{3\times 3}& \textbf{I}_3& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{I}_3
\end{array}
\right],\\
\textbf{G}^{Std}_n=\left[
\begin{array}{cccc}
\textbf{R}^r_{n|n}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{R}^r_{n|n}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}
\end{array}
\right],\\
\textbf{H}^{Std}_{n+1}=\left[
\begin{array}{cccc}
\textbf{H}^{R,R^r}_{n+1}& \textbf{H}^{R,R^f}_{n+1}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{H}^{p,R^r}_{n+1}& \textbf{0}_{3\times 3}& \textbf{H}^{p,p^r}_{n+1}& \textbf{H}^{p,p^f}_{n+1}\\
\end{array}
\right],\\
\end{array}
\label{FGH_std}
\end{equation}
where
$$\begin{aligned}
&\textbf{H}^{R,R^r}_{n+1}=\textbf{H}^{p,p^r}_{n+1}=-({\textbf{R}}_{n+1|n}^r)^T,\\
&\textbf{H}^{R,R^f}_{n+1}=\textbf{H}^{p,p^f}_{n+1}=({\textbf{R}}_{n+1|n}^r)^T,\\
&\textbf{H}^{p,R^r}_{n+1}=(\textbf{R}^r_{n+1|n})^T(\textbf{p}^f_{n+1|n}-\textbf{p}^r_{n+1|n})^{\land},
\end{aligned}$$
$\textbf{F}_n$ and $\textbf{G}_n$ are the Jacobians of process model evaluated by the state $\textbf{X}_{n|n}$ and the odometry $(\textbf{R}_n^u,\textbf{p}_n^u)$, respectively, and $\textbf{H}^{Std}_{n+1}$ evaluated at $\textbf{X}_{n+1|n}$ is the Jacobian of observation $\textbf{y}$ defined in (\ref{Y}).
\subsection{Observability Analysis for Standard EKF}
\begin{myTheo}
For Std-EKF, the unobservable subspace $\mathcal{\hat{N}}^{Std}$, is a proper subspace of $\mathcal{\breve{N}}^{Std}$, where
\begin{equation} \mathcal{\hat{N}}^{Std}=\mathop{\text{span}} _{col.}[\textbf{0}_{3\times 3},\textbf{0}_{3\times 3},\textbf{I}_3,\textbf{I}_3]^T,
\end{equation}
and
\begin{equation}
\mathcal{\breve{N}}^{Std}=\mathop{\text{span}} _{col.}\left[
\begin{array}{cccccc}
\textbf{0}_{3,3}& \textbf{I}_{3}\\
\textbf{0}_{3,3}& \textbf{I}_{3}\\
\textbf{I}_{3}& (\textbf{p}^r_0)^{\land}\\
\textbf{I}_{3}& (\textbf{p}^f)^{\land}
\end{array}
\right],
\end{equation}
$\textbf{p}^r_0$ and $\textbf{p}^f$ are respectively the true positions of initial robot and object feature.
And the dimension of $\mathcal{\hat{N}}^{Std}$ is 3, while the dimension of $\mathcal{\breve{N}}^{Std}$ is 6.
\label{Std_OC}
\end{myTheo}
\begin{proof}
See Appendix C.
\iffalse
The observability matrix of the standard EKF is constructed as
\begin{equation}
\mathcal{O}(\hat{\textbf{X}}^{Std})=\left[
\begin{array}{cccccc}
\hat{\textbf{H}}^{Std}_0\\
\hat{\textbf{H}}^{Std}_{1}\hat{\textbf{F}}^{Std}_{0,0}\\
\vdots\\
\hat{\textbf{H}}^{Std}_{n+1}\hat{\textbf{F}}^{Std}_{n,0}
\end{array}
\right]
\end{equation}
where $\hat{\textbf{H}}^{Std}_{i+1}$ is the Jacobian matrix evaluated at the prediction $\textbf{X}_{i+1|i}$ for the $(i+1)$-th step observation model in (\ref{FGH_std}), and
\begin{equation}
\begin{array}{rl}
&\hat{\textbf{F}}^{Std}_{i,0}=\hat{\textbf{F}}^{Std}_i\hat{\textbf{F}}^{Std}_{i-1}\cdots \hat{\textbf{F}}^{Std}_0\\
&=\left[
\begin{array}{cccccc}
\textbf{I}_6&\textbf{0}_{6\times 6}\\
\left[\begin{array}{cccccc}
\sum_{j=0}^i(\textbf{p}^r_{j|j}-\textbf{p}^r_{j+1|j})^{\land}&\textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}&\textbf{0}_{3\times 3}
\end{array}
\right]&\textbf{I}_6
\end{array}
\right]
\end{array}
\end{equation}
$\hat{\textbf{F}}^{Std}_{j}$ is Jacobian evaluated at estimated state $\textbf{X}_{j|j}$ of process model for standard EKF in (\ref{FGH_std}).
In ideal case, the Jacobians are evaluated at the true state $\breve{\textbf{X}}_i$. Then, we have $$\textbf{p}^r_{i+1|i+1}= \textbf{p}^r_{i+1|i}$$ and $$\textbf{p}_{i+1|i}^f=\textbf{p}^f,\ \forall i.$$ And thus, $\hat{\textbf{H}}^{Std}_{i}\hat{\textbf{F}}^{Std}_{i-1,0}$ in $\mathcal{O}(\breve{\textbf{X}}^{Std})$ for ideal case becomes
\iffalse
\begin{equation}
\begin{array}{l}
\mathcal{O}(\breve{X}^{Std})=\\
\left[
\begin{array}{cccccc}
-{R}^T_{0}& {R}^T_{0}& 0_{3\times 3}& 0_{3\times 3}\\
-{R}^T_{0}(p^f-x_0)^{\land}& 0_{3\times 3}& -{R}^T_{0}& {R}^T_{0}\\
\vdots& \vdots& \vdots& \vdots\\
-{R}^T_{n+1}& {R}^T_{n+1}& 0_{3\times 3}& 0_{3\times 3}\\
-{R}^T_{n+1}(p^f-x_0)^{\land}& 0_{3\times 3}& -{R}^T_{n+1}& {R}^T_{n+1}\\
\end{array}
\right].
\end{array}
\end{equation}
\fi
\begin{equation}
\begin{array}{l}
\hat{\textbf{H}}^{Std}_{i}\hat{\textbf{F}}^{Std}_{i-1,0}=\\
\left[
\begin{array}{cccccc}
-({\textbf{R}}^r_{i})^T& ({\textbf{R}}^r_{i})^T& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
-({\textbf{R}}^r_{i})^T(\textbf{p}^f-\textbf{p}^r_0)^{\land}& \textbf{0}_{3\times 3}& -({\textbf{R}}^r_{i})^T& ({\textbf{R}}^r_{i})^T\\
\end{array}
\right].
\end{array}
\end{equation}
\iffalse
The right null space $\mathcal{\breve{N}}^{Std}$ of this observability matrix spans the unobservable space of system, where
\begin{equation}
\mathcal{\breve{N}}^{Std}=\left[
\begin{array}{cccccc}
0_{3,3}& I_{3}\\
0_{3,3}& I_{3}\\
I_{3}& (x_0)^{\land}\\
I_{3}& (p^f)^{\land}
\end{array}
\right].
\end{equation}
\fi
Then unobservable space evaluated by the ground truth is obtained as
\begin{equation}
\mathcal{\breve{N}}^{Std}=\mathop{\text{span}} _{col.}\left[
\begin{array}{cccccc}
\textbf{0}_{3,3}& \textbf{I}_{3}\\
\textbf{0}_{3,3}& \textbf{I}_{3}\\
\textbf{I}_{3}& (\textbf{p}^r_0)^{\land}\\
\textbf{I}_{3}& (\textbf{p}^f)^{\land}
\end{array}
\right].
\end{equation}
Therefore, the dimension of unobservable subspace of system is 6. The same conclusion is for the case of multiple features.
However, in practice, generally
$$\begin{array}{ll}
\textbf{p}^r_{i+1|i+1}&\neq \textbf{p}^r_{i+1|i},\\
\textbf{p}^f_{i+1|i}&\neq \textbf{p}^f_{j+1|j},\ \forall i\neq j,
\end{array} $$ and thus the unobservable subspace of standard EKF evaluated by the estimates becomes
\begin{equation}
\mathcal{\hat{N}}^{Std}=\mathop{\text{span}} _{col.}[\textbf{0}_{3\times 3},\textbf{0}_{3\times 3},\textbf{I}_3,\textbf{I}_3]^T,
\end{equation}
whose dimension is 3.
\fi
\end{proof}
According to Theorem \ref{Std_OC}, due to this improper linearization for object based SLAM, standard EKF mistakenly takes spurious information into estimation, leading to overconfident estimate (inconsistency).
\section{Simulations}
\begin{figure}[t]
\centering
\includegraphics[width=.4\textwidth]{figure/Simulations/circle/Map.eps}
\caption{Simulation environment: 6 object features (the poses are shown as red-green-blue arrows) in a 3D environment, robot moves on the circle (the yellow arrow shows the initial heading of the robot).}
\label{Map}
\end{figure}
\iffals
\begin{table*}
\centering
\caption{Performance of RI-EKF, Std-EKF and Ideal-EKF}
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|}
\hline
\hline
& Robot Rotation & Robot Position & Robot Pose & Feature Rotation & Feature Position & Feature Pose \\
\hline
\hline
&\multicolumn{6}{|c|}{RMSE}\\
\hline
RI-EKF & 0.0776 & 0.1021 & 0.1283 & 0.0209& 0.0266 & 0.0338\\
Std-EKF & 0.0825 & 0.1075 & 0.1356 & 0.0238& 0.0282 & 0.0369\\
Ideal-EKF & 0.0696 & 0.0958 & 0.1185 & 0.0156& 0.0238 & 0.0285\\
\hline
\hline
&\multicolumn{7}{|c|}{NEES}\\
\hline
RI-EKF & 0.9673 & 1.0901 & 1.0064 & 0.9096 & 1.1018 & 0.9923\\
Std-EKF & 1.3623 & 1.2566 & 1.2294 & 2.3887& 1.2494 & 1.7178\\
Ideal-EKF & 0.9847 & 1.0627 & 1.0320 & 0.9554& 1.0163 & 0.9995\\
\hline
\hline
\end{tabular}
\label{Perf_Std_RI}
\end{table*}
\fi
\begin{figure*}[t]
\begin{minipage}[h]{1\textwidth}
\centering
\includegraphics[width=.27\textwidth]{figure/Simulations/circle/RMSE_RobotRotation_sparse.eps}
\includegraphics[width=.27\textwidth]{figure/Simulations/circle/RMSE_RobotPosition_sparse.eps}
\includegraphics[width=.27\textwidth]{figure/Simulations/circle/NEES_RobotPose_sparse.eps}
\end{minipage}
\begin{minipage}[h]{1\textwidth}
\centering
\includegraphics[width=.27\textwidth]{figure/Simulations/circle/RMSE_FeatureRotation_sparse.eps}
\includegraphics[width=.27\textwidth]{figure/Simulations/circle/RMSE_FeaturePosition_sparse.eps}
\includegraphics[width=.27\textwidth]{figure/Simulations/circle/NEES_FeaturePose_sparse.eps}
\end{minipage}
\caption{Accuracy (RMSE) and consistency (NEES) of Std-EKF, RI-EKF, and Ideal-EKF in simulations.}
\label{NEES}
\end{figure*}
\begin{table}
\centering
\caption{Simulation Results of RI-EKF, Std-EKF and Ideal-EKF}
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|}
\hline
& Std-EKF &RI-EKF & Ideal-EKF\\
\hline
&\multicolumn{3}{|c|}{RMSE}\\
\hline
Robot Rotation (rad) & 0.0919& 0.0851 & 0.0719 \\
Robot Position (m) & 0.1363& 0.1306 & 0.1215 \\
Feature Rotation (rad) & 0.0271& 0.0231 & 0.0134 \\
Feature Position (m)& 0.0365& 0.0343 & 0.0307 \\
\hline
&\multicolumn{3}{|c|}{NEES}\\
\hline
Robot Rotation & 1.5623 & 1.0622& 0.9852 \\
Robot Position & 1.2711& 1.0304 & 1.0560 \\
Robot Pose & 1.3435& 1.0592 & 1.0279 \\
Feature Rotation & 3.5999& 1.1539 & 0.9091 \\
Feature Position & 1.3457& 0.9990 & 1.0378 \\
Feature Pose & 2.3425& 1.0849 & 0.9981 \\
\hline
\end{tabular}
\label{Perf_Std_RI}
\end{table}
In this section, we compare our proposed RI-EKF with standard EKF (Std-EKF) and Ideal-EKF (a variant of the Std-EKF where Jacobians are evaluated at the ground truth). It should be noted that Ideal-EKF is impossible to be applied in the real scenario, since the ground truth is not available. It is just used to explain the influence of observability constraints on inconsistency. We use Normalized Estimation Error Squared (NEES) indicator to evaluate the consistency of an estimation method
\begin{equation}
\text{NEES}=\frac{1}{m\times d}\sum_{i=1}^{m}\textbf{e}_i^T\textbf{P}_i^{-1}\textbf{e}_i,
\end{equation}
where $m$ is the number of samples, and $\textbf{e}_i$ is a $d$ dimensional error sample vector, which is estimated to be a zero mean Gaussian with a $d\times d$ covariance matrix $\textbf{P}_i$. NEES should approximately equal to 1 for large $m$, if the estimator is consistent. In addition, root mean squared error (RMSE) is used to evaluate the accuracy of each estimator.
To compute NEES, it is worth noting that for our proposed RI-EKF, the estimated covariance is corresponding to the nonlinear error defined in (\ref{eq:nonlinear_error}) instead of the standard error in the vector space. However, for a fair comparison, we still use the standard error to compute the RMSE of RI-EKF.
\subsection{Settings}
The simulation environment and the robot trajectory are shown in Fig. \ref{Map}. There are 6 object features in the environment and their poses are represented by the red-green-blue arrows. The robot moves along a circle 25 times (total length: 200m) with a constant linear velocity 0.1 m/s and a constant angular velocity $\pi /40$ rad/s. The robot is able to measure the relative poses of object features lying in a range of $[0.5 \text{m},2 \text{m}]$ around it. The units of rotation and position are radian (rad) and meter (m), respectively. The covariance matrices of odometry noise and observation noise in (\ref{ProcessModel}) and (\ref{ObsModel}) are set to
$\bm{\Sigma}_n=\text{diag}(0.1^2,0.1^2,0.1^2, 0.1^2,0.1^2,0.1^2)$ and $\bm{\Omega}_n=\text{diag}(0.1^2,0.1^2,0.1^2, 0.1^2 0.1^2 0.1^2)$.
\subsection{Result and Analysis}
We conducted 50 Monte-Carlo simulations, i.e. $m=50$. The NEES and RMSE results are shown in Fig. \ref{NEES} and Table \ref{Perf_Std_RI}. Fig. \ref{NEES} shows the RMSE and NEES results for robot pose and feature pose every 50 steps. Table \ref{Perf_Std_RI} lists the average RMSE and NEES for rotation and position error (in rad and m respectively) in the last time step. The results show that in this experiment, RI-EKF and Ideal-EKF perform better than Std-EKF in terms of both accuracy and consistency. Based on the comparison of Std-EKF and Ideal-EKF, we can see that the inconsistency of Std-EKF mainly comes from the inaccuracy of linearization points. And according to the analysis in Section \ref{Ob_anal}, these linearization points in Std-EKF break the observability constraints, leading Std-EKF to obtain spurious information from unobservable subspace. As a result, its estimation will be more inaccurate and its estimated covariance is smaller than the actual uncertainty, and become more and more inconsistent over time. In contrast, RI-EKF remains consistent (NEES $\approx 1$) in a longer duration, behaving like Ideal-EKF. The analysis for RI-EKF in Section \ref{Ob_anal} indicates that RI-EKF naturally maintains the observability constraints, as in Ideal-EKF. And each Jacobians are evaluated at the latest estimate. These make the results of RI-EKF more reliable than those of Std-EKF.
\iffalse
\begin{figure*}[t]
\centering
\includegraphics[width=1\textwidth]{figure/RealData/realdata2.png}
\caption{Four sequences from YCB-Video Dataset \cite{YCB} used in the experiments. The lower row shows an image in which some object observation is inaccurate (marked in circle), while the upper row shows the final estimate from our proposed method which is accurate.}
\label{RealData}
\end{figure*}
\fi
\iffalse
\begin{table}
\centering
\caption{Average RMSE* results from four RGB-D sequences of YCB-Video dataset \cite{YCB}.}
\begin{tabular}{|c|c|c|c|c|}
\hline
& 0019 & 0036 & 0041 & 0049 \\
\hline
DVO & .015/.029 & .021/.055 & .023/.038 & .010/.046 \\
ORB-SLAM2 & .012/.030 & .017/.044 & .014/.028 & \textbf{.004}/{.031} \\
Std-EKF & .007/.009 & .012/.017 & .008/.010 & .201/.252 \\
Robust Std-EKF & .007/.009 & .015/.021 & .008/.010 & .011/.023 \\
RI-EKF & \textbf{.004}/\textbf{.006} & \textbf{.004}/.007 & \textbf{.006}/\textbf{.007} & .156/.205 \\
Robust RI-EKF & \textbf{.004}/\textbf{.006} & \textbf{.004}/\textbf{.006} & \textbf{.006}/\textbf{.007} & {.007}/\textbf{.022}\\
\hline
\end{tabular}
{RMSE* of Robot Position (m)/RMSE of Robot Rotation (rad)}
\label{comparisons}
\end{table}
\fi
\section{Real Data Experiments}
In this section, we test our algorithm on a real dataset YCB-Video \cite{YCB} and compare it with Std-EKF, DVO \cite{DVO} and ORB-SLAM2 \cite{orbslam2} to show its effectiveness. All of these algorithms are fed by the RGB-D images from YCB-Video. Four sequences (0019, 0036, 0041, and 0049), which have relatively long trajectory, are selected to be used in the experiments (Fig. \ref{RealData}). Different from simulation, the data collected from real world may have many outliers. The matches of point clouds in Sequence 0019 are very accurate, but in other sequences, some object observations are very inaccurate, as shown in the last three images in the lower row of Fig. \ref{RealData}.
In order to make the algorithms robust, we need to detect and remove outliers. In addition, there is no information about odometry in these data sequences. To apply our algorithms, we make a simple constant velocity assumption for these data sequences which are obtained at low speed.
\subsection{Dataset and Object Detection}
YCB-Video dataset contains 21 objects with various textures from YCB objects. There are 92 RGB-D videos used for training and testing object detection, in which 80 videos are used for training and 2949 keyframes from the rest 12 videos are used for testing. Besides, 80000
synthetic images are released for training. There are many scenes of stacking objects with partial occlusion, as is shown in Fig. \ref{RealData}.
\subsection{Observation of Object Features}
To get the observation of the object features, in the front-end, we utilize the algorithm called REDE from \cite{REDE}, which is an end-to-end object pose estimator using RGB-D data as inputs. In YCB dataset, the results of the pose estimator can realize $98.9\%$ recall under the metric of average ADD \cite{add}. The outputs of REDE are directly fed into (\ref{ObsModel}) as observations.
\subsection{Constant Velocity Assumption}
Since the data are collected from a low speed camera, we assume that the camera is moving at constant velocity. Here we just take a very simple method to obtain the odometry. We assume the angular velocity is zero with noise. And expected linear velocity is the average of previous estimations.
\subsection{Outlier Removal}
Suppose there is an object feature observed in the $n+1$ step, and $\textbf{Z}\in \mathbb{SO}(3)\times \mathbb{R}^3$ is its observation. Before update the state vector, we will first compute $\textbf{y}=\textbf{Z}\boxminus h(\textbf{X}_{n+1|n},\textbf{0})$ in (\ref{Y}). According to EKF framework,
\begin{equation}
\begin{array}{lll}
\textbf{y}\approx \textbf{H}_{n+1}\bm{\xi}_{n+1|n}+\textbf{v}_{n+1}\\
\end{array}
\end{equation}
where $\textbf{H}_{n+1}$ is the Jacobian of observation function evaluated at $\textbf{X}_{n+1|n}$, and $\textbf{v}_{n+1}\sim N(\textbf{0},\bm{\Omega}_{n+1})$ is the noise. If the estimation is accurate, then $\textbf{y}$ should form a zero mean Gaussian distribution with covariance
\begin{equation}
\textbf{P}_y=\textbf{H}_{n+1}\textbf{P}_{n+1|n}(\textbf{H}_{n+1})^T+\bm{\Omega}_{n+1}.
\label{Py}
\end{equation}
Therefore, if all the elements of $\textbf{y}$, i.e. $\textbf{y}(k),\ k=1,\cdots, 6$, are in its $3\sigma$ bound, i.e. $$|\textbf{y}(k)|<3\sqrt{\textbf{P}_y(k,k)},\ k=1,\cdots 6,$$
then we will use $y$ to update the state. Otherwise, the observation will be considered as an outlier. The EKF methods with this outlier removal are called Robust EKF methods in the following.
\begin{figure*}[t]
\centering
\includegraphics[width=1\textwidth]{figure/RealData/Display.png}
\caption{Sample images from the four sequences in YCB-Video Dataset \cite{YCB} used in the experiments. For each column, the lower row shows an image with feature observations while the upper row shows the final estimate from our proposed method.}
\label{RealData}
\end{figure*}
\begin{table}
\centering
\caption{Average RMSE* results from four RGB-D sequences of YCB-Video dataset \cite{YCB}.}
\begin{tabular}{|c|c|c|c|c|}
\hline
& 0019 & 0036 & 0041 & 0049 \\
\hline
DVO & .015/.029 & .021/.055 & .023/.038 & .010/.046 \\
ORB-SLAM2 & .012/.030 & .017/.044 & .014/.028 & \textbf{.004}/{.031} \\
Std-EKF & .007/.009 & .012/.017 & .008/.010 & .201/.252 \\
Robust Std-EKF & .007/.009 & .015/.021 & .008/.010 & .011/.023 \\
RI-EKF & \textbf{.004}/\textbf{.006} & \textbf{.004}/.007 & \textbf{.006}/\textbf{.007} & .156/.205 \\
Robust RI-EKF & \textbf{.004}/\textbf{.006} & \textbf{.004}/\textbf{.006} & \textbf{.006}/\textbf{.007} & {.007}/\textbf{.022}\\
\hline
\end{tabular}
{*RMSE of Robot Position (m)/RMSE of Robot Rotation (rad)}
\label{comparisons}
\end{table}
\subsection{Results and Analysis}
We compare our algorithm with DVO \cite{DVO}, ORB-SLAM2 \cite{orbslam2} and Std-EKF using the four data sequences. The average RMSE for robot rotation and position are shown in Table \ref{comparisons}.
In general, Robust RI-EKF performs the best on these four data sequences as listed in Table \ref{comparisons}. Although both DVO and ORB-SLAM2 utilize all the features in the whole trajectory, they only exploit low-level features (point features). However, the object features considered in our methods have broader perspective loop closures, longer feature track, and more intrinsic constraints information between low-level features. Hence, DVO and ORB-SLAM2 are not fairly comparable. This could explain why the filter based Robust RI-EKF outperforms these two optimization based methods.
The comparison of Robust RI-EKF, Robust Std-EKF, RI-EKF, and Std-EKF on Sequence 0049 shows that robust methods are far better on such inaccurate data sequences.
We also note that some RMSE of Robust Std-EKF are larger than that of Std-EKF, especially on Sequence 0036. This is mainly caused by the inconsistency of Std-EKF which results in mistaken deletion for correct data.
Fig. \ref{3S_RI_Std} shows the errors of robot pose estimates and the 3$\sigma$ bounds of each component for Robust RI-EKF and Robust Std-EKF on Sequence 0036, respectively. Robust RI-EKF perfoms well in terms of consistency, while Robust Std-EKF underestimates the uncertainty of the state in the latter half of the sequence. This can finally result in larger errors. In contrast, the estimates by Robust RI-EKF are more reliable, making our outlier removal more effective.
Fig. \ref{RMSE_obj} shows the RMSE of objects in every 100 steps. They illustrate that Robust RI-EKF also broadly generates more accurate estimates on the object poses than Robust Std-EKF.
In general, from the real data experiments, we can see Robust RI-EKF can generate good estimation results. In Fig. \ref{RealData}, the upper row images show the estimated objects from Robust RI-EKF, which significantly improve the corresponding observations shown in the lower row images for Sequences 0036, 0041 and 0049.
Although the difference for Sequence 0019 is not significant, it can be seen in Fig. \ref{Display2} that the estimation results is more closer to the true object as compared with the observations.
{\tiny }
\begin{figure*}[t]
\centering
\begin{minipage}[h]{1\textwidth}
\centering
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_RIRobust_Rx.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_RIRobust_Ry.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_RIRobust_Rz.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_RIRobust_x.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_RIRobust_y.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_RIRobust_z.png}
\end{minipage}
\centering
\begin{minipage}[h]{1\textwidth}
\centering
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_StdRobust_Rx.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_StdRobust_Ry.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_StdRobust_Rz.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_StdRobust_x.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_StdRobust_y.png}
\includegraphics[width=.16\textwidth]{figure/RealData/3SigmaBound_StdRobust_z.png}
\end{minipage}
\caption{Robot pose estimate errors and the corresponding 3$\sigma$ bounds for Sequence 0036: the upper six figures are for Robust RI-EKF, the lower six figures are for Robust Std-EKF.}
\label{3S_RI_Std}
\end{figure*}
\iffalse
\begin{figure}[t]
\centering
\includegraphics[width=.5\textwidth]{figure/RealData/0041_RMSE_object_reshaped.eps}
\caption{RMSE of 4 object features in Sequence 0041 for Robust RI-EKF and Robust Std-EKF.}
\label{RMSE_obj}
\end{figure}
\fi
\iffalse
\begin{figure}[t]
\centering
\includegraphics[width=.5\textwidth]{figure/RealData/0041_RMSE_Obj1_FT.png}
\caption{RMSE of ** in Sequence 0041 for Robust RI-EKF and Robust Std-EKF.}
\label{RMSE_obj1}
\end{figure}
\begin{figure}[t]
\centering
\includegraphics[width=.5\textwidth]{figure/RealData/0041_RMSE_Obj2_FT.png}
\caption{RMSE of ** in Sequence 0041 for Robust RI-EKF and Robust Std-EKF.}
\label{RMSE_obj2}
\end{figure}
\begin{figure}[t]
\centering
\includegraphics[width=.5\textwidth]{figure/RealData/0041_RMSE_Obj3_FT.png}
\caption{RMSE of ** in Sequence 0041 for Robust RI-EKF and Robust Std-EKF.}
\label{RMSE_obj3}
\end{figure}
\begin{figure}[t]
\centering
\includegraphics[width=.5\textwidth]{figure/RealData/0041_RMSE_Obj4_FT.png}
\caption{RMSE of ** in Sequence 0041 for Robust RI-EKF and Robust Std-EKF.}
\label{RMSE_obj4}
\end{figure}
\fi
\iffalse
\begin{figure}[t]
\centering
\includegraphics[width=.5\textwidth]{figure/RealData/0041_RMSE_Obj3.png}
\caption{RMSE of an object in Sequence 0041 for Robust RI-EKF and Robust Std-EKF.}
\label{RMSE_obj3}
\end{figure}
\fi
\iffalse
\begin{figure}[t]
\centering
\includegraphics[width=.4\textwidth]{figure/RealData/Display2.png}
\caption{Sample result of Robust RI-EKF for Sequence 0019.}
\label{Display2}
\end{figure}
\fi
\begin{figure}[t]
\centering
\begin{minipage}[h]{.5\textwidth}
\centering
\includegraphics[width=1\textwidth]{figure/RealData/0041_RMSE_obj12.png}
\end{minipage}
\centering
\begin{minipage}[h]{.5\textwidth}
\centering
\includegraphics[width=1\textwidth]{figure/RealData/0041_RMSE_obj34.png}
\end{minipage}
\caption{RMSE of objects in Sequence 0041 for Robust RI-EKF and Robust Std-EKF. (Object1: Master Chef Can; Object2: Cracker Box; Object3: Pitcher Base; Object4: Foam Brick)}
\label{RMSE_obj}
\end{figure}
\begin{figure}[t]
\centering
\includegraphics[width=.4\textwidth]{figure/RealData/Display2.png}
\caption{A sample result of Robust RI-EKF for Sequence 0019.}
\label{Display2}
\end{figure}
\section{Conclusion}
In this work, we propose a right invariant EKF (RI-EKF) algorithm for object based SLAM, where object features are represented by 3D poses and are estimated together with the latest robot pose. From theoretical analysis, we prove that our RI-EKF generated by the proposed Lie group can automatically maintain the correct observability properties. This is different from standard EKF with object features that does not have the correct observability property. Results from simulations and real data experiments confirm the good performance of the proposed RI-EKF algorithm.
In this paper, we focus on the SLAM back-end and assume the objects observed are within a given database such that they can be detected and matched relatively easily from the SLAM front-end. In the future, we will investigate the more challenging object based SLAM problem where the objects in the environments are more general and may not belong to a known database.
\input{ref.tex}
\section*{APPENDIX}
In this appendix, we provide the mathematical derivation for the feature initialization/augmentation method in Section \ref{sec:initialization}, and the proofs of the two theorems in Section \ref{Ob_anal}.
\subsection{Mathematical Derivation for Initialization Method}\label{Math}
Note that
\begin{equation}
\begin{array}{rll}
\exp(\bm{\xi}^{R^r})&=\textbf{R}^r(\hat{\textbf{R}}^r)^T,\\
\exp(\bm{\xi}^{R^{f}})&=\textbf{R}^{f}(\hat{\textbf{R}}^{f})^T,\\
\bm{\xi}^{p^r}&\approx \textbf{p}^r-\exp(\bm{\xi}^{R^r})\hat{\textbf{p}}^r,\\
\bm{\xi}^{p^{f}}&\approx \textbf{p}^{f}-\exp(\bm{\xi}^{R^r})\hat{\textbf{p}}^{f}.
\end{array}
\end{equation}
And considering the observation model of the new feature, $(\textbf{R}^{f_{\text{new}}},\textbf{p}^{f_{\text{new}}})$,
\begin{equation}\label{eq:obs_model_app}
\begin{array}{rll}
\textbf{R}^z&=\exp^{\mathbb{SO}(3)}((\textbf{v}^R)^{\land})(\textbf{R}^r)^T\textbf{R}^{f_{\text{new}}},\\
\textbf{p}^z&= (\textbf{R}^r)^T(\textbf{p}^{f_{\text{new}}}-\textbf{p}^r)+\textbf{v}^p,
\end{array}
\end{equation}
we have
\begin{equation}
\begin{array}{rll}
\textbf{R}^{f_{\text{new}}}&=\textbf{R}^r\exp^{\mathbb{SO}(3)}((-\textbf{v}^R)^{\land})\textbf{R}^z\\
&=\exp^{\mathbb{SO}(3)}((\bm{\xi}^{R^r})^{\land})\hat{\textbf{R}}^r\exp^{\mathbb{SO}(3)}((-\textbf{v}^R)^{\land})\textbf{R}^z\\
&\approx\exp^{\mathbb{SO}(3)}((\bm{\xi}^{R^r}-\hat{\textbf{R}}^r\textbf{v}^R)^{\land})\hat{\textbf{R}}^r\textbf{R}^z\\
\end{array}
\label{initialRp_app}
\end{equation}
and
\begin{equation}
\begin{array}{rll}
\textbf{p}^{f_{\text{new}}}&=\textbf{p}^r+\textbf{R}^r\textbf{p}^z-\textbf{R}^r\textbf{v}^p\\&\approx\exp^{\mathbb{SO}(3)}(\bm{\xi}^R)\hat{\textbf{p}}^r\\
&\ \ +\bm{\xi}^{p^r}+\exp^{\mathbb{SO}(3)}(\bm{\xi}^{R^r})\hat{\textbf{R}}^r\textbf{p}^z-\hat{\textbf{R}}^r\textbf{v}^p.
\end{array}
\label{initialp_app}
\end{equation}
Since $\bm{\xi}\sim N(\textbf{0},\textbf{P})$ and $\textbf{v}\sim N(\textbf{0},\bm{\Omega})$, the expectation (or called estimation) of the new object feature, $(\hat{\textbf{R}}^{f_{\text{new}}},\hat{\textbf{p}}^{f_{\text{new}}})$, related to the observation $\textbf{Z}$ is given by
\begin{equation}
\begin{array}{rll}
\hat{\textbf{R}}^{f_{\text{new}}}&=\hat{\textbf{R}}^r\textbf{R}^z,\\
\hat{\textbf{p}}^{f_{\text{new}}}&=\hat{\textbf{p}}^r+\hat{\textbf{R}}^r\textbf{p}^z.
\end{array}\label{expectations_app}
\end{equation}
For their covariance, denote $\bm{\xi}^{R^{f_{\text{new}}}}$ and $\bm{\xi}^{p^{f_{\text{new}}}}$ as the corresponding components for $\textbf{R}^{f_{\text{new}}}$ and $\textbf{p}^{f_{\text{new}}}$ in the new error state vector, respectively. Notice that by the proposed Lie group structure, we have
\begin{equation}
\begin{array}{rll}
\exp^{\mathbb{SO}(3)}(\bm{\xi}^{R^{f_{\text{new}}}})&=\textbf{R}^{f_{\text{new}}}(\hat{\textbf{R}}^{f_{\text{new}}})^T,&\\
\bm{\xi}^{p^{f_{\text{new}}}}&\approx
\textbf{p}^{f_{\text{new}}}-\exp^{\mathbb{SO}(3)}(\bm{\xi}^{R^r})\hat{\textbf{p}}^{f_{\text{new}}}.\\
\end{array}\label{initialxi1_app}
\end{equation}
Then, combining equations (\ref{initialRp_app}), (\ref{initialp_app}), (\ref{expectations_app}), and (\ref{initialxi1_app}), we obtain
\begin{equation}
\begin{array}{rll}
\bm{\xi}^{R^{f_{\text{new}}}}\approx \bm{\xi}^{R^r}-\hat{\textbf{R}}^r\textbf{v}^R\\
\end{array}
\end{equation}
and
\begin{equation}
\begin{array}{rll}
\bm{\xi}^{p^{f_{\text{new}}}}\approx\bm{\xi}^{p^r}-\hat{\textbf{R}}^r\textbf{v}^p.
\end{array}
\end{equation}
Therefore, consider the state covariance before augmentation,
$$\textbf{P}=\left[
\begin{array}{ccc}
\textbf{P}^{R,R}& \textbf{P}^{R,p}\\
\textbf{P}^{p,R}& \textbf{P}^{p,p}
\end{array}
\right],$$ where $\textbf{P}^{i,j}=\text{Cov}(\bm{\xi}^i,\bm{\xi}^j)$, $\bm{\xi}^i,\bm{\xi}^j\in\{\bm{\xi}^R,\bm{\xi}^p\}$ in (\ref{xi_form}). And the covariance of an observation $$\bm{\Omega}=\left[
\begin{array}{ccc}
\bm{\Omega}^{R,R}& \bm{\Omega}^{R,p}\\
\bm{\Omega}^{p,R}& \bm{\Omega}^{p,p}
\end{array}
\right], $$ $\bm{\Omega}^{i,j}=\text{Cov}(\textbf{v}^i,\textbf{v}^j),\ \textbf{v}^i,\textbf{v}^j\in\{\textbf{v}^R,\textbf{v}^p\}$. Then the augmented covariance $\textbf{P}_{\text{aug}}$ is computed as
\begin{equation}
\textbf{P}_{\text{aug}}=\left[
\begin{array}{cccccc}
\textbf{P}^{R,R}& \textbf{P}^{R,R}\textbf{M}_1^{T}& \textbf{P}^{R,p}& \textbf{P}^{R,p}\textbf{M}_2^{T}\\
\textbf{M}_1P^{R,R}& \textbf{P}_f^{R,R}& \textbf{M}_1\textbf{P}^{R,p}& \textbf{P}_f^{R,p}\\
\textbf{P}^{p,R}& \textbf{P}^{p,R}\textbf{M}_1^{T}& \textbf{P}^{p,p}& \textbf{P}^{p,p}\textbf{M}_2^{T}\\
\textbf{M}_2\textbf{P}^{p,R}& (\textbf{P}_f^{R,p})^T& \textbf{M}_2\textbf{P}^{p,p}& \textbf{P}_f^{p,p}\\
\end{array}
\right],
\label{Pnew_app}
\end{equation}
where
\begin{equation}
\begin{array}{rll}
\textbf{M}_1&=[\textbf{I}_3 \ \textbf{0}_{3,3K}],\\
\textbf{M}_2&=[\textbf{I}_3 \ \textbf{0}_{3,3K}],\\
\textbf{P}_f^{R,R}&=\textbf{M}_1\textbf{P}^{R,R}\textbf{M}_1^{T}+\hat{\textbf{R}}^r\bm{\Omega}^{R,R}(\hat{\textbf{R}}^r)^T,\\
\textbf{P}_f^{R,p}&=\textbf{M}_1\textbf{P}^{R,p}\textbf{M}_2^{T}+\hat{\textbf{R}}^r\bm{\Omega}^{R,p}(\hat{\textbf{R}}^r)^T,\\
\textbf{P}_f^{p,p}&=\textbf{M}_2\textbf{P}^{p,p}\textbf{M}_2^{T}+\hat{\textbf{R}}^r\bm{\Omega}^{p,p}(\hat{\textbf{R}}^r)^T.
\end{array}
\end{equation}
\subsection{Proof of Theorem 1}\label{Proof_Th1}
\begin{proof}
The observabilty matrix of the real system model (the ideal case: evaluated at the groundtruth) for RI-EKF is shown as
\iffalse
\begin{equation}
\begin{array}{rl}
&\mathcal{O}(\breve{X}^{RI})=\left[
\begin{array}{cccccc}
\breve{H}^{RI}_0\\
\breve{H}^{RI}_1\breve{F}^{RI}_{1,0}\\
\vdots\\
\breve{H}^{RI}_{n+1}\breve{F}^{RI}_{n+1,0}
\end{array}
\right]\\
&=\left[
\begin{array}{cccccc}
-{R}^T_{0}& {R}^T_{0}& 0_{3\times 3}& 0_{3\times 3}\\
0_{3\times 3}& 0_{3\times 3}& -{R}^T_{0}& {R}^T_{0}\\
\vdots& \vdots& \vdots& \vdots\\
-{R}^T_{n+1}& {R}^T_{n+1}& 0_{3\times 3}& 0_{3\times 3}\\
0_{3\times 3}& 0_{3\times 3}& -{R}^T_{n+1}& {R}^T_{n+1}\\
\end{array}
\right],
\end{array}
\end{equation}
\fi
\begin{equation}
\begin{array}{rl}
&\mathcal{\breve{\bm{O}}}^{RI}=\left[
\begin{array}{cccccc}
\breve{\textbf{H}}^{RI}_0\\
\breve{\textbf{H}}^{RI}_1\breve{\textbf{F}}^{RI}_{0,0}\\
\vdots\\
\breve{\textbf{H}}^{RI}_{n+1}\breve{\textbf{F}}^{RI}_{n,0}
\end{array}
\right]\\
&=\left[
\begin{array}{cccccc}
\breve{\textbf{H}}^{R,R^r}_0& \breve{\textbf{H}}^{R,R^f}_0& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \breve{\textbf{H}}^{p,p^r}_0& \breve{\textbf{H}}^{p,p^f}_0\\
\vdots& \vdots& \vdots& \vdots\\
\breve{\textbf{H}}^{R,R^r}_{n+1}& \breve{\textbf{H}}^{R,R^f}_{n+1}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}&\breve{\textbf{H}}^{p,p^r}_{n+1}& \breve{\textbf{H}}^{p,p^f}_{n+1}\\
\end{array}
\right],
\end{array}
\end{equation}
where $$\begin{aligned}
&\breve{\textbf{H}}^{RI}_0=\left[
\begin{array}{cccccc}
-({\textbf{R}}_{0}^r)^T& ({\textbf{R}}_{0}^r)^T& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& -({\textbf{R}}_{0}^r)^T& ({\textbf{R}}_{0}^r)^T
\end{array}
\right],\\
&\breve{\textbf{H}}^{R,R^r}_{i+1}=\breve{\textbf{H}}^{p,p^r}_{i+1}=-({\textbf{R}}_{i+1}^r)^T,\ \forall i=0,\cdots, n,\\
&\breve{\textbf{H}}^{R,R^f}_{i+1}=\breve{\textbf{H}}^{p,p^f}_{i+1}=({\textbf{R}}_{i+1}^r)^T,\ \forall i=0,\cdots, n,\\
\end{aligned}$$
$\breve{\textbf{H}}^{RI}_{i+1}$ is the Jacobian matrix for the $(i+1)$-th step observation model evaluated at the true state $\breve{\textbf{X}}^{RI}_{i+1}$, and $\breve{\textbf{F}}^{RI}_{i,0}=\breve{\textbf{F}}^{RI}_i\breve{\textbf{F}}^{RI}_{i-1}\cdots \breve{\textbf{F}}^{RI}_0$ is the identity matrix, $\breve{\textbf{F}}^{RI}_j$ is the Jacobian matrix for the $j$-th step propagation model evaluated at the true state $\breve{\textbf{X}}^{RI}_j$, $ j=0,\cdots, i$.
Based on the linearization method of RI-EKF introduced above,
we can obtain the unobservable subspace $\mathcal{\breve{N}}^{RI}$ by
\begin{equation}
\mathcal{\breve{N}}^{RI}=\mathop{\text{span}} _{col.}\left[
\begin{array}{cccccc}
\textbf{I}_{3}& \textbf{0}_{3,3}\\
\textbf{I}_{3}& \textbf{0}_{3,3}\\
\textbf{0}_{3,3}& \textbf{I}_{3}\\
\textbf{0}_{3,3}& \textbf{I}_{3}
\end{array}
\right],
\label{nullspace_app}
\end{equation}
whose dimension is 6.
Then consider the observabilty matrix $\mathcal{\hat{\bm{O}}}^{RI}$ evaluated by RI-EKF estimations,
\iffalse
\begin{equation}
\begin{array}{rl}
&\mathcal{O}(\hat{\textbf{X}}^{RI})=\left[
\begin{array}{cccccc}
\hat{\textbf{H}}^{RI}_0\\
\hat{\textbf{H}}^{RI}_1\hat{\textbf{F}}^{RI}_{1,0}\\
\vdots\\
\hat{\textbf{H}}^{RI}_{n+1}\hat{\textbf{F}}^{RI}_{n+1,0}
\end{array}
\right]\\
&=\left[
\begin{array}{cccccc}
-(\hat{R}^r_{1|0})^T& (\hat{R}^r_{1|0})^T& 0_{3\times 3}& 0_{3\times 3}\\
0_{3\times 3}& 0_{3\times 3}& -(\hat{R}^r_{1|0})^T& (\hat{R}^r_{1|0})^T\\
\vdots& \vdots& \vdots& \vdots\\
-(\hat{R}^r_{n+1|n})^T& (\hat{R}^r_{n+1|n})^T& 0_{3\times 3}& 0_{3\times 3}\\
0_{3\times 3}& 0_{3\times 3}& -(\hat{R}^r_{n+1|n})^T& (\hat{R}^r_{n+1|n})^T\\
\end{array}
\right],
\end{array}
\end{equation}
where
\fi
\begin{equation}
\begin{array}{rl}
&\mathcal{\hat{\bm{O}}}^{RI}=\left[
\begin{array}{cccccc}
\hat{\textbf{H}}^{RI}_0\\
\hat{\textbf{H}}^{RI}_1\hat{\textbf{F}}^{RI}_{0,0}\\
\vdots\\
\hat{\textbf{H}}^{RI}_{n+1}\hat{\textbf{F}}^{RI}_{n,0}
\end{array}
\right]\\
&=\left[
\begin{array}{cccccc}
\hat{\textbf{H}}^{R,R^r}_0& \hat{\textbf{H}}^{R,R^f}_0& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& \hat{\textbf{H}}^{p,p^r}_0& \hat{\textbf{H}}^{p,p^f}_0\\
\vdots& \vdots& \vdots& \vdots\\
\hat{\textbf{H}}^{R,R^r}_{n+1}& \hat{\textbf{H}}^{R,R^f}_{n+1}& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}&\hat{\textbf{H}}^{p,p^r}_{n+1}& \hat{\textbf{H}}^{p,p^f}_{n+1}\\
\end{array}
\right],
\end{array}
\end{equation}
where $$\begin{aligned}
&\hat{\textbf{H}}^{RI}_0=\left[
\begin{array}{cccccc}
-(\hat{\textbf{R}}^r_{0|0})^T& (\hat{\textbf{R}}^r_{0|0})^T& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}& -(\hat{\textbf{R}}^r_{0|0})^T& (\hat{\textbf{R}}^r_{0|0})^T\\
\end{array}\right],\\
&\hat{\textbf{H}}^{R,R^r}_{i+1}=\hat{\textbf{H}}^{p,p^r}_{i+1}=-(\hat{\textbf{R}}_{i+1|i}^r)^T,\ \forall i=0,\cdots, n,\\
&\hat{\textbf{H}}^{R,R^f}_{i+1}=\hat{\textbf{H}}^{p,p^f}_{i+1}=(\hat{\textbf{R}}_{i+1|i}^r)^T,\ \forall i=0,\cdots, n,\\
\end{aligned}$$
$\hat{\textbf{H}}^{RI}_{i+1}$ is the Jacobian matrix for the $(i+1)$-th step observation model evaluated at the estimated state $\hat{\textbf{X}}^{RI}_{i+1|i}$, and $\hat{\textbf{F}}^{RI}_{i,0}=\hat{\textbf{F}}^{RI}_i\hat{\textbf{F}}^{RI}_{i-1}\cdots \hat{\textbf{F}}^{RI}_0$, $\hat{\textbf{F}}_j$ is the Jacobian matrix for the $j$-th step propagation model evaluated at the estimated state $\hat{\textbf{X}}^{RI}_{j|j}$, $j=0,\cdots i$. The unobservable subspace $\mathcal{\hat{N}}^{RI}$ of $\mathcal{\hat{\bm{O}}}^{RI}$ is the same as (\ref{nullspace_app}).
\end{proof}
\subsection{Proof of Theorem 2}\label{Proof_Th2}
\begin{proof}
The observabilty matrix of the stdandard EKF based on state estimates is constructed as
\begin{equation}
\mathcal{\hat{\bm{O}}}^{Std}=\left[
\begin{array}{cccccc}
\hat{\textbf{H}}^{Std}_0\\
\hat{\textbf{H}}^{Std}_{1}\hat{\textbf{F}}^{Std}_{0,0}\\
\vdots\\
\hat{\textbf{H}}^{Std}_{n+1}\hat{\textbf{F}}^{Std}_{n,0}
\end{array}
\right]
\end{equation}
where $\hat{\textbf{H}}^{Std}_{i+1}$ is the Jacobian matrix evaluated at the prediction $\textbf{X}_{i+1|i}$ for the $(i+1)$-th step observation model in (\ref{FGH_std}), and
\begin{equation}
\begin{array}{rl}
&\hat{\textbf{F}}^{Std}_{i,0}=\hat{\textbf{F}}^{Std}_i\hat{\textbf{F}}^{Std}_{i-1}\cdots \hat{\textbf{F}}^{Std}_0\\
&=\left[
\begin{array}{cccccc}
\textbf{I}_6&\textbf{0}_{6\times 6}\\
\left[\begin{array}{cccccc}
\sum_{j=0}^i(\textbf{p}^r_{j|j}-\textbf{p}^r_{j+1|j})^{\land}&\textbf{0}_{3\times 3}\\
\textbf{0}_{3\times 3}&\textbf{0}_{3\times 3}
\end{array}
\right]&\textbf{I}_6
\end{array}
\right]
\end{array}
\end{equation}
$\hat{\textbf{F}}^{Std}_{j}$ is Jacobian evaluated at estimated state $\textbf{X}_{j|j}$ of process model for standard EKF in (\ref{FGH_std}).
In ideal case, the Jacobians are evaluated at the true state $\breve{\textbf{X}}_i$. Then, we have $$\textbf{p}^r_{i+1|i+1}= \textbf{p}^r_{i+1|i}$$ and $$\textbf{p}_{i+1|i}^f=\textbf{p}^f,\ \forall i.$$ And thus, $\hat{\textbf{H}}^{Std}_{i}\hat{\textbf{F}}^{Std}_{i-1,0}$ in $\mathcal{\breve{\bm{O}}}^{Std}$ for ideal case becomes
\iffalse
\begin{equation}
\begin{array}{l}
\mathcal{O}(\breve{X}^{Std})=\\
\left[
\begin{array}{cccccc}
-{R}^T_{0}& {R}^T_{0}& 0_{3\times 3}& 0_{3\times 3}\\
-{R}^T_{0}(p^f-x_0)^{\land}& 0_{3\times 3}& -{R}^T_{0}& {R}^T_{0}\\
\vdots& \vdots& \vdots& \vdots\\
-{R}^T_{n+1}& {R}^T_{n+1}& 0_{3\times 3}& 0_{3\times 3}\\
-{R}^T_{n+1}(p^f-x_0)^{\land}& 0_{3\times 3}& -{R}^T_{n+1}& {R}^T_{n+1}\\
\end{array}
\right].
\end{array}
\end{equation}
\fi
\begin{equation}
\begin{array}{l}
\hat{\textbf{H}}^{Std}_{i}\hat{\textbf{F}}^{Std}_{i-1,0}=\\
\left[
\begin{array}{cccccc}
-({\textbf{R}}^r_{i})^T& ({\textbf{R}}^r_{i})^T& \textbf{0}_{3\times 3}& \textbf{0}_{3\times 3}\\
-({\textbf{R}}^r_{i})^T(\textbf{p}^f-\textbf{p}^r_0)^{\land}& \textbf{0}_{3\times 3}& -({\textbf{R}}^r_{i})^T& ({\textbf{R}}^r_{i})^T\\
\end{array}
\right].
\end{array}
\end{equation}
\iffalse
The right null space $\mathcal{\breve{N}}^{Std}$ of this observabilty matrix spans the unobservable subspace of system, where
\begin{equation}
\mathcal{\breve{N}}^{Std}=\left[
\begin{array}{cccccc}
0_{3,3}& I_{3}\\
0_{3,3}& I_{3}\\
I_{3}& (x_0)^{\land}\\
I_{3}& (p^f)^{\land}
\end{array}
\right].
\end{equation}
\fi
Then unobservable subspace based on the ground truth is obtained as
\begin{equation}
\mathcal{\breve{N}}^{Std}=\mathop{\text{span}} _{col.}\left[
\begin{array}{cccccc}
\textbf{0}_{3,3}& \textbf{I}_{3}\\
\textbf{0}_{3,3}& \textbf{I}_{3}\\
\textbf{I}_{3}& (\textbf{p}^r_0)^{\land}\\
\textbf{I}_{3}& (\textbf{p}^f)^{\land}
\end{array}
\right].
\end{equation}
Therefore, the dimension of unobservable subspace of system is 6. The same conclusion is for the case of multiple features.
However, in practice, generally
$$\begin{array}{ll}
\textbf{p}^r_{i+1|i+1}&\neq \textbf{p}^r_{i+1|i},\\
\textbf{p}^f_{i+1|i}&\neq \textbf{p}^f_{j+1|j},\ \forall i\neq j,
\end{array} $$ and thus the unobservable subspace of standard EKF evaluated by the estimates becomes
\begin{equation}
\mathcal{\hat{N}}^{Std}=\mathop{\text{span}} _{col.}[\textbf{0}_{3\times 3},\textbf{0}_{3\times 3},\textbf{I}_3,\textbf{I}_3]^T,
\end{equation}
whose dimension is 3.
\end{proof}
\end{document}
| {'timestamp': '2021-09-14T02:13:41', 'yymm': '2109', 'arxiv_id': '2109.05297', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05297'} | arxiv |
\section{Introduction}
\label{sec:intro}
Stencil computation is an important computation paradigm that appears in many scientific applications, such as geophysics simulations~\cite{serpa17padw,farres19eage,shen20ieice}, computational electromagnetics~\cite{adams07fdtd}, and image processing~\cite{tabik18supe}. The key principle of stencil computation is to iteratively apply a fixed calculation pattern (stencil, where the update of an element relies on the surrounding elements) to every element of the output datasets.
Such a single-instruction multiple-data (SIMD) characteristic of stencil computation makes itself a perfect scenario to use the graphics processing units (GPUs) for acceleration.
A GPU has thousands of cores and its memory bandwidth is 5--10 times higher than that of a CPU, thus excelling at accelerating both compute- and memory-intensive scientific applications~\cite{okuyama14itpds,ikeda14ieeejbhi,shen17ica3pp,shen19ccpe}.
However, as a GPU has a limited capacity of device memory (tens of GBs), it fails to run a large stencil code directly whose data size exceeds its memory capacity.
A large entity of research on GPU-based out-of-core stencil computation has been performed to address this issue~\cite{jin14ichpca,sourouri16ijpp,shimokawabe17iccc,miki19hpcn,shen20ieice}. For a large dataset whose data size exceeds the capacity of the device memory, out-of-core computation first decomposes the dataset into smaller blocks and then streams the blocks to and from the GPU for processing. Nevertheless, the outcome of this approach is often limited by data transfer between the CPU and GPU because the interconnects fail to catch up with the development of the computation capability of GPUs as described in \cite{shen19ccpe}. Data-centric strategies are thus necessary to reduce the data transfer between the CPU and GPU.
Studies have introduced strategies such as temporal blocking and region sharing to reuse the on-GPU data and to avoid transferring extra data \cite{jin14ichpca,miki19hpcn,shen20ieice}.
Nevertheless, we need to further optimize the methods to reduce data transfer time. according to \cite{shen20ieice}, the performance of out-of-core stencil code is still limited by data transfer.
A potential solution is to use on-the-fly compression to compress the data on the GPU before transferring back to the CPU, and decompress the data on the GPU before processing. Until now, however, studies on the acceleration of GPU-based out-of-core stencil computation with on-the-fly compression are really rare. According to a comprehensive review \cite{cappello20review}, research on leveraging lossy compression techniques in scientific applications mainly focuses on scenarios such as post-analysis and failure recovery.
We think that the scarcity of relevant research raises two research questions:
\begin{itemize}
\item Would the overhead of compression/decompression outweighs the reduced data transfer time?
\item Would the precision loss involved by data compression be so huge that the output becomes useless?
\end{itemize}
In this study, we (1) propose a method to accelerate out-of-core stencil computation with on-the-fly compression on the GPU and (2) try to give answers to the two above-mentioned questions. The contribution of this work is three-fold:
\begin{itemize}
\item We introduced a novel approach to integrate an on-the-fly lossy compression into the workflow of a 25-point stencil computation. For large datasets that are decomposed into blocks, this approach solves the data dependency between two contiguous blocks and thus secures the accessibility to the common regions between two contiguous blocks after compression.
\item We modified a widely-used GPU-based compression library~\cite{cuZfp} to support pipelining, which is mandatory for the purpose of overlapping CPU-GPU data transfer with GPU computation.
\item We gathered experimental results to answer the aforementioned questions, i.e., on-the-fly compression is useful in reducing the overall execution time of out-of-core stencil computation, and the precision loss is tolerable. Therefore, the present study may lead to future research on leveraging compression techniques to accelerate out-of-core stencil computation on a GPU.
\end{itemize}
The remainder of this study is organized as follows: Previous studies that accelerate stencil and similar scientific applications with compression techniques are introduced in Section~\ref{sec:prew}. Stencil computation, its background and challenges in the acceleration of stencil computation with on-the-fly compression are briefly described in Section~\ref{sec:stencil}. Section~\ref{sec:compr} discusses the selection of an appropriate GPU-based compression library. The proposed method used to integrate the compression processes into the workflow of out-of-core stencil computation is described in Section~\ref{sec:proposed}. In Section~\ref{sec:expr}, experimental results are presented and analyzed. Finally, Section~\ref{sec:conc} concludes the present study and proposes future research directions.
\section{Previous Work}
\label{sec:prew}
Nagayasu \textit{et al.}~\cite{nagayasu08cg} proposed a decompression pipeline for accelerating out-of-core volume rendering of time-varying data. Their method was specified to compress and decompress RGB data and the decompression procedure was partially performed on the CPU.
Tao \textit{et al.}~\cite{tao18hpdc} proposed a lossy checkpointing scheme, which significantly improved the checkpointing performance of iterative methods with lossy compressors. In the presence of system failures, their method reduced the fault tolerance overhead for iterative methods by 23\%--70\% compared with traditional checkpointing and 20\%--58\% compared with lossless-compressed checkpointing.
Calhoun \textit{et al.}~\cite{calhoun19saga} proposed metrics to evaluate loss of accuracy caused by using lossy compression to reduce the snapshot data used for checkpoint restart. In this study, Calhoun and colleagues improved efficiency in checkpoint restart for partial differential equation (PDE) simulations by compressing the snapshot data, and found that this compression did not affect overall accuracy in the simulation, as demonstrated by the proposed evaluation metrics.
Wu \textit{et al.}~\cite{wu19sc} proposed a method to simulate large quantum circuits using lossy or lossless compression techniques adaptively. Thanks to their method, they managed to increase the simulation size by 2--16 qubits. However, their method was designed for CPU-based supercomputers and thus the compression libraries cannot be used for GPU-based scenarios. Moreover, the adaptive selection between lossy and lossless compression, i.e., using lossy compression if lossless one failed, is impractical in GPU-based applications because such failures heavily impair the computational performance.
Jin \textit{et al.}~\cite{jin20ipdps} proposed a method to use GPU-based lossy compression for extreme-scale cosmological simulations. Their findings show that GPU-based lossy
compression can enable sufficient accuracy on post-analysis for cosmological simulations, as well as high compression and decompression throughputs. Instead of compressing datasets for post-analysis, our method aims to improve the performance of GPU-based out-of-core stencil computation by compressing or/and decompressing datasets at run-time.
Tian \textit{et al.}~\cite{tian20pact} proposed Cusz, an efficient GPU-based error-bounded lossy compression framework for scientific computing. This framework reported high compression and decompression throughputs and a good compression ratio. However, according to their study, Cusz has sequential subprocedures, which prevents us to use this framework as on-the-fly compression in our work due to the concern of the overhead to shift from GPU to CPU computation.
Zhou \textit{et al.}~\cite{zhou21ipdps} designed high-performance MPI libraries with on-the-fly compression for modern GPU clusters. In their work, they reduced the inter-node communication time by compressing the messages transferred between nodes, and the size of messages was up to 32 MB. On the other hand, our method compressed large datasets for stencil computation that were more than 10 GB to reduce the data transfer time between the CPU and GPU (i.e., intra-node communication time). Moreover, our method is specified to deal with out-of-core stencil computation, solving the data dependency between decomposed data blocks.
\section{Stencil Computation}
\label{sec:stencil}
\begin{figure}
\centering
\includegraphics[width=\linewidth]{stencil.eps}
\caption{Five-point stencil computation. Subfigure (a) update of an element relies on its four neighbor elements. Subfigure (b) the decomposed blocks must be transferred with the according halo data.}
\label{fig:stencil}
\end{figure}
\begin{figure}
\centering
\includegraphics[width=\linewidth]{shareregions.eps}
\caption{The contiguous blocks can share common regions on the GPU
and thus avoid transferring the amount of data that is equivalent to the
halo areas.}
\label{fig:shareregions}
\end{figure}
Stencil computation is an iterative computation that updates each element in one or more datasets according to a fixed pattern that computes with the neighbor elements of the element to be updated.
A hello-world application of stencil computation is the solver of Laplace's equation, which can describe the phenomenon of heat conduction: A five-point stencil code, where the temperature of each element at the (\textit{t}+1)-th time step is obtained by taking the average temperature of the four surrounding elements at the \textit{t}-th time step (Fig. \ref{fig:stencil}(a)).
To use out-of-core stencil computation, we decompose the large datasets into smaller blocks and stream the blocks to and from the GPU for processing. Because of the data dependency of stencil computation, when we transfer a block to the GPU for computation, we must also piggyback the neighbor data (``halo area'' in jargon) with the block (Fig. \ref{fig:stencil}(b)). The more time steps we want to compute on a block on the GPU, the larger halo area we must transfer along with the block. But because two contiguous blocks share common regions, a block can get
the common regions from its former block and provide the common regions with its later block. By doing so, we can in effect reduce the amount of data transfer equivalent to the size of halo areas (Fig. \ref{fig:shareregions}).
One challenge in integrating on-the-fly compression into the workflow of out-of-core stencil computation is that we must solve the aforementioned data dependency. Naively compressing each block prevents the use of halo
areas, whereas compressing each block with its halo areas not only consumes more memory space but also prevents contiguous blocks sharing common regions. Therefore, sophisticated compression strategy is necessary, and will be introduced in Section \ref{sec:sep}.
\section{On-the-fly Compression}
\label{sec:compr}
Another concern in using on-the-fly compression in out-of-core computation is the overheads of compression and decompression that are often considerable. GPU-based compression libraries such as cuZFP \cite{cuZfp}, Cusz \cite{tian20pact}, and nvComp \cite{nvcomp} reported high speeds in compression and decompression. The cuZFP and Cusz libraries are lossy compression, whereas the nvComp is lossless.
In this study, we used cuZFP because this library is performant and its source code is (relatively) easy to modify to implement functionalities we want. The cuZFP library allows users to specify the compression ratio.
Users can specify the number of bits to use to preserve a value. For example, specifying 32 bits to preserve a double-precision floating-point (i.e., double-type) value achieves a compression ratio of 2:1.
We avoid using the lossless nvComp due to the concern of compression ratio. In the preliminary experiments, we found the size of data compressed with nvComp was larger than that of the uncompressed data. We therefore avoid the use of nvComp because we cannot estimate the upper bound of the size of the compressed data, so we must allocate device memory every time the compression happens instead of reusing pre-allocated device buffers with fixed sizes. The reason why we avoided using Cusz was explained in Section \ref{sec:prew}.
\section{Proposed Method}
\label{sec:proposed}
In this section, we introduce our proposed method, including separate compression that solves the data dependency between contiguous blocks and thus allows us to compress the decomposed datasets freely, and a pipelining version of cuZFP that supports overlapping compression/decompression with CPU-GPU data transfer.
\subsection{Separate Compression}
\label{sec:sep}
\begin{figure}
\centering
\includegraphics[width=\linewidth]{sepcomp.eps}
\caption{Separate compression approach to solve data dependency between contiguous blocks. In this approach, a compressed block consists of the reminder and the common region. As shown in subfigure (a), the $i$-th compressed reminder and common region are decompressed on the GPU for computation; and in subfigure (b), after computation, the reminder and common region were compressed and transferred back to CPU to update the $i$-th remainder and ($i-1$)-th common region, respectively.}
\label{fig:sepcomp}
\end{figure}
As shown in Fig. \ref{fig:shareregions}, two contiguous blocks have
common regions that are shareable. Precisely, the bottom
halo areas needed by the $i$-th block fall in the ($i+1$)-th
block, and the top halo areas needed by the ($i+1$)-th
block fall in the the ($i$)-th block. Therefore, the common
regions between the two blocks consist of the top areas
and a part of the ($i+1$)-th block whose size is equivalent
to that of the top halo areas. If we transfer the ($i$)-th block
with its bottom halo areas, we can avoid transferring the
common regions for the ($i+1$)-th block.
Summarily, each block only needs to be transferred
with its reminder and bottom halo areas, so the two
parts, i.e., reminder and half common region, must be
exclusively readable and writable to the according contiguous
blocks. Based on the observation, we propose
a separate compression approach that compress the two
parts separately. As shown in Fig. \ref{fig:sepcomp}(a), before computation, the $i$-th compressed reminder and common region
are decompressed and therefore the $i$-th block can be
computed on and provide the data needed by the $(i+1)$-
th block. As shown in Fig. \ref{fig:sepcomp}(b), after computation, the
$(i+1)$-th block are compressed as the $(i+1)$-th reminder
and $i$-th common region.
\subsection{Pipelining cuZFP}
\label{sec:pzfp}
\begin{figure}
\centering
\includegraphics[width=\linewidth]{pipeline.eps}
\caption{Modified cuZFP that supports pipelining. Three CUDA streams are used to perform operations, overlapping CPU-GPU data transfer with GPU kernels including compression, decompression, and computation.}
\label{fig:pzfp}
\end{figure}
The cuZFP library \cite{cuZfp} is mainly designed as a standalone
tool that can be seamlessly used for post-analysis
and CPU-centric scientific computations. However, as an
on-the-fly process in the out-of-core stencil computation,
we must modify the source code to support pipelining
that overlaps CPU/GPU data transfer with GPU computations.
Thanks to the excellent coding quality of the
cuZFP project, we managed to modify the source code
to add such functionality with a reasonable amount of
programming effort. In the pipelining cuZFP, we use three
CUDA \cite{cudawww} streams to perform operations (Fig. \ref{fig:pzfp}).
\section{Experimental Results}
\label{sec:expr}
\begin{table}[tb!]
\centering
\begin{tabular}{lllll} \\\hline
No. of & Data type & Dim. info. & Entire \\
datasets & & & data size \\\hline
4 & Double & (1152+2$\times$HALO)$^3$ & 46 GB \\
& & HALO$=$4 & \\\hline
\end{tabular}
\caption{Target stencil code.}
\label{tab:dataset}
\end{table}
\begin{table}[tb!]
\centering
\begin{tabular}{ll} \\\hline
GPU & NVIDIA Tesla V100-PCIe\\
Device memory & 32 GB\\
CPU & Xeon Silver 4110 \\
Host memory & 500 GB \\
OS & Ubuntu 16.04.6 \\
CUDA & 10.1 \\
cuZFP & 0.5.5\\\hline
\end{tabular}
\caption{Testbed for experiments.}
\label{tab:machine}
\end{table}
In this section, we analyze the experimental results to evaluate the benefits of using on-the-fly compression in out-of-core stencil computation on a GPU. The stencil code we used is an acoustic wave propagator from a previous work \cite{shen20ieice} of ours. The code is a 25-point stencil computation that has two read-write datasets, a write-only dataset, and a read-only dataset. The two read-write datasets store the updated elements of the volume, and needed to be transferred to and from the GPU. The write-only dataset stores intermediate results at run-time and does not need to be transferred at all. The read-only dataset are constant values that must be referenced at run-time, and needed to be transferred to the GPU. The values are of double-type because it is more preferable compared to single-precision floating-point format (i.e. \texttt{float}-type) in iterative scientific applications. According to our previous work~\cite{shen20iccc}, the CPU version of a code using float-type data leads to outputs different from that of the GPU version. Such divergence becomes a more severe problem with the increase of the total number of iterations. On the other hand, when using double-type, results of the CPU and GPU versions of the same code were consistent. Table \ref{tab:dataset} shows the detail of the datasets used by the stencil code.
Moreover, we used four codes in our experiments to evaluate the performance and precision loss. The four codes include:
\begin{enumerate}
\item The original stencil code.
\item The stencil code with one read-write dataset compressed using a 32/64 rate (i.e., using 32 bits to preserve each double value).
\item The stencil code with the read-only dataset compressed using a 32/64 rate.
\item The stencil code with one read-write dataset and the read-only dataset compressed using a 24/64 rate. Note that we used 24 bits to preserve each double value due to the limited device memory capacity.
\end{enumerate}
The configuration to run the stencil codes is as the one described in \cite{shen20ieice} where the number of division is 8 and the number of temporal blocking time steps is 12. Accordingly, we divide the data into 8 blocks, and when a block is transferred to the GPU, it will be computed on for 12 times before transferred back to the CPU. For the total time steps, we used numbers from 480 to 4320 with an increment of 480. For specifications of the testbed for all experiments performed, see Table~\ref{tab:machine}.
\subsection{Evaluation of Performance Benefits}
\label{sec:benef}
\begin{figure}
\centering
\includegraphics[width=\linewidth]{spdup.eps}
\caption{Performance of the four stencil codes.}
\label{fig:spdup}
\end{figure}
As shown in Fig. \ref{fig:spdup}, the three codes using on-the-fly compression ran faster than the original code. The code compressing a read-write dataset and a read-only dataset outperformed the others, running 1.20$\times$ as fast as the original code. The code compressing a read-only dataset and the code compressing a read-write dataset achieved speedups of 1.18$\times$ and 1.16$\times$, respectively. Based on these results, our proposed method is beneficial for GPU-based out-of-core stencil computation in terms of performance. A detailed analysis of the achieved performance improvement will be given in next section.
\subsection{Detailed Analysis of Achieved Performance Improvement}
\label{sec:detailed}
\begin{figure}
\centering
\includegraphics[width=\linewidth]{detailed.eps}
\caption{Breakdown of the execution time when the four GPU-based codes ran for 12 time steps. The execution time of a CPU-based code was measured to show the performance benefits of using GPU acceleration. Note that the bounding operation time for the fourth GPU-based code was GPU computation time (bars in the middle), whereas the bounding operation time for the other three GPU-based codes was CPU-to-GPU data transfer time (dark green bars).}
\label{fig:detail}
\end{figure}
In this experiment, we ran the four GPU-based codes individually for 12 time steps and profiled the breakdown of execution time. Moreover, we also ran a CPU-based code for 12 time steps to show the advanced performance of GPU-based code, compared to that of the CPU-based code. The CPU-based code was parallelized with OpenMP~\cite{wwwomp} and executed with 40 CPU threads. As shown in Fig. \ref{fig:detail}, we can see the three codes using compression reduced the CPU-to-GPU time (dark green bars) that limited the overall performance. The most interesting finding is that the fourth GPU-based code shifted from data-transfer-bounding to computation-bounding compared to the former three GPU-based codes, which is favorable because it theoretically means that the data transfer time can be fully hidden by the computation time.
Moreover, although the code compressing the read-only dataset did not reduce the GPU-to-CPU data transfer time, it did not involve significant compression time (dark purple). Therefore, the code compressing the read-only dataset slightly outperformed the code compressing a read-write dataset. Nevertheless, the gaps between the overall execution time and the bounding operation time (i.e., longest bar) of the three codes with compression are larger than that of the original GPU-based code. This suggests that the compression or/and decompression involved some unidentified overheads that compromised the efficiency of overlapping data transfer with GPU computation, otherwise the overall execution time should have been similar to the bounding operation time. Therefore, we need more sophisticated measures to orchestrate the pipelining to achieve further improvement.
\subsection{Evaluation of Precision Loss}
\label{sec:mod}
\begin{figure}
\centering
\includegraphics[width=\linewidth]{precloss.eps}
\caption{Change in precision loss as total time steps increase.}
\label{fig:precloss}
\end{figure}
Besides showing performance benefits, demonstrating that the compression involves no significant precision loss is crucial. After completing the total time steps, we sampled 115,200 points (i.e., 100 points per plane) and compared the point values of the three codes using compression with that of the original code to calculate the average point-wise relative errors (Fig. \ref{fig:precloss}). Although the relative errors increased with an increase in the total time steps, they were still far from significant at 4,320 time steps. The code compressing the read-only dataset had the lowest precision loss because the read-only dataset does not need to be compressed repeatedly. The code compressing one read-write dataset and the read-only dataset using 24/64 rate resulted in the largest precision loss due to the fewer bits we used to preserve the double values. Nevertheless, the code is useful because the relative error was trivial (between $10^{-6}$ and $10^{-7}$). Given this, the proposed method will not lead to intolerable precision loss at least for a moderate number of time steps.
\section{Conclusions and Future Work}
\label{sec:conc}
In this study, we introduced a method to accelerate GPU-based out-of-core stencil computation with on-the-fly compression. To realize the method, we proposed a novel approach to compress the decomposed data, solving the data dependency between contiguous blocks. We also modified the cuZFP library \cite{cuZfp} to support pipelining for overlapping data transfer with GPU computation. Experimental results show that the proposed method achieved a speedup of 1.2$\times$ at the expense of a trivial precision loss, i.e., an average point-wise relative error between $10^{-6}$ and $10^{-7}$.
The results answer the two research questions mentioned in Section \ref{sec:intro}. First, the reduction of CPU-GPU data transfer time achieved by using on-the-fly compression outweighs the overhead of compression/decompression, improving the overall performance of GPU-based out-of-core stencil computation.
Secondly, the on-the-fly compression does not cause severe precision loss for thousands of time steps.
Future work includes (1) comparing other on-the-fly compression algorithms to cuZFP and (2) orchestrating the pipelining for better efficiency in overlapping data transfer with GPU computation.
\section*{Acknowledgments}
This study was supported in part by the Japan Society for the
Promotion of Science KAKENHI under grants 20K21794, and “Program for Leading Graduate
Schools” of the Ministry of Education, Culture, Sports, Science,
and Technology, Japan.
We collaborated with Mauricio Hanzich and Albert Farr\'es (Computer Applications in Science and Engineering (CASE) Department, Barcelona Supercomputing Center (BSC)) to implement the stencil code used in this work.
| {'timestamp': '2021-09-14T02:18:37', 'yymm': '2109', 'arxiv_id': '2109.05410', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05410'} | arxiv |
\section{Introduction}
\label{sec:introduction}
\IEEEPARstart{S}{emantic} segmentation plays a prominent role in computerized surgical workflow analysis. Especially in cataract surgery, where workflow analysis can highly contribute to the reduction of intra-operative and post-operative complications\cite{RBE}, semantic segmentation is of great importance. Cataract refers to the eye's natural lens having become cloudy and causing vision deterioration. Cataract surgery is the procedure of restoring clear eye vision via cataract removal followed by artificial lens implantation. This surgery is the most common ophthalmic surgery and one of the most frequent surgical procedures worldwide~\cite{JFCS}. Semantic segmentation in cataract surgery videos has several applications ranging from phase and action recognition~\cite{RDC, DeepPhase}, irregularity detection (pupillary reaction, lens rotation, lens instability, and lens unfolding delay detection), objective skill assessment, relevance-based compression\cite{RelComp}, and so forth~\cite{IoLP, RTIT, RTSB, NoR, MTU}. Accordingly, there exist four different relevant objects in videos from cataract surgery, namely Intraocular Lens, Pupil, Cornea, and Instruments. The diversity of features of different relevant objects in cataract surgery imposes a challenge on optimal neural network architecture designation. More concretely, a semantic segmentation network is required that can simultaneously deal with (I) deformability and transparency in case of the artificial lens, (II) color and texture variation in case of the pupil, (III) blunt edges in case of the cornea, and (IV) harsh motion blur degradation, reflection distortion, and scale variation in case of the instruments (Fig.~\ref{fig: Problems}).
\begin{figure}[!tb]
\centering
\includegraphics[width=1\columnwidth]{pics/Problems4.png}
\caption{Semantic Segmentation difficulties for different relevant objects in cataract surgery videos.}
\label{fig: Problems}
\end{figure}
This paper presents a U-Net-based CNN for semantic segmentation that can adaptively capture the semantic information in cataract surgery videos.
The proposed network, termed as DeepPyram, mainly consists of three modules: (i) Pyramid View Fusion (PVF) module enabling a varying-angle surrounding view of feature map for each pixel position, (ii) Deformable Pyramid Reception (DPR) module being responsible for performing shape-wise feature extraction on the input convolutional feature map (Fig.~\ref{fig: DeepPyram}), and (iii) Pyramid Loss ($P\mathcal{L}$) module that directly supervises the multi-scale semantic feature maps. We have provided a comprehensive study to compare the performance of DeepPyram with thirteen rival state-of-the-art approaches for relevant-instance segmentation in cataract surgery. The experimental results affirm the superiority of DeepPyram, especially in the case of scalable and deformable transparent objects. To support reproducibility and further comparisons, we will release the PyTorch implementation of DeepPyram and all rival approaches and the customized annotations with the acceptance of this paper.
\begin{figure}[!tb]
\centering
\includegraphics[width=0.75\columnwidth]{pics/DeepPyram8.png}
\caption{Two major operations in DeepPyram.}
\label{fig: DeepPyram}
\end{figure}
The rest of the paper is organized as follows. In Section~\ref{sec: relatedwork}, we position our approach in the literature by reviewing the state-of-the-art semantic segmentation approaches. We then delineate the proposed network (DeepPyram) in Section~\ref{sec: Methodology}. We describe the experimental settings in Section~\ref{sec: Experimental Settings} and analyze the experimental results in Section~\ref{sec: Experimental Results}. We also provide an ablation study on DeepPyram in Section~\ref{sec: Experimental Results} and conclude the paper in Section~\ref{sec: Conclusion}.
\begin{figure*}[tb!]
\centering
\includegraphics[width=0.85\textwidth]{pics/BDF2.png}
\caption{The overall architecture of the proposed DeepPyram network. It contains Pyramid View Fusion (PVF), Deformable Pyramid Reception (DPR), and Pyramid Loss ($P\mathcal{L}$) modules.}
\label{fig: Block_diagram}
\end{figure*}
\section{Related Work}
\label{sec: relatedwork}
This section briefly reviews U-Net-based approaches, state-of-the-art semantic segmentation approaches related to attention and fusion modules, and multi-branch supervision.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{U-Net-based Networks. }}}
U-Net~\cite{U-Net} was initially proposed for medical image segmentation and achieved succeeding performance being attributed to its skip connections. In the encoder side of this encoder-decoder network, low-level features are combined and transformed into semantic information with low resolution. The decoder network improves these low-resolution semantic features and converts them to semantic segmentation results with the same resolution as the input image. The role of skip connections is to transmit the fine-grained low-level feature maps from the encoder to the decoder layers. The coarse-grained semantic feature maps from the decoder and fine-grained low-level feature maps from the encoder are accumulated and undergo convolutional operations. This accumulation technique helps the decoder retrieve the object of interest's high-resolution features to provide delineated semantic segmentation results. Many U-Net-based architectures have been proposed over the past five years to improve the segmentation accuracy and address different flaws and restrictions in the previous architectures~\cite{SegNet, FED-Net, RAUNet, CE-Net, MultiResUNet, dU-Net, PAANet, BARNet, CPFNet, UNet++}.
In SegNet~\cite{SegNet}, non-linear upsampling in a decoder's layer is performed using the stored max-pooling indices in its symmetrical encoder's layer. The sparse upsampled feature maps are then converted to dense feature maps using convolutional layers.
In another work, dU-Net~\cite{dU-Net} replaces the classic convolutional operations in U-Net with deformable convolutions~\cite{DeformConv} to deal with shape variations.
Full-Resolution Residual Networks (FRRN) adopt a two-stream architecture, namely the residual and the pooling stream~\cite{FRRN}. The residual stream preserves the full resolution of the input image. The pooling stream employs consecutive full-resolution residual units (FRRU) to add semantic information to the residual stream gradually.
Inspired by FRNN, Jue~\emph{et al.\xspace}~\cite{MRRC} developed two types of multiple resolution residually connected networks (MRRN) for lung tumor segmentation. The two versions of MRNN, namely incremental-MRNN and dense-MRNN, aim to fuse varying-level semantic feature maps with different resolutions to deal with size variance in tumors.
It is argued that the optimal depth of a U-Net architecture for different datasets is different. UNet++~\cite{UNet++} as an ensemble of varying-depth UNets is proposed to address this depth optimization problem.
Hejie~\emph{et al.\xspace}~\cite{Fused-UNet++} employe UNet++ as their baseline and add dense connections between the blocks with matching-resolution feature maps for pulmonary vessel segmentation.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Attention Modules. }}}
Attention mechanisms can be broadly described as the techniques to guide the network's computational resources (\textit{i.e.}, the convolutional operations) towards the most determinative features in the input feature map. Such mechanisms have been especially proven to be gainful in the case of semantic segmentation.
Inspired by Squeeze-and-Excitation block~\cite{SAE}, the SegSE block~\cite{AFRR} and scSE block~\cite{SCSE} aim to utilize inter-channel dependencies and recalibrate the channels spatially by applying fully connected operations on the globally pooled feature maps.
RAUNet~\cite{RAUNet} includes an attention module to merge the multi-level feature maps from the encoder and decoder using global average pooling. BARNet~\cite{BARNet} adopts a bilinear-attention module to extract the cross semantic dependencies between the different channels of a convolutional feature map. This module is specially designed to enhance the segmentation accuracy in the case of illumination and scale variation for surgical instruments.
PAANET~\cite{PAANet} uses a double attention module (DAM) to model semantic dependencies between channels and spatial positions in the convolutional feature map.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Fusion Modules. }}}
Fusion modules can be characterized as modules designed to improve semantic representation via combining several feature maps. The input feature maps could range from varying-level semantic features to the features coming from parallel operations.
PSPNet~\cite{PSPNet} adopts a pyramid pooling module (PPM) containing parallel sub-region average pooling layers followed by upsampling to fuse the multi-scale sub-region representations. This module has shown significant improvement and is frequently used in semantic segmentation architectures~\cite{3D-PPN}.
Atrous spatial pyramid pooling (ASPP)~\cite{DeepLab, DeepLabv3+} was proposed to deal with objects' scale variance as an efficient alternative to Share-net~\cite{AtS}. Indeed, the ASPP module aggregates multi-scale features extracted using parallel varying-rate dilated convolutions and obviates the need to propagate and aggregate the features of multi-scale inputs. This module is employed in many segmentation approaches due to its effectiveness in capturing multi-scale contextual features~\cite{MSCA, AFPNet, 3D-ASPP}.
Autofocus Convolutional Layer~\cite{Autofocus} uses a novel approach to fuse resulting feature maps of dilated convolutions adaptively. CPFNet~\cite{CPFNet} uses another fusion approach for scale-aware feature extraction. MultiResUNet~\cite{MultiResUNet} and Dilated MultiResUNet~\cite{DilatedMultiResUNet} factorize the large and computationally expensive receptive fields into a fusion of successive small receptive fields.
\begin{figure*}[!tb]
\centering
\includegraphics[width=1\textwidth]{pics/BD00.png}
\caption{The detailed architecture of the Deformable Pyramid Reception (DPR) and Pyramid View Fusion (PVF) modules.}
\label{fig: DPR}
\end{figure*}
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Multi-Branch Supervision. }}}
The idea of deep supervision was initially proposed by Chen-Yu~\emph{et al.\xspace}~\cite{DSN}. The authors proved that introducing a classifier (SVM or Softmax) on top of hidden layers can improve the learning process and minimize classification failure.
This idea is simultaneously adopted by GoogleNet~\cite{GoogleNet} to facilitate gradient flow in deep neural network architectures.
The auxiliary loss in PSPNet~\cite{PSPNet} follows the same strategy and guides one feature map in the encoder network to reinforce learning discriminative features in shallower layers.
The architecture of DensNets~\cite{DCCN} implicitly enables such deep supervision. Multi-branch supervision approaches are frequently used for improving semantic segmentation. Qi~\emph{et al.\xspace}~\cite{3DDSN} suggest directly supervising multi-resolution feature maps of the encoder network by adding deconvolutional layers followed by a Softmax activation layer on top of them. Zhu~\emph{et al.\xspace}~\cite{DSPS} adopt five deep supervision modules for the multi-scale feature maps in the encoder network and three deep supervision modules in the decoder network. In each module, the input feature map is upsampled to its original version and undergoes a deconvolutional layer which extracts semantic segmentation results.
The nested architecture of UNet++~\cite{UNet++} inherently provides such multi-depth semantic feature maps with original resolution.
\section{Methodology}
\label{sec: Methodology}
\subsection{Overview}
Fig.~\ref{fig: Block_diagram} depicts the architecture of the proposed network. Overall, the network consists of a contracting path and an expanding path. The contracting path is responsible for converting low-level to semantic features. The expanding path accounts for performing super-resolution on the coarse-grained semantic feature maps and improving the segmentation accuracy by taking advantage of the symmetric\footnote{Symmetric feature maps are the feature maps with the same spatial resolution.} fine-grained feature maps. The encoder network in the baseline approach is VGG16, pretrained on ImageNet. The decoder network consists of three modules: (i) Pyramid View Fusion (PVF), which induces a large-scale view with progressive angles, (ii) Deformable Pyramid Reception (DPR), which enables a large, sparse, and learnable receptive field, which can sample from up to seven pixels far from each pixel position in the input convolutional feature map, and (iii) Pyramid Loss ($P\mathcal{L}$), which is responsible for the direct supervision of multi-scale semantic feature maps. In the following subsections, we detail each of the proposed modules.
\subsection{Pyramid View Fusion (PVF)} By this module, we aim to stimulate a neural network deduction process analogous to the human visual system. Due to non-uniformly distributed photoreceptors on the retina, the perceived region with high resolution by the human visual system is up to $2-5\degree$ of visual angle centering around the gaze~\cite{Af}. Correspondingly, we infer that the human eye recognizes the semantic information considering not only the internal object's content but also the relative information between the object and the surrounding area. The pyramid view fusion (PVF) module's role is to reinforce the feeling of such relative information at every distinct pixel position. One way to exploit such relative features is to apply convolutional operations with large receptive fields. However, increasing the receptive field's size is not recommended due to imposing huge additional trainable parameters, and consequently (i) escalating the risk of overfitting and (ii) increasing the requirement to more annotations. Alternatively, we use average pooling for fusing the multi-angle local information in our novel attention mechanism. At first, as shown at the bottom of Fig.~\ref{fig: DPR}, a bottleneck is formed by employing a convolutional layer with a kernel size of one to curb the computational complexity. After this dimensionality reduction stage, the convolutional feature map is fed into four parallel branches. The first branch is a global average pooling layer followed by upsampling. The other three branches include average pooling layers with progressive filter sizes and the stride of one. Using a one-pixel stride is specifically essential for obtaining pixel-wise centralized pyramid view in contrast with region-wise pyramid attention in PSPNet~\cite{PSPNet}. The output feature maps are then concatenated and fed into a convolutional layer with four groups. This layer is responsible for extracting inter-channel dependencies during dimensionality reduction. A regular convolutional layer is then applied to extract joint intra-channel and inter-channel dependencies before being fed into a layer-normalization function.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Discussion. }}}There are three significant differences between the \textbf{PVF module} in DeepPyram and pyramid pooling module in PSPNet~\cite{PSPNet}: (i) All average pooling layers in the PVF module use a stride of one pixel, whereas the average pooling layers in PSPNet adopt different strides of 3, 4, and 6 pixels. The pyramid pooling module separates the input feature map into varying-size sub-regions and plays the role of object detection as region proposal networks (RPNs~\cite{RPN}). However, the stride of one pixel in the PVF module is used to capture the subtle changes in pyramid information that is especially important for segmenting the narrow regions of objects such as instruments and the artificial lens hooks\footnote{Precise segmentation of the artificial lens hooks is crucial for lens rotation and irregularity detection.}. These subtle differences can be diluted after fusing the pyramid information in the pyramid pooling module in PSPNet. (ii) In contrast with PSPNet, the PVF module applies three functions to the concatenated features to capture high-level contextual features: (1) a group convolution function to fuse the features obtained from the average pooling filters independently (as in PSPNet), (2) a convolutional operation being responsible for combining the multi-angle local features to reinforce the semantic features corresponding to each target label, and (3) a layer normalization function that accelerates training and avoids overfitting to the color and contrast information in case of few annotations.
\subsection{Deformable Pyramid Reception (DPR)}
Fig.~\ref{fig: DPR} (top) demonstrates the architecture of the deformable pyramid reception (DPR) module. At first, the fine-grained feature map from the encoder and coarse-grained semantic feature map from the previous layer are concatenated. Afterward, these features are fed into three parallel branches: a regular $3\times 3$ convolution and two deformable blocks with different dilation rates. These layers together cover a learnable sparse receptive field of size $15\times 15$\footnote{The structured $3\times 3$ filter covers up to one pixel far from the central pixel). The deformable filter with $dilation=3$ covers an area from two to four pixels far away from each central pixel. The second deformable convolution with $dilation=6$ covers an area from five to seven pixels far away from each central pixel. Therefore, these layers together form a sparse filter of size $15\times 15$ pixels. This sparse kernel can be better seen in Fig.~\ref{fig: DeepPyram}.}. The output feature maps are then concatenated before undergoing a sequence of regular layers for higher-order feature extraction and dimensionality reduction.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Deformable Block. }}}
Dilated convolutions can implicitly enlarge the receptive field without imposing additional trainable parameters. Dilated convolutional layers can recognize each pixel position's semantic label based on its cross-dependencies with varying-distance surrounding pixels. These layers are exploited in many architectures for semantic segmentation~\cite{MSCA, DeepLab, AFPNet}. Due to the inflexible rectangle shape of the receptive field in regular convolutional layers, however, the feature extraction procedure cannot be adapted to the target semantic label's shape. Dilated deformable convolutional layers can effectively support the object's geometric transformations in terms of scale and shape. As shown in the \textit{Deformable Block} in Fig.~\ref{fig: DPR}, a regular convolutional layer is applied to the input feature map to compute the offset field for deformable convolution. The offset field provides two values per element in the convolutional filter (horizontal and vertical offsets). Accordingly, the number of offset field's output channels for a kernel of size $3\times 3$ is equal to 18. Inspired by dU-Net~\cite{dU-Net}, the convolutional layer for the offset field is followed by an activation function. We use the hard tangent hyperbolic function (HardTanh), which is computationally cheap, to clip the offset values in the range of $[-1,1]$. The deformable convolutional layer uses the learned offset values along with the convolutional feature map with a predetermined dilation rate to extract object-adaptive features.
The output feature map ($y$) for each pixel position ($p_0$) and the receptive field ($\mathcal{RF}$) for a regular 2D convolution with a $3\times 3$ filter and dilation rate of one can be defined as:
\begin{equation}
y(p_o)=\sum_{p_i\in \mathcal{RF}_1}{x(p_0+p_i).w(p_i)}
\end{equation}
\begin{equation}
\mathcal{RF}_1=\{(-1,-1),(-1,0), ..., (1,0),(1,1)\}
\end{equation}
Where $x$ denotes the input convolutional feature map and $w$ refers to the weights of the convolutional kernel. In a dilated 2D convolution with a dilation rate of $\alpha$, the receptive field can be defined as $\mathcal{RF}_{\alpha}=\alpha \times \mathcal{RF}_1$. Although the sampling locations in a dilated receptive field have a greater distance with the central pixel, they follow a firm structure. In a deformable dilated convolution with a dilation rate of $\alpha$, the sampling locations of the receptive field are dependent to the local contextual features. In the proposed deformable block, the sampling location for the $i$th element of the receptive field and the input pixel $p_0$ can be formulated as:
\begin{equation}
\begin{aligned}
\mathcal{RF}_{def,\alpha}[i,p_{0}]=& \mathcal{RF}_\alpha[i]\\
+&f(\sum_{p_j\in \mathcal{RF}_1}{x(p_0+p_j).\hat{w}(p_j)})
\end{aligned}
\label{eq: RF3}
\end{equation}
In~\eqref{eq: RF3}, $f$ denotes the activation function, which is the tangent hyperbolic function in our case, and $\hat{w}$ refers to the weights of the offset filter. This learnable receptive field can be adapted to every distinct pixel in the convolutional feature map and allows the convolutional layer to extract more informative semantic features compared to the regular convolution.
\begin{figure}[!tb]
\centering
\includegraphics[width=1\columnwidth]{pics/PL7.png}
\caption{Demonstration of the \textit{Pyramid Loss} module.}
\label{fig:PL}
\end{figure}
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Discussion. }}}deformable convolutions are usually used for video object detection, tracking, and segmentation since a deformable layer needs offsets. These offsets are usually provided by optical flow computation, subtracting consecutive frames, or substracting the corresponding feature maps of consecutive frames (as in MaskProp~\cite{MaskProp} and MF-TAPNet~\cite{ITP}). Since we use videos recorded in usual and non-laboratory conditions, we have many problems in the video dataset such as defocus blur and harsh motion blur (due to fast movements of eye and motions of the instruments~\cite{DCS}). Using temporal information for semantic segmentation (as in MaskProp~\cite{MaskProp}) may lead to error accumulation and less precise results. Moreover, video object segmentation requires much more annotations which is an additional burden on the expert surgeons' time. For the DPR module, we propose (1) a deformable block to apply deformable convolutions based on learned offsets from static information, (2) a combination of deformable and static filters which can not only capture the edge-sensitive information in the case of sharp edges (as in pupil and lens), but also can cover a large area (up to a size of $15\times 15$ pixels) to deal with color and scale variations, blunt edges in case of cornea, and reflections in case of instruments.
\subsection{Pyramid Loss (P$\mathcal{L}$)}
The role of this module is to directly supervise the multi-scale semantic feature maps on the decoder's side. As shown in Fig~\ref{fig:PL}, in order to enable direct supervision, a fully connected layer is formed using a pixel-wise convolution operation. The output feature map presents the semantic segmentation results with the same resolution as the input feature map. To compute the loss for varying-scale outputs, we downscale the ground-truth masks using inter-nearest downsampling for multi-class segmentation and max-pooling for binary segmentation. The overall loss is defined as:
\begin{equation}
P\mathcal{L} = \mathcal{L}_1 + \alpha \mathcal{L}_2 + \beta \mathcal{L}_4 + \gamma \mathcal{L}_8
\end{equation}
Where $\alpha$, $\beta$, and $\gamma$ are predetermined weights in the range of $[0,1]$ (In the experiments, we have set $\alpha = 0.75$, $\beta=0.5$, and $\gamma = 0.25$). Besides, $\mathcal{L}_i$ denotes the loss of output mask segmentation result with the resolution of $(1/i)$ compared to the input resolution.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Discussion. }}}The auxiliary losses for deep semantic segmentation that are proposed to date have two different purposes: (1) Many auxiliary losses aim to guide one or more feature maps in the encoder subnetwork to prevent gradient vanishing due to using a deep architecture (for instance ResNet50) as the backbone. (2) Some auxiliary losses attempt to improve the segmentation accuracy by directly guiding different layers of the encoder or decoder network. In the second case, the loss is computed by performing super-resolution through interpolating the output feature map (to obtain a feature map with the same resolution as the ground truth) and comparing it to the ground truth. In contrast, the $P\mathcal{L}$ module directly compares each feature map to the downsampled version of the ground truth. This strategy is more time-efficient and computationally less expensive compared to the previously proposed auxiliary losses. Moreover, in contrast with state-of-the-art approaches, each loss branch in the $P\mathcal{L}$ module only consists of $Conv2D + Softmax$ to keep the number of trainable parameters as few as possible.
\import{Tables/}{Rivals_inf.tex}
\section{Experimental Setup}
\label{sec: Experimental Settings}
\noindent{\textit{\textbf{Datasets. }}}
We have used four datasets with varying instance features to provide extensive evaluations for the proposed and rival approaches. The two public datasets include the ``Cornea''~\cite{RelComp} and ``Instruments"~\cite{CaDIS} mask annotations. Additionally, we have prepared a customized dataset for ``Intraocular Lens" and ``Pupil" pixel-wise segmentation\footnote{The dataset will be publicly released with the acceptance of the paper.}. The number of training and testing images for the aforementioned objects are 178:84, 3190:459, 141:48, and 141:48, respectively. All training and testing images are sampled from distinctive videos to meet real-world conditions. Our annotations are performed using the ``supervise.ly" platform\footnote{https://supervise.ly/} based on the guidelines from cataract surgeons.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Rival Approaches. }}}
Table~\ref{tab:specification} details the specifications of the proposed approach and rival approaches employed in our experiments. To provide a fair comparison, we adopt our improved version of PSPNet, featuring a decoder designed similarly to U-Net (with four sequences of double-convolution blocks). Besides, our version of du-Net has the same number of filter-response-maps as for U-Net.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Data Augmentation Methods. }}}
Data augmentation is a vital step during training, which prevents network overfitting and boosts the network performance in the case of unseen data. Accordingly, the training images for all evaluations undergo various augmentation approaches before being fed into the network. We chose the transformations considering the inherent and statistical features of datasets. For instance, we use motion blur transformation to encourage the network to deal with harsh motion blur regularly occurring in cataract surgery videos~\cite{DCS}. Table~\ref{tab:aug} details the adopted augmentation pipeline. Each listed method is randomly applied to the input pairs of images and masks with the probability of $0.5$.
\begin{table}[th!]
\renewcommand{\arraystretch}{0.9}
\caption{Augmentation Pipeline.}
\label{tab:aug}
\centering
\begin{tabu}{lcc}
\specialrule{.12em}{.05em}{.05em
Augmentation Method&Property&Value\\\specialrule{.12em}{.05em}{.05em
Brightness~\& Contrast&Factor Range&(-0.2,0.2)\\
Shift~\& Scale&Percentage&10\%\\
Rotate&Degree Range&[-10,10]\\
Motion Blur&Kernel-Size Range &(3,7)\\
\specialrule{.12em}{.05em}{0.05em
\end{tabu}
\end{table}
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Neural Network Settings. }}}
As listed in Table~\ref{tab:specification}, U-Net, MultiResUNet, and dU-Net do not adopt a pretrained backbone. For the other approaches, the weights of the backbone are initialized with ImageNet~\cite{ImageNet} training weights.
The input size of all models is set to $3\times 512\times 512$. In the evaluation and testing stages of UNet++/DS and DeepPyram, we disregard the additional output branches (branches related to auxiliary loss functions) and only consider the master output branch.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Training Settings. }}}
Due to the different depth and connections of the proposed and rival approaches, all networks are trained with three different initial learning rates ($lr\in\{0.0005,0.0002,0.001\}$), and the results with the highest IoU for each network are listed. The learning rate is scheduled to decrease every two epochs with the factor of $0.8$. In all different evaluations, the networks are trained end-to-end and for 30 epochs. We use a threshold of $0.1$ for gradient clipping during training\footnote{Gradient clipping is used to clip the error derivatives during back-propagation to prevent gradient explosion.}.
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Loss Function. }}}
The \textit{cross entropy log dice} loss, which is used during training, is a weighted sum of binary cross-entropy ($BCE$) and the logarithm of soft Dice coefficient as follows:
\begin{equation}
\begin{aligned}
\mathcal{L} = &(\lambda)\times BCE(\mathcal{X}_{true}(i,j),\mathcal{X}_{pred}(i,j))\\
&-(1-\lambda)\times (\log \frac{2\sum \mathcal{X}_{true}\odot \mathcal{X}_{pred}+\sigma}{\sum \mathcal{X}_{true} + \sum \mathcal{X}_{pred}+ \sigma})
\end{aligned}
\label{eq: loss}
\end{equation}
\iffalse
\begin{equation}
\begin{split}
Loss_{CE-dice} &= -(\alpha)\times \sum_{i=1}^{W}{\sum_{j=1}^{H}{I_{true}(i,j)\log{(I_{pred}(i,j))}}}\\
&+(1-\alpha)\times \frac{2|M_{true}\cap M_{pred}|}{|M_{true}|+|M_{pred}|}
\end{split}
\end{equation}
\begin{equation}
\begin{aligned}
\mathcal{L} = &-(\lambda)\times \sum_{i=1}^{W}{\sum_{j=1}^{H}{\mathcal{X}_{true}(i,j)\log{(\mathcal{X}_{pred}(i,j))}}}\\
&-(1-\lambda)\times (\log \frac{2|\mathcal{M}_{true}\cap \mathcal{M}_{pred}|+s}{|\mathcal{M}_{true}|+|\mathcal{M}_{pred}|+s})
\end{aligned}
\end{equation}
\fi
Where $\mathcal{X}_{true}$ denote the ground truth binary mask, and $\mathcal{X}_{pred}$ denote the predicted mask ($0\leq \mathcal{X}_{pred}(i,j) \leq 1$). The parameter $\lambda \in [0,1]$ is set to $0.8$ in our experiments, and $\odot$ refers to Hadamard product (element-wise multiplication). Besides, the parameter $s$ is the Laplacian smoothing factor which is added to (i) prevent division by zero, and (ii) avoid overfitting (in experiments, $\sigma = 1$).
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Evaluation Metrics. }}}
The Jaccard metric (Intersection-over-Union -- IoU) and the Dice Coefficient (F1-score) are regarded as the major semantic segmentation indicators. Accordingly, we evaluate the proposed and rival approaches using average IoU and dice. In order to enable a broader analysis of the networks' performance, the standard deviation of IoU, and minimum and maximum of dice coefficient over all of the testing images are additionally compared.
\import{BarChart/}{bar11.tex}
\begin{table*}[t!]
\renewcommand{\arraystretch}{0.9}
\caption{Impact of different modules on the segmentation results (IoU\% and Dice\%) of DeepPyram.}
\label{tab:ablation2}
\centering
\begin{tabular}{m{0.5cm} m{0.5cm} m{0.5cm} ccccccccccc}
\specialrule{.12em}{.05em}{.05em
\multicolumn{3}{c}{Modules}&&\multicolumn{2}{c}{Lens}&\multicolumn{2}{c}{Pupil}&\multicolumn{2}{c}{Cornea}&\multicolumn{2}{c}{Instrument}&\multicolumn{2}{c}{Overall}\\\cmidrule(lr){1-3}\cmidrule(lr){5-6}\cmidrule(lr){7-8}\cmidrule(lr){9-10}\cmidrule(lr){11-12}\cmidrule(lr){13-14}
PVF&DPR&$P\mathcal{L}$&Params&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)\\\specialrule{.12em}{.05em}{.05em}
\ding{55}&\ding{55}&\ding{55}&22.55 M&82.98&90.44&95.13&97.48&86.02&92.28&69.82&79.05&83.49&89.81\\
\checkmark&\ding{55}&\ding{55}&22.99 M&83.73&90.79&96.04&97.95&88.43&93.77&72.58&81.84&85.19&91.09\\
\ding{55}&\checkmark&\ding{55}&23.17 M&81.85&89.58&95.32&97.59&86.43&92.55&71.57&80.60&83.79&90.08\\
\checkmark&\checkmark&\ding{55}&23.62 M&83.85&90.89&95.70&97.79&89.36&94.29&72.76&82.00&85.42&91.24\\
\checkmark&\checkmark&\checkmark&23.62 M&\textbf{85.84}&\textbf{91.98}&\textbf{96.56}&\textbf{98.24}&\textbf{90.24}&\textbf{94.77}&\textbf{74.40}&\textbf{83.30}&\textbf{86.76}&\textbf{92.07}\\ \specialrule{.12em}{.05em}{.05em
\end{tabular}
\label{tab:modules}
\end{table*}
\vspace{0.5\baselineskip}
\noindent{\textit{\textbf{Ablation Study Settings. }}}
To evaluate the effectiveness of different modules, we have implemented another segmentation network, excluding all the proposed modules. This network has the same backbone as our baseline (VGG16). However, the PVF module is completely removed from the network. Besides, the DPR module is replaced with a sequence of two convolutional layers, each of which is followed by a batch normalization layer and a ReLU layer. The connections between the encoder and decoder remain the same as DeepPyram. Besides, DeepPyram++ in ablation studies is the nested version of DeepPyram implemented based on UNet++.
\import{BarChart/}{bar3.tex}
\section{Experimental Results}
\label{sec: Experimental Results}
\subsection{Relevant Object Segmentation}
Fig.~\ref{IoU} compares the resulting IoU of DeepPyram and thirteen rival approaches\footnote{SegNet did not converge during training for instrument segmentation with different initial learning rates.}. Overall, the rival approaches have shown a different level of performance for each of the four relevant objects.
Based on the mean IoU, the best four segmentation approaches for each of the four relevant objects are listed in descending order below:
\begin{itemize}
\item \textit{Lens:} DeepPyram, Unet++, PSPNet+, UNet++/DS
\item \textit{Pupil:} DeepPyram, Unet++, UNet++/DS, FEDNet
\item \textit{Cornea:} DeepPyram, PSPNet+, CPFNet, UNet++/DS
\item \textit{Instrument:} DeepPyram, Unet++, RAUNet, BARNet
\end{itemize}
Accordingly, DeepPyram, Unet++, and PSPNet+ contribute to the top three segmentation results for the relevant objects in cataract surgery videos. However, DeepPyram shows considerable improvement in segmentation accuracy compared to the second-best approach in each class. Specifically, DeepPyram has achieved more than $4\%$ improvement in lens segmentation ($85.61\%$ vs. $81.32\%$) and more than $4\%$ improvement in instrument segmentation ($74.40\%$ vs. $70.11\%$) compared to UNet++ as the second-best approach. Moreover, DeepPyram appears to be the most reliable approach considering the smallest standard deviation compared to the rival approaches. This significant improvement is attributed to the PVF, DPR, and $P\mathcal{L}$ modules.
As shown in Fig~\ref{fig:dice}, DeepPyram has achieved the highest dice coefficient compared to the rival approaches for the lens, pupil, cornea, and instrument segmentation. Moreover, DeepPyram is the most reliable segmentation approach based on achieving the highest minimum dice percentage.
Fig.~\ref{fig:Vis} further affirms the effectiveness of DeepPyram in enhancing the segmentation results. Taking advantage of the pyramid view provided by the PVF module, DeepPyram can handle reflection and brightness variation in instruments, blunt edges in the cornea, color and texture variation in the pupil, as well as transparency in the lens. Furthermore, powering by deformable pyramid reception, DeepPyram can tackle scale variations in instruments and blunt edges in the cornea. In particular, we can perceive from Fig.~\ref{fig:Vis} that DeepPyram shows much less distortion in the region of edges (especially in the case of the cornea. Furthermore, based on these qualitative experiments, DeepPyram shows much better precision and recall in the narrow regions for segmenting the instruments and other relevant objects in the case of occlusion by the instruments.
\subsection{Ablation Study}
Table~\ref{tab:modules} validates the effectiveness of the proposed modules in segmentation enhancement. The PVF module can notably enhance the performance for cornea and instrument segmentation ($2.41\%$ and $2.76\%$ improvement in IoU, respectively). This improvement is due to the ability of the PVF module to provide a global view of varying-size sub-regions centering around each distinctive spatial position. Such a global view can reinforce semantic representation in the regions corresponding to blunt edges and reflections. Due to scale variance in instruments, the DPR module can effectively boost the segmentation performance for instruments. The addition of $P\mathcal{L}$ module results in the improvement of IoU for all relevant segments, especially lens segmentation (around $2\%$ improvement) and Instrument ($1.64\%$ improvement). The combination of PVF, DPR, and $P\mathcal{L}$ modules can contribute to $4.58\%$ improvement in instrument segmentation and $4.22\%$ improvement in cornea segmentation (based on IoU\%). These modules have improved the IoU for the lens and pupil by $2.85\%$ and $1.43\%$, respectively.
Overall\footnote{The ``Overall" column in Table~\ref{tab:modules} is the mean of the other four average values.}, the addition of different modules of DeepPyram has led to considerable improvement of segmentation performance ($3.27\%$ improvement in IoU) on average compared to the baseline approach. The PVF module can provide varying-angle global information centering around each pixel in the convolutional feature map to support relative information access. The DPR module enables large-field content-adaptive reception while minimizing the additive trainable parameters.
It should be noted that even our baseline approach has much better performance compared to some rival approaches. We argue that the fusion modules adopted in some rival approaches may lead to the dilution of discriminative semantic information.
\begin{figure*}[tb!]
\centering
\includegraphics[width=0.9\textwidth]{pics/replace_module1.png}
\caption{The overall architecture of DeepPyram compared to its three alternatives. The locations A, B, C, and D in each architecture correspond to the four modules for which we visualize the feature representations in Fig.~\ref{fig: replace_module_vis}.}
\label{fig: replace_module}
\end{figure*}
\begin{figure*}[tb!]
\centering
\includegraphics[width=0.9\textwidth]{pics/ScoreCAM3.png}
\caption{Visualization of the effect of the proposed and alternative modules based on class activation maps~\cite{Score-CAM} using the network architectures demonstrated in Fig.~\ref{fig: replace_module}. For each approach, the figures from left to right represent the gray-scale activation maps, heatmaps, and heatmaps on images for a representative input image from the test set.}
\label{fig: replace_module_vis}
\end{figure*}
\subsection{Comparisons with Alternative Modules}
Herein, we compare the effectiveness of the proposed modules with our enhanced version of the ASPP module~\cite{DeepLab} and PPM~\cite{PSPNet}. More concretely, we replace the PVF module with PPM (referring to as $Alternative^{PPM}$) and DPR module with our improved version of the ASPP module (referring to as $Alternative^{ASPP+}$). Fig.~\ref{fig: replace_module} demonstrates the architecture of DeepPyram versus the alternative networks. The difference between the modules ASPP+ and ASPP lies in the filter size of the convolutional layers. In the ASPP module, there are four parallel convolutional layers: a pixel-wise convolutional layer and three dilated convolutions with different dilation rates. In ASPP+, the pixel-wise convolution is replaced with a $3\times 3$ convolutional layer that effectively enhances the segmentation performance. Instead of three dilated convolutions in ASPP+, we use two dilated convolutions with the same dilation rates as in the DPR module. Moreover, the parallel feature-maps in the ASPP module are fused using a pixel-wise convolution, whereas the ASPP+ module adopts a kernel-size of $3\times 3$ to boost the segmentation performance. Besides, we have removed the $P\mathcal{L}$ module and referred to it as $DeepPyram^{-P\mathcal{L}}$, to qualitatively compare its performance with DeepPyram. As illustrated in Fig.~\ref{fig: replace_module}, location ``A" corresponds to the output of the last encoder's layer in the bottleneck. locations ``B-D" are the outputs of three modules in the same locations of the decoder networks in DeepPyram and the three alternative networks. Fig.~\ref{fig: replace_module_vis} compares the class activation maps corresponding to these four locations in DeepPyram and alternative approaches for cornea segmentation in a representative image~\footnote{These activation maps are obtained using Score-CAM~\cite{Score-CAM} visualization approach.}. A comparison between the activation maps of DeepPyram and $DeepPyram^{-P\mathcal{L}}$ indicates how negatively removing the $P\mathcal{L}$ module affects the discrimination ability in different semantic levels. It is evident that the activation map of block ``C" in DeepPyram is even more concrete compared to the activation map of block ``D" (which is in a higher semantic level) in $DeepPyram^{-P\mathcal{L}}$. We can infer that the $P\mathcal{L}$ module can effectively reinforce the semantic representations in different semantic levels of the network. The effect of pixel-wise global view (PVF module) versus region-wise global view (PPM) can be inferred by comparing the activation maps of DeepPyram and $Alternative^{PPM}$. The activation maps of $Alternative^{PPM}$ are impaired and distorted in different regions, especially in the lower semantic layers. The activation maps of $Alternative^{ASPP+}$ compared to DeepPyram confirm that replacing the deformable convolutions with regular convolutions can negatively affect semantic representation in narrow regions and the object borders. Table~\ref{tab:module-comparison} provides quantitative comparisons among the proposed and alternative networks. These results further confirm the effectiveness of the proposed PVF and DPR modules compared to their alternatives.
\begin{table*}[!t]
\renewcommand{\arraystretch}{0.9}
\caption{Impact of alternative modules on the segmentation results (IoU\% and Dice\%) of DeepPyram.}
\label{tab:module-comparison}
\centering
\begin{tabular}{lccccccccccc}
\specialrule{.12em}{.05em}{.05em}%
&&\multicolumn{2}{c}{Lens}&\multicolumn{2}{c}{Pupil}&\multicolumn{2}{c}{Cornea}&\multicolumn{2}{c}{Instrument}&\multicolumn{2}{c}{Overall}\\\cmidrule(lr){3-4}\cmidrule(lr){5-6}\cmidrule(lr){7-8}\cmidrule(lr){9-10}\cmidrule(lr){11-12}
Network&Params&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)\\\specialrule{.12em}{.05em}{.05em}%
$Alternative^{ASPP+}$&22.99 M&85.02&91.51&96.41&98.17&88.83&94.00&\textbf{74.81}&\textbf{83.66}&86.26&91.83\\
$Alternative^{PPM}$&23.44 M&83.40&90.66&95.70&97.79&87.44&92.88&72.51&81.03&84.76&90.59\\
DeepPyram&23.62 M&\textbf{85.84}&\textbf{91.98}&\textbf{96.56}&\textbf{98.24}&\textbf{90.24}&\textbf{94.77}&74.40&83.30&\textbf{86.76}&\textbf{92.07}\\\specialrule{.12em}{.05em}{.05em}%
\end{tabular}
\label{tab:alternative}
\end{table*}
\begin{table*}[!t]
\renewcommand{\arraystretch}{0.9}
\caption{Impact of different backbones and combinations on the segmentation results (IoU\% and Dice\%) of DeepPyram.}
\label{tab:ablation}
\centering
\begin{tabular}{llccccccccccc}
\specialrule{.12em}{.05em}{.05em}%
&&&\multicolumn{2}{c}{Lens}&\multicolumn{2}{c}{Pupil}&\multicolumn{2}{c}{Cornea}&\multicolumn{2}{c}{Instrument}&\multicolumn{2}{c}{Overall}\\\cmidrule(lr){4-5}\cmidrule(lr){6-7}\cmidrule(lr){8-9}\cmidrule(lr){10-11}\cmidrule(lr){12-13}
&&Params&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)\\\specialrule{.12em}{.05em}{.05em}%
\multicolumn{1}{ c| }{\parbox[t]{1mm}{\multirow{4}{*}{\rotatebox[origin=c]{90}{Backbone}}}}&ResNet50&85.52 M&81.71&89.54&95.09&97.46&89.32&94.23&71.79&80.73&84.48&90.49\\
\multicolumn{1}{ c| }{}&ResNet34&25.77 M&82.77&90.22&95.06&97.45&88.68&93.84&72.58&80.99&84.77&90.62\\
\multicolumn{1}{ c| }{}&VGG19&28.93 M&85.33&91.66&96.36&98.14&88.77&93.93&\textbf{74.70}&\textbf{83.49}&86.29&91.80\\
\multicolumn{1}{ c| }{}&VGG16&23.62 M&\textbf{85.84}&\textbf{91.98}&\textbf{96.56}&\textbf{98.24}&\textbf{90.24}&\textbf{94.77}&74.40&83.30&\textbf{86.76}&\textbf{92.07}\\
\hline\hline
\multicolumn{2}{ c }{DeepPyram++}&28.48 M&84.83&91.54&96.30&98.11&89.48&94.34&74.64&83.34&86.31&91.83\\\specialrule{.12em}{.05em}{.05em}%
\end{tabular}
\label{tab:backbone}
\end{table*}
\begin{table*}[!t]
\renewcommand{\arraystretch}{0.9}
\caption{Impact of different super-resolution functions on the segmentation results (IoU\% and Dice\%) of DeepPyram.}
\label{tab:ablation}
\centering
\begin{tabular}{lccccccccccc}
\specialrule{.12em}{.05em}{.05em}%
&&\multicolumn{2}{c}{Lens}&\multicolumn{2}{c}{Pupil}&\multicolumn{2}{c}{Cornea}&\multicolumn{2}{c}{Instrument}&\multicolumn{2}{c}{Overall}\\\cmidrule(lr){3-4}\cmidrule(lr){5-6}\cmidrule(lr){7-8}\cmidrule(lr){9-10}\cmidrule(lr){11-12}
Upsampling&Params&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)&IoU(\%)&Dice(\%)\\\specialrule{.12em}{.05em}{.05em}%
Trans Conv&25.01 M&84.37&91.22&96.01&97.96&88.80&93.97&\textbf{75.16}&\textbf{83.71}&86.08&91.71\\
PixelShuffle&36.15 M&84.31&91.00&96.49&98.20&89.17&94.15&74.55&83.41&86.13&91.69\\
Bilinear&23.62 M&\textbf{85.84}&\textbf{91.98}&\textbf{96.56}&\textbf{98.24}&\textbf{90.24}&\textbf{94.77}&74.40&83.30&\textbf{86.76}&\textbf{92.07}\\\specialrule{.12em}{.05em}{.05em}%
\end{tabular}
\label{tab:upsampling}
\end{table*}
\subsection{Effect of Different Backbones and Nested Architecture}
We have evaluated the achievable segmentation accuracy using different backbone networks to decide which backbone performs the best, considering the trade-off between the number of trainable parameters and the Dice percentage. As listed in Table~\ref{tab:backbone}, the experimental results show that the higher-depth networks such as ResNet50 cannot improve the segmentation accuracy. In contrast, VGG16 with the fewest number of trainable parameters has achieved the best segmentation performance. Moreover, VGG19, having around 5.3M parameters more than VGG16, performs just slightly better than the baseline backbone in instrument segmentation. In Table~\ref{tab:backbone}, DeepPyram++ is the nested version of DeepPyram \footnote{UNet++ uses the encoder-decoder architecture of U-Net as baseline, and adds additional convolutional layers between different encoder's and decoder's layers to form a nested multi-depth architecture. In DeepPyram++, we replace the the encoder-decoder baseline of UNet++ (which is U-Net) with our proposed DeepPyram network to see if these additional layers and connections can improve the segmentation performance of DeepPyram.} (with the same connections as in UNet++). This nested architecture shows around a one percent drop in IoU percentage on average.
\subsection{Effect of Different Super-resolution Functions}
Table~\ref{tab:upsampling} compares the effect of three different super-resolution functions on the segmentation performance, including transposed convolution, Pixel-Shuffle~\cite{PixelShuffle}, and bilinear upsampling. Overall, the network with bilinear upsampling function with the fewest parameters has achieved the best performance among the networks with different upsampling functions. Besides, the results reveal that the bilinear upsampling function has the best performance in segmenting all relevant objects except for the instruments.
\begin{figure}[!tb]
\centering
\includegraphics[width=0.94\columnwidth]{pics/cc4.png}
\caption{Qualitative comparisons among DeepPyram and the rival approaches for the relevant objects in cataract surgery videos (the numbers denote the Dice(\%) coefficient for each detection). The representative images are selected from the test set.}
\label{fig:Vis}
\end{figure}
\section{Conclusion}
\label{sec: Conclusion}
In recent years, considerable attention has been devoted to computerized surgical workflow analysis for various applications such as action recognition, irregularity detection, objective skill assessment, and so forth. A reliable relevant-instance-segmentation approach is a prerequisite for a majority of these applications. In this paper, we have proposed a novel network architecture for semantic segmentation in cataract surgery videos. The proposed architecture takes advantage of three modules, namely ``Pyramid View Fusion", ``Deformable Pyramid Reception", and ``Pyramid Loss", to simultaneously deal with different challenges. These challenges include: (i) geometric transformations such as scale variation and deformability, (ii) blur degradation and blunt edges, and (iii) transparency, and texture and color variation. Experimental results have shown the effectiveness of the proposed network architecture (DeepPyram) in retrieving the object information in all mentioned situations. DeepPyram stands in the first position for cornea, pupil, lens, and instrument segmentation compared to all rival approaches. The proposed architecture can also be adopted for various other medical image segmentation and general semantic segmentation problems.
\balance
\bibliographystyle{IEEEtran}
| {'timestamp': '2021-09-14T02:16:05', 'yymm': '2109', 'arxiv_id': '2109.05352', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05352'} | arxiv |
\section*{Abstract}
We present a high-throughput optogenetic illumination system capable of simultaneous closed-loop light delivery to specified targets in populations of moving \textit{Caenorhabditis elegans}. The instrument addresses three technical challenges: it delivers targeted illumination to specified regions of the animal's body such as its head or tail; it automatically delivers stimuli triggered upon the animal's behavior; and it achieves high throughput by targeting many animals simultaneously. The instrument was used to optogenetically probe the animal's behavioral response to competing mechanosensory stimuli in the the anterior and posterior soft touch receptor neurons. Responses to more than $10^4$ stimulus events from a range of anterior-posterior intensity combinations were measured. The animal's probability of sprinting forward in response to a mechanosensory stimulus depended on both the anterior and posterior stimulation intensity, while the probability of reversing depended primarily on the posterior stimulation intensity. We also probed the animal's response to mechanosensory stimulation during the onset of turning, a relatively rare behavioral event, by delivering stimuli automatically when the animal began to turn. Using this closed-loop approach, over $10^3$ stimulus events were delivered during turning onset at a rate of 9.2 events per worm-hour, a greater than 25-fold increase in throughput compared to previous investigations. These measurements validate with greater statistical power previous findings that turning acts to gate mechanosensory evoked reversals. Compared to previous approaches, the current system offers targeted optogenetic stimulation to specific body regions or behaviors with many-fold increases in throughput to better constrain quantitative models of sensorimotor processing.
\section*{Author summary}
Targeting optogenetic stimulation to only specific body regions or during only specific behaviors is useful for dissecting the role of neurons and circuits underlying behavior in small transparent organisms like the nematode \textit{C. elegans}. Existing methods, however, tend to be very low-throughput, which can pose challenges for acquiring sufficiently large datasets to constrain quantitative models of neural computations. Here we describe a method to deliver targeted illumination to many animals simultaneously at high throughput. We use this method to probe mechanosensory processing in the worm and we validate previous experiments with many-fold higher throughput, larger sample sizes and greater statistical power.
\section*{Introduction}
How sensory signals are transformed into motor outputs is a fundamental question in systems neuroscience \cite{clark_mapping_2013}. Optogenetics \cite{boyden_history_2011, fenno_development_2011} coupled with automated measures of behavior \cite{datta_computational_2019, pereira_quantifying_2020} has emerged as a useful tool for probing sensorimotor processing, especially in small model organisms \cite{calhoun_quantifying_2017}. In optically transparent animals, such as \textit{C. elegans} and \textit{Drosophila}, such optogenetic manipulations can be performed non-invasively by illuminating an animal expressing light gated ion channels \cite{nagel_light_2005, leifer_optogenetics_2012}. Optogenetically perturbing neural activity and observing behavior has been widely used to study specific neural circuits, such as those involved in chemotaxis \cite{kocabas_controlling_2012, hernandez-nunez_reverse-correlation_2015, gepner_computations_2015, schulze_dynamical_2015} (reviewed for \textit{Drosophila} in \cite{calabrese_search_2015}), olfaction \cite{gordus_feedback_2015}, learning and memory \cite{claridge-chang_writing_2009, cho_parallel_2016}, and locomotion and escape \cite{wen_proprioceptive_2012, donnelly_monoaminergic_2013, kato_global_2015, wang_flexible_2020}, to name just a few examples. In \textit{Drosophila}, high throughput optogenetic delivery to behaving animals has been used to screen libraries of neural cell types and map out previously unknown relations between neurons and behavior \cite{cande_optogenetic_2018}.
Optogenetic investigations of neural circuits underlying behavior confront three technical challenges: the first is to deliver stimulation targeted only to the desired neuron or neurons; the second is to deliver the stimulus at the correct time in order to probe the circuit in a relevant state or behavioral context; and the third is to efficiently acquire enough observations of stimulus and response to draw meaningful conclusions. Existing methods each address some of these challenges, but not all three.
To stimulate only desired cells, the expression of optogenetic proteins is typically restricted to specific cells or cell-types \cite{boulin_reporter_2006, pfeiffer_tools_2008, jenett_gal4-driver_2012}. If cell-specific genetic drivers are not readily available, then genetic specificity can be complemented with optical targeting. Patterned light from a projector, for example, can be used to illuminate only a subset of the cells expressing the optogenetic protein \cite{guo_optical_2009, wyart_optogenetic_2009}. For targeting behaving animals, real-time processing is also needed to track the animal and dynamically update the illumination pattern based on its movements \cite{leifer_optogenetic_2011, stirman_real-time_2011, bath_flymad_2014, shipley_simultaneous_2014, porto_reverse-correlation_2017, dong_toward_2021}.
Closed-loop approaches are further needed to deliver a perturbation timed to a specific behavior. For example, delivering a perturbation triggered to the swing of an animal's head has informed our understanding of neural mechanisms underlying thermotaxis \cite{stephens_dimensionality_2008} and chemotaxis \cite{kocabas_controlling_2012}.
The use of closed-loop stimulation triggered on behavior in \textit{C. elegans} \cite{faumont_image-free_2011, dong_toward_2021}, \textit{Drosophila} \cite{musso_closed-loop_2019} and mammals \cite{adamantidis_optogenetic_2011, oconnor_neural_2013}
is part of a broader trend in systems neuroscience towards more efficient exploration of the vast space of possible neural perturbations \cite{clancy_volitional_2014, grosenick_closed-loop_2015}, especially during ethnologically relevant naturalistic behaviors \cite{krakauer_neuroscience_2017}.
Targeted and closed-loop illumination systems probe one animal at a time \cite{leifer_optogenetic_2011, stirman_high-throughput_2010, kocabas_controlling_2012, lee_compressed_2019, dong_toward_2021}, or at most two \cite{wu_optogenetic_2014}. This low throughput poses challenges for acquiring datasets with enough statistical power to constrain quantitative models of neural computation. To increase throughput, a separate body of work simultaneously measures behavior of populations of many animals in an arena, in order to amass thousands of animal-hours of recordings \cite{kerr_imaging_2006, branson_high-throughput_2009, gershow_controlling_2012, husson_keeping_2012}. Delivering spatially uniform optogenetic perturbations to such populations has helped constrain quantitative models of sensorimotor processing of chemotaxis and mechanosensation \cite{gepner_computations_2015, hernandez-nunez_reverse-correlation_2015, liu_temporal_2018}. Because the entire body of every animal is illuminated, this approach relies entirely on genetics for targeting. Recent work has used stochastic spatially varying illumination patterns in open-loop from a projector \cite{deangelis_spatiotemporally_2020} or cellphone \cite{meloni_controlling_2020} to probe the spatial dependence of optogenetic stimulation. But because these methods are open loop they cannot target stimulation specifically to any animal or body part. Instead they rely on after-the fact inspection of where their stimuli landed, decreasing throughput.
Here we demonstrate a closed-loop real-time targeting system for \textit{C. elegans} that tackles all three challenges: targeting, closed-loop triggering and throughput. The system delivers targeted illumination to specified parts of the animal's body, stimulus delivery can be be triggered automatically on behavior, and the system achieves a high throughput by tracking and independently delivering targeted stimuli to populations of animals simultaneously. We apply this system to the \textit{C. elegans} mechanosensory circuit \cite{chalfie_developmental_1981, chalfie_neural_1985} to characterize how competing stimuli in anterior and posterior mechanosensory neurons are integrated by downstream circuity. We also revisit our prior observation that turning behavior gates mechanosensory evoked reversals \cite{liu_temporal_2018}. We deliver closed-loop stimulation triggered to the onset of turning to obtain a dataset with two-orders-of-magnitude more stimulus-events compared to that investigation. We use these measurements to validate our initial observation with greater statistical power.
\section*{Results}
We developed a closed-loop targeted delivery system to illuminate specified regions in populations of \textit{C. elegans} expressing the optogenetic protein Chrimson as the animals crawled on agar in a 9 cm dish. The system used red light (peak 630 nm) from a custom color projector made of an optical engine (Anhua M5NP) driven by a separate control board, described in methods. Animal behavior was simultaneously recorded from a CMOS camera, Figure \ref{fig:instrument}a,b. Dark-field illumination from a ring of infrared LEDs (peak emission at 850 nm) was used to observe animal behavior because this avoided exciting Chrimson. Optical filters allowed the infrared illuminated behavior images to reach the camera, but blocked red or blue light coming from the projector. Green light from the projector was used to present visual timestamps and other spatiotemoporal calibration information to the camera. Custom real-time computer vision software monitored the pose and behavior of each animal and generated patterned illumination restricted to only specified regions of the animal, such as its head or tail, optionally triggered by the animal's behavior, Figure \ref{fig:instrument}c and \nameref{vid:arena}.
\begin{figure}[!htbp]
\begin{center}
\includegraphics[width=0.8\textwidth]{Figures_used/experimentaldesign.pdf}
\caption{{\bf Closed-loop targeted optogenetic delivery system.} a) Schematic of system. A projector simultaneously delivers patterned targeted optogenetic stimulation to multiple worms on an agar plate in real-time. b) Photograph of instrument. c) Image from experiment shows
animals expressing Chrimson in touch receptor neurons (AML470) as they crawl on agar. Corresponding video is shown in \nameref{vid:arena}. Tracked paths are shown in yellow. Green and white dots in the center relate to a visual time-stamping system and are excluded from analysis. Inset shows details of an animal receiving optogenetic stimulation targeted to its head and tail (0.5mm diameter stimuli). The two white circle in the inset show the targeted location of the stimulus. Red shading shows area where stimulus was delivered. }
\label{fig:instrument}
\end{center}
\end{figure}
\subsection*{Anterior and posterior mechanosensory response}
The mechanosensory response to anterior or posterior stimulation has been probed extensively by softly touching the animal with a hair \cite{chalfie_developmental_1981, chiba_developmental_1990, chalfie_assaying_2014}, tapping the substrate on which the animal crawls \cite{chalfie_developmental_1981, wicks_integration_1995},
automatically applying forces via micro-electromechanical force probes \cite{petzold_mems-based_2013, mazzochette_real_2013, mazzochette_tactile_2018} or applying forces via a microfluidic device \cite{mcclanahan_comparing_2017}. These approaches have identified dozens of genes related to touch sensation \cite{chalfie_neurosensory_2009}.
Mechanosensory responses have also been probed optogenetically by expressing light-gated ion channels in the six soft-touch mechanosenory neurons ALML, ALMR, AVM, PVM, PLML and PLMR \cite{nagel_light_2005}. Targeted illumination experiments showed that optogenetically stimulating posterior touch neurons PLML and PLMR was sufficient to elicit the animal to speed up or sprint and that stimulating anterior soft touch neurons (ALML, ALMR) or AVM was sufficient to induce the animal to move backwards in a reversal behavior \cite{leifer_optogenetic_2011, stirman_real-time_2011, porto_reverse-correlation_2017}. Those experiments were conducted one worm-at-a time, to accommodate the patterned illumination systems that were needed to restrict illumination to only a portion of the animal. Here we revisit these experiments, this time by probing a population of animals simultaneously to achieve higher sample sizes.
We delivered 1 s of red light illumination to the head, tail, or both, of transgenic animals expressing the light-gated ion channel Chrimson in the six soft touch mechanosensory neurons (500 um diameter stimulus region, 30 s inter-stimulus interval.) Multiple combinations of illumination intensities were used, but here only the 80 uW/mm$^2$ intensity stimuli are considered, Figure~\ref{fig:apresponse}. The system independently tracked or stimulated an average of $12\pm 10$ worms on a plate simultaneously (mean $\pm$ standard deviation), \nameref{tab:recordings}. Across four days, 95 plates were imaged using four identical instruments running in parallel, for a total of 31,761 stimulation-events across all stimulus intensity combinations. Of those, there were 7,125 stimulus-events with an illumination intensity of 80 uW/mm$^2$, at least 1,500 stimulus events each of the following conditions: head illumination, tail illumination, both, or neither. For comparison, \cite{leifer_optogenetic_2011} used 14 stimulus events, a two-order of magnitude difference in sample size.
\begin{figure}[htbp]
\begin{adjustwidth}{-2.25in}{0in}
\begin{center}
\includegraphics[width=1.37\textwidth]{Figures_used/anteriorposterior.pdf}
\caption{{\bf Stimulation of anterior mechanosensory neurons evokes reverse behavior; stimulation of posterior mechanosensory neurons evokes sprints.} Targeted stimulation is delivered to worms expressing Chrimson in their soft touch mechanosensory neurons (strain AML470). \textbf{a-d)} Representative velocity trace from single stimulus event. Dashed lines indicate timing of stimulation (1 s, 0.5mm diameter circular illumination pattern centered at the tip of the animal's head and/or tail, red light intensity of 80 uW/mm\textsuperscript{2}). \textbf{e-h)} 20 randomly sampled velocity traces for each stimulus condition are shown, sorted by mean velocity immediately after stimulation. Same as in Supplementary Videos S2-S5. Arrow indicates each representative trace shown in \textbf{a-d}. \textbf{i-l)} Probability density of velocities for each stimulus condition. Mean velocity is shown as black line. $n>1,500$ stimulus-events per condition. \textbf{m-p)} The fraction of animals inhabiting each of four velocity-defined behavioral states is shown for the time point 2 s before stimulation onset and immediately after stimulation. Cutoffs for behavior states are shown in \nameref{fig:velocitybehaviors}. P-values calculated using Wilcoxon rank-sum test. Error bars represents 95\% confidence intervals estimated using 1000 bootstraps.}
\label{fig:apresponse}
\end{center}
\end{adjustwidth}
\end{figure}
Consistent with prior reports, activating posterior mechanosensory neurons by delivering light to the tail resulted in an increase in sprints and an overall increase in average velocity (Figure \ref{fig:apresponse} and \nameref{vid:tail}). Similarly, activating anterior mechanosensory neurons by delivering light to the head resulted in an increase in reversal events and a decrease in average velocity (\nameref{vid:head}). Simultaneous stimulation to head and tail resulted an increase in reversals (\nameref{vid:headandtail}). Animals were classified as performing forward locomotion, pause, sprint or reversals, based on their velocity, \nameref{fig:velocitybehaviors}. The animal showed little response to control conditions in which no light was delivered (Figure \ref{fig:apresponse}a,e,i,m and \nameref{vid:control}), or in which the necessary co-factor all-trans retinal was withheld, \nameref{fig:anteriorposteriornoret}.
We also stimulated a different strain of animals nominally of the same genotype that we had used previously, AML67, \cite{liu_temporal_2018}. That strain had been constructed with a higher DNA plasmid concentration during microinjection (40 ng/ul for AML67, compared to 10 ng/ul for AML470 used above). The AML67 strain behaved the same on this instrument in response to simultaneous anterior and posterior stimulation as it had in \cite{liu_temporal_2018}. It also exhibited reversals in response to anterior illumination, as expected, but surprisingly, it did not exhibit sprint behaviors in response to posterior illumination as AML470 did (\nameref{fig:AML67anteriorposterior}). We suspect that some aspect resulting from the higher DNA plasmid injection concentration caused animals of this strain to behave differently during sprint behaviors.
\subsection*{Integration of conflicting anterior and posterior mechanosensory signals}
Mechanosensory neurons act as inputs to downstream interneurons and motor neurons that translate mechanosensory signals into a behavioral response \cite{chalfie_neural_1985, wicks_integration_1995, gray_circuit_2005, alkema_tyramine_2005, wang_flexible_2020}. A growing body of evidence suggests that downstream circuitry relies on the magnitude of signals in both the anterior and posterior mechanosensory neurons to determine the behavioral response. For example, a plate tap activates both anterior and posterior mechanosensory neurons and usually elicits a reversal response \cite{chiba_developmental_1990, wicks_integration_1995, swierczek_high-throughput_2011, liu_temporal_2018}. But the animal's response to tap can be biased towards one response or another by selectively killing specific touch neurons via laser ablation \cite{wicks_integration_1995}. For example, if ALMR alone is ablated, the animal is more balanced in its response and is just as likely to respond to a tap by reversing as it is by sprinting. If both ALML and ALMR are ablated the animal will then sprint the majority of the time \cite{wicks_integration_1995}.
Competing anterior-posterior optogenetic stimulation of the mechanosensory neurons also influences the animal's behavioral response. For example, a higher intensity optogenetic stimulus to the anterior touch neurons is needed to evoke a reversal when the posterior touch neurons are also stimulated, compared to when no posterior stimulus is present \cite{stirman_real-time_2011}.
To systematically characterize how anterior and posterior mechanosensory signals are integrated, we inspected the animal's probability of exhibiting reverse, forward, pause or sprint behavior in response to 25 different combinations of head and tail light intensity stimuli, Figure \ref{fig:heatmap}a-d. This data is a superset of that shown in Figure \ref{fig:apresponse}. Here 31,761 stimulus-events are shown, corresponding to all 25 different conditions. Behavior is defined such that the animal always occupies one of four states: reverse, pause, forward or sprint, so that for a given stimulus condition, the four probabilities necessarily sum to one, Figure \ref{fig:heatmap}e.
To explore the dependence of the probability of evoking a given behavior on the anterior and posterior stimulus intensity, we fit planes to the probability surfaces and computed the gradient of the resulting plane, Figure \ref{fig:heatmap},f. Fitting was performed using the method of least squares. The head and tail components of the gradient provide a succinct estimate of how the probability depends on either head or tail stimulus illumination intensity. For example, the probability of reversal depends strongly on the head stimulus intensity, as indicated by the large positive head component of the gradient. The probability of reversal also depends slightly on the tail stimulus intensity, consistent with \cite{stirman_real-time_2011}, but we note this dependence was small and that the 95\% confidence intervals of this dependence spanned the zero value. Of the four behaviors tested, only sprint behavior depended on both head and tail stimulation intensity such that the 95\% confidence intervals of both components of their gradient excluded the value zero. Sprints occurred with highest probability at the highest tail illumination intensity when head illumination was zero. As head illumination increased, the probability of a sprint rapidly decreased. One interpretation of these measurements is that head induced reversals are less likely to be counteracted by a tail stimulation, than tail induced sprints are to be counteracted by head stimulation.
\begin{figure}[htbp]
\begin{center}
\includegraphics[width=\textwidth]{Figures_used/heatmaps.pdf}
\caption{{\bf Behavioral response to competing stimulation of anterior and posterior mechanosensory neurons.} Various combinations of light intensity was delivered to the head and tail of worms expressing Chrimson in soft-touch mechanosensory neurons (strain AML470, n= 31,761 stimulus-events total, supserset of data shown in Figure \ref{fig:apresponse} ). a.) Probability of reverse b.) pause c.) forward and d.) sprint behaviors are shown individually e) and all together as pie charts. f.) The gradient of the plane-of-best-fit is shown as a vector for each behavior. Fitting was performed using methods of least squares. Error-bars are 95\% confidence intervals.}
\label{fig:heatmap}
\end{center}
\end{figure}
Taken together, we conclude that anterior and posterior mechanosensory signals are combined in a nontrivial way to determine the relative likelihood of different behavioral responses. For example, the animal's decision to reverse in response to mechanosensory stimulation is primarily dependent on signals in anterior mechanosensory neurons with only minimal dependence on posterior mechanosensory neurons. In contrast, the animal's decision to sprint is influenced more evenly by signals in both sets of neurons. This places constraints on any quantitative models of sensory integration performed by downstream circuitry.
\subsection*{Behavior-triggered stimulation increases throughput when investigating rare behaviors}
\textit{C. elegans'} response to mechanosensory stimulation depends on its behavioral context. The probability that a tap or optogenetic mechanosensory stimulation evokes a reversal is higher when the stimulus occurs as the animal moves forward compared to if the stimulus occurs when the animal is in the midst of a turn, suggesting that the nervous system gates mechanosensory evoked responses during turns \cite{liu_temporal_2018}. This was first observed in open-loop experiments in which the animal was stimulated irrespective of its behavior. Those experiments relied on identifying, after-the-fact, stimulus-events that arrived by chance during turning. Because turning events are brief and occur infrequently, it can be challenging to observe sufficient numbers of stimuli events delivered during turn onset using such an open-loop approach. For example, in that work only 15 optogenetic stimulus-events landed during turns.
The animal's spontaneous rate of turn initiation varies with the presence of food and other environmental conditions, but it has been reported to be approximately 0.03 Hz \cite{pierce-shimomura_fundamental_1999}.
To obtain higher efficiency and throughput at probing the animal's response to stimulation during turning, we delivered closed-loop stimulation automatically triggered on the onset of the animal's turning behavior.
Full-body red light illumination (1.5 mm diameter) was automatically delivered to animals expressing Chrimson in the soft-touch mechanosensory neurons (strain AML67, same as in \cite{liu_temporal_2018}) when the real-time tracking software detected that the animal entered a turn.
Turn onset was detected by monitoring the ellipse ratio of a binary image of the animal, as described in methods.
A refractory period of 30 s was imposed to prevent the same turning event from triggering multiple stimuli and served to set a minimum inter-stimulus interval.
47 plates of animals were recorded for 30 mins each over three days, and on average, the system simultaneously tracked or stimulated 44.5$\pm$20 worms on a plate at any given time, \nameref{tab:recordings}.
Three different stimulus intensities (0.5, 40 and 80 uW/mm$^2$) and three different stimulus durations (1, 3 and 5 s) were explored, totaling 39,477 turn-triggered stimuli events, of which on post-processing analysis 9,774 or 24.8\% passed our more stringent inclusion criteria for turn onset, worm validity and track stability, Table \ref{tab:enrichmentcomparison}.
To compare the closed- and open-loop approaches, 29 additional plates were stimulated in open loop over the same three day period.
\begin{figure}[!h]
\begin{center}
\includegraphics[width=\textwidth]{Figures_used/probability_of_reversal_AML67_AML470_final_version_2_pdf_format.pdf}
\caption{{\bf Probability of reversing in response to a mechanosensory stimulus is higher for stimuli that arrive during forward locomotion than for stimuli that arrive during turning.} Response to whole body optogenetic illumination of soft-touch mechanosensory neurons is shown for stimuli that arrive during either forward or turning behaviors for two strains of nominally identical genotypes, a) AML67 and b) AML470. Stimuli delivered during turns are from closed-loop optogenetic experiments, while stimuli delivered during forward locomotion are from open-loop experiments. 3 s of 80 uW/mm$^2$ illumination was delivered in the experiment condition. Only 0.5 uW/mm$^2$ was delivered for control condition. Error bars are 95 percent confidence interval calculated via 10,000 bootstraps. Z-test was used to calculate significance. *** indicates $p<0.001$. $p$ value for AML67 control group is 0.549. $p$ value for AML470 control group is 0.026. The number of stimulus events for each condition (from left-most bar to right-most bar) for AML67 are: 5,968, 1,551, 5,971, 1,448; for AML470: 2,501, 1,543, 2,676, 1,438. }
\label{fig:turning}
\end{center}
\end{figure}
We compared the probability of reversing in response to closed-loop stimuli delivered during turn onset against the probability of reversing in response to open-loop stimuli delivered during forward locomotion, Figure \ref{fig:turning}a. For this analysis we considered only stimuli of 3 s duration and either 80 uW/mm$^2$ or 0.5 uW/mm$^2$ (control) illumination intensity, of which 2,999 stimulus-events were delivered during turn onset. Consistent with previous reports, the animal was significantly more likely to initiate a reversal in response to stimuli delivered during forward locomotion than during turning. We repeated this experiment in strain AML470. That strain was also statistically significantly more likely to reverse in response to stimuli delivered during forward locomotion than during turning, although interestingly the effect was less striking in this strain compared to AML67 even though animals were overall more responsive. By using a high throughput closed-loop approach we confirmed previous findings with larger sample size ($10^3$ events compared to 15), and revealed subtle differences between two different strains with nominally identical genotypes.
Both throughput and efficiency are relevant for studying stimulus response during turning. Throughput refers to the number of stimuli delivered during turns per time. High throughput is needed to generate a large enough sample size in a reasonable enough amount time to draw statistically significant conclusions. Efficiency, or yield, refers to the fraction of delivered stimuli that were indeed delivered during turns. A high efficiency, or yield, is desired to avoid unwanted stimulation of the animal which can lead to unnecessary habituation.
We compared the throughput and efficiency of stimulating during turn onset with closed-loop stimulation to an open-loop approach on the same instrument using our same analysis pipeline and inclusion criteria, Table \ref{tab:enrichmentcomparison}. Again we considered only stimuli delivered within a small 0.33 s window corresponding to our definition of the onset of turns, and applied in post-processing the same stringent inclusion criteria to both open-loop and closed-loop stimuli. Closed loop-stimulation achieved a throughput of 9.2 turn-onset associated stimulation events per worm hour, an order of magnitude greater than the 0.5 events per worm hour in open loop stimulation. Crucially, closed-loop stimulation was also more efficient, achieving a yield of 24.8\%, nearly two orders of magnitude higher than the 0.4\% open-loop yield. We reach similar conclusions by comparing to previous open-loop optogenetic experiments from \cite{liu_temporal_2018} that had a longer inter-stimulus interval. Taken together, by delivering stimuli triggered on turns in a closed-loop fashion, we achieved higher throughput and efficiency than open-loop approaches.
\begin{table}[!ht]
\begin{adjustwidth}{-2.25in}{0in}
\centering
\caption{
{\bf Comparison of open- and closed-loop approaches for studying the animal's response to stimulation during a turn.} Whole-body illumination experiments using AML67 are shown. This is a superset of the data shown in Figure \ref{fig:turning} and includes a variety of stimulus intensities and stimulus durations. Compared to an open-loop approach, closed-loop turn-triggered stimulation provides higher throughput and higher yield. $^*$Note we report an effective throughput for experiments in \cite{liu_temporal_2018} to account for discrepencies in how different stimulus intensities are reported in that work (reported cumulative worm-hours include 6 different stimuli intensities, while only one intensity is considered in the reported number of stimulus events).}
\begin{tabular}{|l|l|l|l|l|l|l|l|l|}
\hline
Ref. & Experiment Type & Plates & \begin{tabular}[c]{@{}l@{}}Cum. Recording \\ Duration \\(Worm-hr)\end{tabular} & \begin{tabular}[c]{@{}l@{}}ISI \\(s)\end{tabular} & \begin{tabular}[c]{@{}l@{}}All Stim \\Events\end{tabular} & \begin{tabular}[c]{@{}l@{}}Turn-Associated \\ Stim Events\end{tabular}
& Yield
& \begin{tabular}[c]{@{}l@{}}Throughput \\ (Turn-Associated\\ Stim Events/\\Worm-hr)\end{tabular} \\ \thickhline
\begin{tabular}[c]{@{}l@{}}This\\work\end{tabular} & \begin{tabular}[c]{@{}l@{}}Closed-loop\\optogenetic\end{tabular} & 47 & 1,060 & $>30$ & 39,477 & 9,774 & 24.8\% & 9.2 \\ \hline
\begin{tabular}[c]{@{}l@{}}This\\work\end{tabular} & \begin{tabular}[c]{@{}l@{}}Open-loop\\optogenetic\end{tabular} & 29 & 633 & 30 & 70,699 & 299 & 0.4\% & 0.5
\\ \thickhline
\cite{liu_temporal_2018} & \begin{tabular}[c]{@{}l@{}}Open-loop\\optogenetic\end{tabular} & 12 & 260 & 60 & 2,487 & 15 & 0.6\% & 0.35$^*$
\\ \thickhline
\end{tabular}
\label{tab:enrichmentcomparison}
\end{adjustwidth}
\end{table}
\subsection*{Further characterization of the instrument}
We sought to further characterize the system to better understand its capabilities and limitations, Figure \ref{fig:characterization}. We quantified round-trip latency, prevalence of dropped frames, the spatial drift between camera and projector, and other key parameters that impact performance or resolution based on an analysis of the recordings in Figure \ref{fig:heatmap} and \nameref{fig:anteriorposteriornoret}.
\begin{figure}[!hptb]
\includegraphics[width=.95\textwidth]{Figures_used/characterization.pdf}
\caption{{\bf Characterization of key performance metrics.} Performance is evaluated for the set of experiments displayed in Figure \ref{fig:heatmap}. \textbf{a)} Round-trip latency is the elapsed time between camera exposure and stimulus delivery in response to that acquired image, as determined by visual time stamps drawn by the projector. \textbf{b)} The probability distribution of update times for tracking worms is plotted on a log axis. Over 96\% of frames do experience the full 30 Hz frame rate. Around 1 in 1000 frames have a tracking rate of less than 2 Hz. \textbf{c)} Histogram of camera-to-projector spatial drift between start and end of 30 min recording for each of 151 plates. \textbf{d)} Probability distribution of worm lengths for all tracks. Only worms with lengths 700 um and above are included for behavioral analysis. \textbf{e)} Probability distribution of the duration of tracks in the dataset. \textbf{f)} The probability distribution of the number of tracked worms at any given time. The mean and standard deviation for this set of recordings is $12\pm10$. Mean for other recordings is listed in \nameref{tab:recordings}. }
\label{fig:characterization}
\end{figure}
The round-trip latency between an animal's movement and a corresponding change in illumination output based on that movement is a key determinant of system performance. If the latency is too high compared to the animal's motion, the stimulus will arrive off-target. Round-trip latency is the cumulative delay from many steps including: exposing the camera, transferring camera images to memory, image processing, generating an illumination pattern, transferring the pattern to the projector and then ultimately adjusting micromirrors inside the projector to illuminate targeted regions of the animal. We constantly measured round-trip latency in real time by projecting a frame stamp visible to the camera using the projector's green channel (green and dots arranged in a circle visible in the center of Figure \ref{fig:instrument}c. They sometimes appear white in this visualization due to saturation.). The round-trip latency is the elapsed time between projecting a given frame stamp, and generating a new illumination pattern in response to the camera image containing that frame stamp. Median round-trip latency was 167 ms, Figure \ref{fig:characterization}a. For a worm moving at a typical center-of-mass velocity of order 200 um/s this corresponds to a roughly 50 um bound on spatial resolution. This is more than sufficient for the 500 um diameter head-tail illuminations used here. But the latency for this system is notably longer than single-worm targeted illumination systems (e.g. 29 ms for \cite{shipley_simultaneous_2014}) and suggests that the current system is unlikely to be well-suited to target the dorsal versus ventral side of the animal, for example.
When a real-time tracking systems fails to keep pace with a stream of incoming images it may drop the processing of frames, resulting in a lower effective frame rate. The system records the acquisition time stamp of each camera frame that was successfully processed by the real-time tracker. Later, the system detects any frames that were dropped by inspecting gaps in these time stamps. 96.5\% of the time the system achieved 30 Hz with no frame drops, Figure \ref{fig:characterization}c. 99.9\% of the time the system achieved a framerate above 2Hz, which we estimate is roughly the limit for resolving the head versus tail for a 1 mm worm moving at 200 um/s. When frames were dropped, the majority of time only one frame in a row was dropped (2.38\% of all frames).
Spatial resolution relies on the alignment between the projector and the camera, but this alignment can shift during the course of a recording due to projector heating or other effects. We quantified the drift in alignment between projector and camera by comparing a calibration pattern projected onto the agar in the green channel at the beginning and end of each 30 min plate recording. For the majority of recordings, spatial drift was small, corresponding to less than 25 um, or less than 5\% of the diameter of the head-tail stimulus, Figure \ref{fig:characterization}c. Finally, we also report the number of simultaneously tracked worms, the duration for which they were tracked and the worms' size for comparison, Figure \ref{fig:characterization}d-f.
\section*{Discussion and Conclusions}
The approach here dramatically improves throughput in two ways compared to previous methods. First, this work extends targeted illumination to many worms in parallel, providing an order of magnitude higher throughput per plate compared to previous single-worm methods capable of delivering optogenetic illumination targeted to different regions of the body \cite{leifer_optogenetic_2011, stirman_real-time_2011, kocabas_controlling_2012}. Second, the method enables automatic stimulus delivery triggered on a behavior.
For studying stimulus response during rare behaviors, like turns, this closed-loop approach provides higher throughput and efficiency compared to previous open-loop methods \cite{liu_temporal_2018}.
To achieve simultaneous independent targeting of many animals and tracking of behavior, we developed new algorithms, such as real-time centerline tracking algorithms, improved existing ones using parallelization and also leveraged advances in computing power. For example, we took advantage of the availability of powerful fast many-core CPUs, GPUs, multi-terabyte solid-state drives, and low-latency USB3 cameras.
To attain such high-throughput, the system also sacrifices some spatial resolution compared to previous single-worm approaches \cite{leifer_optogenetic_2011, stirman_high-throughput_2010, kocabas_controlling_2012}. For example, the round-trip latency and observed drift in calibration places a roughly 100 um floor on our spatial resolution, which makes the system ill-suited for resolving individual neurons located close to one another. Nonetheless, this resolution is more than sufficient to selectively illuminate the head or tail of adult \textit{C. elegans}, which allows for new types investigations. For example, we used the instrument to systematically probe anterior-posterior integration of mechanosensory signals for a range of competing stimuli intensities, delivering over $3.1\times10^4$ stimulus-events in total. The sample size needed for such an experiment would be impractical with single-worm targeted illumination methods. And current genetic labeling approaches preclude this experiment from being conducted with non-targeted whole field-of-view illumination setups, such as in \cite{liu_temporal_2018}.
Our measurements suggest that the worms' behavioral response to competing mechanosensory stimuli depends on integrating anterior and posterior mechanosensory signals in a non-trivial way. The probability of a sprint is influenced roughly evenly by signals in both anterior and posterior mechanosensory neurons, while the probability of reversing is primarily influenced by the anterior mechanosensory neurons. Overall, head stimuli that would induce reversals are less likely to be counteracted by a tail stimulation, than tail induced sprints are to be counteracted by head stimulation. The \textit{C. elegans} response to anterior mechanosensory stimuli is an important part of the escape response \cite{pirri_neuroethology_2012} and helps the animal avoid predation by nematophagous fungi \cite{maguire_c._2011}. It is possible that the relative difficulty in disrupting head induced reversals compared to sprints reflects the relative importance of the role of the reversal in this escape behavior.
Here we used red illumination to excite Chrimson, but we note that the system can be trivially extended to independently deliver simultaneous red and blue light illumination \cite{stirman_real-time_2011}, for example to independently activate two different opsins such as the excitatory red opsin Chrimson and the inhibitory blue opsin gtACR2 \cite{govorunova_natural_2015, vierock_bipoles_2021}. Like other targeted illumination systems before it \cite{leifer_optogenetic_2011, stirman_real-time_2011}, this system is not capable of targeting regions within the body when the animal touches itself, as often occurs during turning, or when coiling \cite{croll_behavoural_1975, croll_components_1975}. This still permits probing the animal's response to mechanosensory stimulation during turns because we were interested in whole-animal stimulation for those specific experiments, rather than targeting the head or tail. We note that our post-processing analysis does resolve the animal's centerline even during self-touching \cite{liu_temporal_2018}, but that method is not currently suitable for real-time processing.
We investigated the response to stimulus during turning by delivering closed-loop stimuli automatically triggered on the turn.
We achieved a more than 25-fold increase in throughput compared to a previous investigation \cite{liu_temporal_2018} and similar order-of-magnitude increase compared to an open-loop approach implemented on the same instrument with the same analysis pipeline and inclusion criteria. The closed-loop functionality can be easily triggered on sprints or pauses or, in principal, even on extended motifs like an escape response. This high-throughput triggering capability may be useful for searching for long-lived behavior states, probing the hierarchical organizations of behavior \cite{kaplan_nested_2020}, or exploring other instances of context-dependent sensory processing \cite{liu_temporal_2018}.
\section*{Materials and methods}
\subsection*{Strains}
Two strains were used in this work, AML67 and AML470, Table \ref{table:methods:strains}. A list of strains cross-referenced by figure is shown in \nameref{tab:recordings}. Both strains expressed the light gated ion channel Chrimson and a fluorescent reporter mCherry under the control of a \textit{mec-4} promoter, and differed mainly by the concentration of the Chrimson-containing plasmid used for injection. AML67 was injected with 40 ng/ul of the Chrimson-containing plasmid while AML470 was injected with 10 ng/ul. Specifically, to generate AML470, a plasmid mix containing 10 ng/ul of pAL::pmec-4::Chrimson::SL2::mCherry::unc-54 (RRID:Addgene\_107745) and 100 ng/ul of pCFJ68 unc-122::GFP (RRID:Addgene\_19325) were injected into CZ20310 \cite{noma_rapid_2018} and then integrated via UV irradiation. Experiments were conducted with AML470 strains prior to outcrossing.
\begin{table}
\begin{adjustwidth}{-2.35in}{0in}
\centering
\caption{
{\bf Strains used.}}
\begin{tabular}{|c|p{4.5cm}|p{7.3cm}|p{2.9cm}|p{1cm}|}
\hline
Strain & RRID & Genotype & Notes & Ref \\
\hline
AML67 & RRID:WB-STRAIN:WBStrain00000193 &wtfIs46[pmec-4::Chrimson::SL2::mCherry::unc-54 40ng/ul] & 40 ng Chrimson injection & \cite{liu_temporal_2018}\\ \hline
AML470 & & juSi164 unc-119(ed3) III; wtfIs458 [mec-4::Chrimson4.2::SL2::mCherry::unc-54 10 ng/ul + unc-122::GFP 100 ng/ul] & 10 ng Chrimson injection & This work\\ \hline
\end{tabular}
\label{table:methods:strains}
\end{adjustwidth}
\end{table}
\subsection*{Instrument}
\subsubsection*{Hardware}
A CMOS camera (acA4112-30um, Basler) captured images of worms crawling on a 9 cm diameter agar plate at 30 frames per second, illuminated by a ring of 850 nm infrared LEDs, all housed in a custom cabinet made of 1 inch aluminum extrusions. To illuminate the worm, a custom projector was built by combining a commercial DMD-based light engine (Anhua M5NP, containing a Texas Instruments DLP4500) with a Texas Instrument evaluation control board (DLPLCR4500EVM). The light engine contained red, green and blue LEDs with peaks at 630 nm, 540 nm and 460 nm, respectively (\nameref{fig:spectra}). The projector cycles sequentially through patterns illuminated by red, green and then blue illumination once per cycle at up to 60 Hz and further modulates the perceived illumination intensity for each pixel within each color by fluttering individual mirrors with varying duty-cycles at 2.8 kHz. The system produced a small image (9 cm wide) from a short distance away (15 cm) such that a single element of the DMD projects light onto a roughly 85 um$^2$ region of agar.
A light engine driven by a separate evaluation board was chosen instead of an all-in-one off-the-shelf projector because the API provided by the evaluation board allowed for more precise timing and control of all aspects of the illumination, including the relative exposure duration and bit-depth of the red, green and blue channels. For example, in this work only the red and green channels are used. So for these experiments the projector was programmed to update at 30 Hz and display a green pattern for 235 us (1 bit depth), followed by a red pattern for 33,098 us (8 bit depth) during each 30 Hz cycle. This choice of timing and bit depth maximizes the range of average intensities available in the red channel for optogenetic stimulation, while restricting the green channel to binary images sufficient for calibration. The choice of 30 Hz is optimized for the 30 Hz camera framerate. To avoid aliasing, camera acquisition was synchronized to the projector by wiring the camera trigger input to the green LED on the light engine. If both red and blue channels are to be used for optogenetic stimulation, a different set of timing parameters can be used.
It is desired that the animal perceives the illumination as continuous and not flickering. The inactivation time constant for Chrimson is 21.4$\pm$1.1 ms \cite{klapoetke_independent_2014}. As configured, the 80 uW/mm$^2$ illumination intensity generates a gap in red light illumination of only 235 us from cycle to cycle, well below Chrimson's inactivation time constant. Therefore the animal will perceive the illumination as continuous. At 20 uW/mm$^2$ the gap in illumination due to the temporal modulation of the micromirrors is nearly 25 ms, similar to the inactivation timescale. Intensities lower than this may be perceived as flickering. The only lower intensities used in this work were 0.5 uW/mm$^2$, for certain control experiments. We were reassured to observe no obvious behavioral response of any kind to 0.5 uW/mm$^2$ illumination, suggesting that in this case the animal perceived no stimulus at all.
A set of bandpass and longpass filters was used in front of the camera to block red and blue light from the projector while passing green light for calibration and IR light for behavior imaging. These were, in series, a 538/40 nm bandpass filter (Semrock, FF01-538/40-35-D), a 550 nm longpass filter (Schott, OG-550), and two color photography filters (Roscolux \#318). A 16 mm c-mount lens (Fujinon, CF16ZA-1S) and spacer (CMSP200, Thorlabs) was used to form an image.
Barrel distortion is corrected in software.
A PC with a 3.7 GHz CPU (AMD 3970x) containing 32 cores and a GPU (Quadro P620, Nvidia) controlled the instrument and performed all real-time processing. A 6 TB PCIe solid-state drive provided fast writeable storage on which to store high resolution video streams in real-time, Table \ref{tab:bandwidth}. Images from the camera arrived via USB-C. Drawings were sent to the projector's evaluation board via HDMI.
A complete parts list is provided in \nameref{tab:partslist}, and additional details are described in \cite{liu_c_2020}.
\begin{table}[!ht]
\begin{adjustwidth}{-2.25in}{0in}
\centering
\caption{
{\bf Input and output video streams used or generated by the instrument.} Bandwdith is reported in Megabytes per second of the recording.}
\begin{tabular}{|l|l|l|l|}
\hline
Video Stream & Resolution & Format & Bandwidth (MB/s) \\ \thickhline
Camera video in (real-time) & 2048x1504 @ 30Hz & 8-bit monochrome via USB-C & 85.3
\\ \hline
Camera video saved (real-time) & 2048x1504 @ 30Hz & 8-bit monochrome TIFF & 85.3
\\ \hline
Camera video compressed (post-processing) & 2048x1504 @ 30Hz & 8-bit monochrome HEVC & 0.102
\\ \hline
Projector video out (real-time) & 912x1140 @ 60Hz & 8-bit RGB* via HDMI & 178 \\ \hline
Projector Video Saved (real-time) & 912x570 @ 30Hz & 8-bit RGB TIFF & 44.5 \\ \hline
\begin{tabular}[c]{@{}l@{}}Projector video aligned to camera\\frame of reference (post-processing)\end{tabular} & 2048x1504 @ 30Hz & 8-bit RGB PNG & 0.353
\\ \hline
\end{tabular}
\begin{flushleft} *The green channel is actually displayed as binary since it is only used for calibration. Single color experiments in red or blue can achieve 8-bit color resolution but runs at 30 Hz. For experiments with both red and blue, the projector can only simultaneously decode 7-bits of color resolution for each channel but it runs at 60 Hz.
\end{flushleft}
\label{tab:bandwidth}
\end{adjustwidth}
\end{table}
\subsubsection*{Real-time software}
Custom LabVIEW software was written to perform all real-time image processing and to control all hardware. Software is available at \url{https://github.com/leiferlab/liu-closed-loop-code}. The LabVIEW software is described in detail in \cite{liu_c_2020}. The software is composed of many modules, summarized in Figure \ref{fig:assaymodules}. These modules run separately and often asynchronously to acquire images from the camera, track worms, draw new stimuli, communicate with the projector and update a GUI shown in Figure \ref{fig:GUI}. The software was designed with parallel processing in mind and contains many parallel loops that run independently to take advantage of the multiple cores.
\begin{figure}[!htbp]
\begin{center}
\includegraphics[width=\textwidth]{Figures_used/realtime.pdf}
\caption{{\bf Selected software modules involved in closed-loop light stimulation.} Selected software modules are shown that run synchronously or asynchronously. Note the image processing depiction is illustrative and for a small cropped portion of the actual field of view. }
\label{fig:assaymodules}
\end{center}
\end{figure}
\begin{figure}[!htbp]
\begin{center}
\includegraphics[width=1\textwidth]{Figures_used/GUIscreenshot.png}
\end{center}
\caption{{\bf Graphical user interface (GUI)} shown here during an experiment. }
\label{fig:GUI}
\end{figure}
Camera images and drawn projector images are both saved to disk in real-time as TIFF images, Table \ref{tab:bandwidth}. In post-processing, they are compressed and converted to H.265 HEVC videos using the GPU.
A critical task performed by the software is to track each animals' centerline in real-time so that targeting can be delivered to different regions of the animal. Many centerline algorithms have been developed \cite{husson_keeping_2012}, including some that can operate on a single animal in real-time, e.g. \cite{leifer_optogenetic_2011}. The existing algorithms we tested were too slow to run simultaneously on the many animals needed here. Instead we developed a two pass recursive algorithm that is fast and computationally efficient, Figure \ref{fig:centerline}. An image of the worm is binarized and then skeletonized through morphological thinning. Then, in the first pass, the skeleton is traversed recursively to segment all of the distinct branch points in the skeleton. Then in a second pass, the path of the centerline is found by recursively traversing all sets of contiguous segments to identify the longest contiguous path. The longest contiguous path is resampled to 20 points and reported as the centerline. Further details are described in \cite{liu_c_2020}.
\begin{figure}[!htbp]
\begin{center}
\includegraphics[width=1\textwidth]{Figures_used/multimodal_centerline.png}
\end{center}
\caption{{\bf Illustration of the fast centerline finding algorithm.} The algorithm proceeds in order from left to right. A binary image of the worm is taken as input. A skeleton is then generated through morphological thinning. The first recursive algorithm starts from an endpoint of the skeleton and breaks it down into segments at each branch point. The second recursive algorithm uses these segments to find the longest contiguous segment from one end point to another end point.}
\label{fig:centerline}
\end{figure}
From the animal's centerline, other key attributes are calculated in real-time, including the animal's velocity and eccentricity which are used to determine whether the animal is turning. The software also stitches together images of worms into tracks, using methods adopted from the Parallel Worm Tracker\cite{ramot_parallel_2008} and described in \cite{liu_temporal_2018} and \cite{liu_c_2020}. To identify the head or tail in real-time, the software assumes that the worm cannot go backwards for more than 10 s, and so the direction of motion for greater than 10 s indicates the orientation of the head.
\subsubsection*{Registration and Calibration}
Te generate a map between locations in a camera image and locations on the agar, images are acquired of a calibration grid of dots. A transformation is then generated that accounts for barrel distortion and other optical aberrations.
To generate a map between the projector mirrors and the image viewed by the camera, the projector draws a spatial calibration pattern in the green channel before each recording. This projector-generated pattern is segmented in software and automatically creates a mapping between projector and camera image. The calibration is also performed at the end of each recording to quantify any drift that occurred between projector and camera during the course of the recording.
To provide temporal calibration and to quantify round-trip latency, a visual frame stamp is projected in the green channel for every frame.
The time-stamp appears as a sequence of dots arranged in a circle, each dot representing one binary digit. Any worms inside the circle are all excluded from analysis. Illumination intensity measurements were taken using a powermeter.
\subsubsection*{Behavior Analysis}
After images have been compressed in HEVC format, data is sent to Princeton University's high performance computing cluster, Della, for post-processing and data analysis. Custom MATLAB scripts based on \cite{liu_temporal_2018} inspect and classify animal behavior. For example, the real-time centerline algorithm fails when the animal touches itself. Therefore, when analyzing behavior after the fact, a slower centerline algorithm \cite{deng_efficient_2013}, as implemented in \cite{liu_temporal_2018}, is run to track the centerline even through self-touches.
The animal's velocity is smoothed with 1 s boxcar window and used to define behavior states for the experiments in Figures \ref{fig:apresponse} and \ref{fig:heatmap} according to equal area cutoffs shown in \nameref{fig:velocitybehaviors}.
The turning investigation in Figure \ref{fig:turning} uses the behavior mapping algorithms from \cite{liu_temporal_2018} which in turn are based on an approach first described in \cite{berman_mapping_2014}. The mapping approach classifies the behavior state that the animal occupies at each instance in time. In many instances the classification system decides that the worm is not in a stereotyped behavior, and therefore it declines to classify the behavior. We inspect even the unclassfied behaviors and classify the animal as turning if a) the behavior mapping algorithm from \cite{liu_temporal_2018} defines it as a turn, or b) if the behavior mapping algorith classifies it as a non-stereotyped behavior that has an eccentricity ratio less than 3.6. In this way we rescue a number of instances of turning that had been overlooked. For turning experiments in Figure \ref{fig:turning} additional criteria are also used to determine whether a stimulus landed during the turning onset, and to classify the animal's behavioral response, as described below.
\subsection*{Nematode handling}
Worm preparation was similar to that in \cite{liu_temporal_2018}. To obtain day 2 adults, animals were bleached four days prior to experiment. To obtain day 1 adults, animals were bleached three days prior to experiments. For optogenetic experiments, bleached worms were placed on plates seeded with 1 ml of 0.5 mM all-trans-retinal (ATR) mixed with OP50 \textit{E. coli}. Off-retinal control plates lacked ATR. Animals were grown in the dark at 20 C.
To harvest worms for high-throughput experiments, roughly 100 to 200 worms were cut from agar, washed in M9 and then spun-down in a 1.5 ml micro centrifuge tube. For imaging, four small aliquots of worms in M9 were deposited as droplets on the cardinal directions at the edge of the plate. Each droplet typically contained at least 10 worms for a total of approximately 30-50 worms. The droplet was then dried with a tissue.
\subsection*{Anterior vs posterior stimulation experiments}
Day 2 adults were used. Every 30 seconds, each tracked animal was given a 500 um diameter red light stimulation to either the head, tail, or both simultaneously. The illumination spot was centered on the tip of the head or tail respectively. The stimulus intensity was randomly drawn independently for the head and the tail from the set of 0, 20, 40, 60 and 80 uW/mm\textsuperscript{2} intensities.
To calculate the probability of a reversal response for Figure \ref{fig:heatmap}, we first record the animal's behavior 1 second prior to the stimulation to account for any effect the 1 second smoothing window may have on the annotation. Then, for a total of 2 seconds, one second before stimulation and one second during stimulation, we determine if the animal changes behavioral states. The behavioral response is determined to be the most extreme response the animal has in this 2 second time window as compared to the animal's starting behavior, and it needs to be sustained for more than 0.5 seconds. Note this response may not be the first behavior the animal transitions to, because a paused animal neesd to go through the forward behavior state before it can enter sprint.
\subsection*{Mechanosensory evoked response during turning vs forward locomotion }
\subsubsection*{Open-loop whole-body illumination experiments}
Day 1 adults were used. Every 30 s, each tracked worm received a 3 s duration 1.5 mm diameter red light illumination spot centered on its body with illumination intensity randomly selected to be either 80 uW/mm\textsuperscript{2} or 0.5 uW/mm\textsuperscript{2}. For a subset of plates additional illumination intensities were also used, and/or 1 s and 5 s stimulus duration were also used, but those stimulus events were all excluded from analysis in Figure \ref{fig:turning}. But stimuli of all intensities and duration were counted for the purposes of throughput calculations in Table \ref{tab:enrichmentcomparison}, so long as they passed our further criteria for turning onset, worm validity and track stability described in the next section.
Open-loop stimulation was used to study response to stimulation of animals during forward locomotion. Therefore only stimulus events that landed when the animal exhibited forward locomotion were included. Forward locomotion was defined primarily by the behavior mapping algorithm, but we also required agreement with our turning onset-detection algorithm, described below.
During post-processing, the following worm stimulation events were excluded from analysis based on track stability and worm validity: Instances in which tracking was lost or the worm exited the field of view 17 seconds before or during the stimulus; instances when the worm collided with another worm before, during, or immediately after stimulation; or stimulations to worms that were stationary, exceedingly fat, oddly shaped, or were shorter than expected (less than 550 um for these experiments).
\subsubsection*{Closed-loop turn-triggered whole-body illumination experiments}
Whenever the real-time software detected that a tracked worm exhibited the onset of a turn, it delivered 3 s of 1.5mm diameter red light illumination centered on the worm with an intensity randomly selected to be either 80 uW/mm\textsuperscript{2} or 0.5 uW/mm\textsuperscript{2}. A refractory period was imposed to prevent the same animal from being stimulated twice in less than a 30 s interval.
Stimulus delivery was triggered by real-time detection of turning onset by triggering on instances when the ellipsoid ratio of the binarized image of the worm crossed below 3.5. During post-processing, a more stringent set of criteria was applied. To be considered a turn onset, the stimulus was required to land also when the improved behavior mapping pipeline considered the animal to be in a turn. We also required that the stimuli did indeed fall within a 0.33 s window immediately following the ellipse ratio crossing, to account for possible real-time processing errors. We had also observed some instances when tail bends during reversals were incorrectly categorized as turning onset events. We therefore required that turn onsets occur only when the velocity was above -0.05 mm/s in a 0.15 s time window prior to stimulus onset.
Finally, the same exclusion criteria regarding worm validity and tracking stability from the open-loop whole-body illumination experiments were also applied.
\subsubsection*{Calculating probability of reversals}
To be classified as exhibiting a reversal in response to a stimulation for experiments shown in Figure \ref{fig:turning}, the animal's velocity must decrease below -0.1 mm/s at least once during the 3 s window in which the stimulus is delivered.
\subsection*{Source code}
All software are available at \url{https://github.com/leiferlab/liu-closed-loop-code} including: real-time instrument control software written in LABVIEW, post-processing behavior analysis written in MATLAB, and experiment-specific analysis scripts written in MATLAB.
\subsection*{Datasets}
Datasets for all recordings in this work (\nameref{tab:recordings}) are being deposited in the IEEE DataPorts public repository, DOI:10.21227/t6b0-bc36, \url{https://dx.doi.org/10.21227/t6b0-bc36}.
\newpage
\section*{Supplementary Figures, Tables and Videos}
\paragraph*{Supplementary Figure S1}
\label{fig:velocitybehaviors}
\begin{center}
\includegraphics[width=0.8\textwidth]{Figures_used/AML470_5stimexps_velocity_thesholds_hires.png}
\end{center}
{\bf Classifying behavior by velocity distribution.} For the analyses performed in Figures \ref{fig:apresponse} and \ref{fig:heatmap}, we classify animal behavior to be one of four states using the velocity distribution aggregated from both (+)ATR and (-)ATR head/tail stimulation experiments conducted with AML470. The ``Reverse'' state has a velocity of less than 0. The three states with positive velocity are divided so they are equally likely. The slowest state is ``Pause.'' The middle state is ``Forward,''and the fastest state is "Sprint".
\newpage
\paragraph*{Supplementary Figure S2}
\label{fig:anteriorposteriornoret}
\begin{adjustwidth}{-2.25in}{0in}
\begin{center}
\includegraphics[width=1.45\textwidth]{Figures_used/anteriorposterior_noret.pdf}
\end{center}
{\bf Animals that lack the necessary co-factor all-trans-retinal do not exhibit a behavioral response. } AML470 worms grown (-)ATR. The fraction of animals belonging to behavioral states segmented by velocity before and after each stimulus condition: \textbf{a} no stimulus, \textbf{b} tail only stimulus, \textbf{c} head only stimulus, and \textbf{d} combined head and tail stimulus. The before time point is taken 2 seconds prior to the stimulus onset, and the after time point is taken at the end of the 1 second stimulation. Significance between before and after is determined by p-values calculated using Wilcoxon rank-sum test. The significance test does not correct for multiple hypothesis testing. Error bars represents 95\% confidence intervals estimated using 1000 bootstraps.
\end{adjustwidth}
\newpage
\paragraph*{Supplementary Figure S3}
\begin{adjustwidth}{-2.25in}{0in}
\label{fig:AML67anteriorposterior}
\begin{center}
\includegraphics[width=1.4\textwidth]{Figures_used/anteriorposterior_AML67.pdf}
\end{center}
{\bf Strain AML67 exhibits unexpected response to optogenetic stimulation of posterior mechanosensory neurons}. Anterior targeted stimuli evoke reversals but posterior stimuli unexpectedly reduce sprints for worms expressing Chrimson in the soft touch mechanosensory neurons in this strain. Strain AML67 grown on retinal (+)ATR. \textbf{a-d)} Select single animal velocity in response to no stimulation, tail only stimulation, head only stimulation, and combined head and tail stimulation respectively. Dotted lines denote the onset and termination of stimulation. The stimulus is a 1 second long 0.5mm diameter circular dot centered at the tip of the animal's head and/or tail with a red intensity of 80 uW/mm\textsuperscript{2}. \textbf{e-h)} Randomly selected velocity traces for 20 animals in each stimulus condition are color coded red/blue. The traces are sorted by the mean velocity during the 1 second stimulation window. The arrow indicates the selected velocity trace shown in the corresponding column in \textbf{a-d}. \textbf{i-l)} Probability density of all tracked velocities for each stimulus condition. The mean velocity at any given time is overlaid as the black line. The number of stimuli events for this condition are shown below. \textbf{m-p)} The fraction of animals belonging to behavioral states segmented by velocity before and after each stimulus condition. The before time point is taken 2 seconds prior to the stimulus onset, and the after time point is taken at the end of the 1 second stimulation. Significance between before and after is determined by p-values calculated using Wilcoxon rank-sum test. Error bars represents 95\% confidence intervals estimated using 1000 bootstraps.
\end{adjustwidth}
\newpage
\paragraph*{Supplementary Figure S4}
\label{fig:spectra}
\includegraphics[width=\linewidth]{Figures_used/spectra_panel.pdf}
{\bf Spectral properties of light sources.} Emission spectra are shown for the the projector's a) red b) green and c) blue channels and d) the IR LED ring.
\newpage
\paragraph*{Supplementary Table S1.}
{\bf List of all recordings in this work.}
\bigskip
\begin{adjustwidth}{-2.25in}{0in}
\label{tab:recordings}
\begin{center}
\includegraphics[width=1.4\textwidth]{Figures_used/stable1_datasets.pdf}
\end{center}
\end{adjustwidth}
\newpage
\paragraph*{Supplementary Table 2.}
\label{tab:partslist}
{\bf Hardware Partslist.} Hardware parts list for the instrument. The frame is made from 1 inch aluminum extrusions and are not included. The unit count is for each instrument.
\setlength\LTleft{-2.25in}
\setlength\LTright{0in}
\begin{longtable}{lllll}
\hline
\multicolumn{1}{|l|}{Manufacturer} &
\multicolumn{1}{l|}{Item} &
\multicolumn{1}{l|}{Model/Parts No.} &
\multicolumn{1}{l|}{Units} &
\multicolumn{1}{l|}{Notes} \\ \thickhline
\endfirsthead
%
\endhead
\multicolumn{1}{|l|}{Camera} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Basler} &
\multicolumn{1}{l|}{Camera} &
\multicolumn{1}{l|}{acA4112-30um} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Basler} &
\multicolumn{1}{l|}{USB Cable} &
\multicolumn{1}{l|}{Basler 2000035994} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Basler} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}¼-20 Mounting Adapter \\for Basler ace L USB 3.0\end{tabular}} &
\multicolumn{1}{l|}{Basler 2200000191} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Basler} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Digital I/O and power cable, \\6-pin Hirose (Female), 10 m\end{tabular}} &
\multicolumn{1}{l|}{Basler 2000029411} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
&
&
&
&
\\ \hline
\multicolumn{1}{|l|}{Lens And Filter} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Fujinon} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}CF16ZA-1S 16mm f/1.80\\ Machine Vision C-Mount Lens\end{tabular}} &
\multicolumn{1}{l|}{CF16ZA-1S} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Edmund Optics} &
\multicolumn{1}{l|}{M37.5 x 0.5 Empty Filter Mount} &
\multicolumn{1}{l|}{67-684} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Thorlabs} &
\multicolumn{1}{l|}{C-Mount Spacer Ring, 2.00 mm Thick} &
\multicolumn{1}{l|}{CMSP200} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Semrock} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}538/40 nm BrightLine® single-band \\bandpass filter, 35mm unmounted\end{tabular}} &
\multicolumn{1}{l|}{FF01-538/40-35-D} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Also allows \\in IR \textgreater 800nm\end{tabular}} \\ \hline
\multicolumn{1}{|l|}{SCHOTT} &
\multicolumn{1}{l|}{OG-550, 50.8mm Sq., Longpass Filter} &
\multicolumn{1}{l|}{OG-550} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Roscolux} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}3" x 5" 200 filters, Color Filter \\Booklet, \#318Mayan Sun\end{tabular}} &
\multicolumn{1}{l|}{39-418} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}35 mm circles\\ are cut out. \\2 filters are \\used per lens.\end{tabular}} \\ \hline
&
&
&
&
\\ \hline
\multicolumn{1}{|l|}{Projector} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Anhua} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}M5NP Structured light \\projector engine for 3D Measuring\end{tabular}} &
\multicolumn{1}{l|}{M5NP} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Wintech} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}DLP4500 Projection DLP Reference \\Design Evaluation Board \\without optical module\end{tabular}} &
\multicolumn{1}{l|}{LCR4500 VIS KIT} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Kaga Electronics USA} &
\multicolumn{1}{l|}{AC/DC DESKTOP ADAPTER 12V 84W} &
\multicolumn{1}{l|}{KTPS90-1207} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Tripp Lite} &
\multicolumn{1}{l|}{6' USB A TO MINI-B CABLE M/M} &
\multicolumn{1}{l|}{UR030-006} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Tripp Lite} &
\multicolumn{1}{l|}{HDMI TO MINI HDMI CABLE 6'} &
\multicolumn{1}{l|}{P571-006-MINI} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{CNC Tech} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}CORD 18AWG 5-15P - \\320-C5 6' BLK\end{tabular}} &
\multicolumn{1}{l|}{800-18-39B-BL-0006F} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Molex} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Socket Contact Tin \\24-26 AWG Crimp Stamped\end{tabular}} &
\multicolumn{1}{l|}{874210000} &
\multicolumn{1}{l|}{50} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Molex} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}9 Position Rectangular Housing \\Connector Receptacle Natural \\0.059" (1.50mm) for evaluation board\end{tabular}} &
\multicolumn{1}{l|}{87439-0900} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Molex} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}6 Position Rectangular Housing \\Connector Receptacle Natural \\0.059" (1.50mm) for evalutaion board\end{tabular}} &
\multicolumn{1}{l|}{87439-0600} &
\multicolumn{1}{l|}{3} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Molex} &
\multicolumn{1}{l|}{Fan connector} &
\multicolumn{1}{l|}{51021-0300} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Molex} &
\multicolumn{1}{l|}{Fan and optical module terminal crimp} &
\multicolumn{1}{l|}{50079-8100} &
\multicolumn{1}{l|}{20} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Molex} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}6 Position Rectangular Housing \\Connector Receptacle Natural \\0.049" (1.25mm) Optical Module LED\end{tabular}} &
\multicolumn{1}{l|}{51021-0600} &
\multicolumn{1}{l|}{3} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Foxconn} &
\multicolumn{1}{l|}{Fan} &
\multicolumn{1}{l|}{PVA030E12M} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
&
&
&
&
\\ \hline
\multicolumn{1}{|l|}{IR Ring} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{LightingWill} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}DC12V 5M/16.4ft 72W SMD5050\\ 300LEDs IR InfraRed 850nm Tri-chip White \\PCB Flexible LED Strips 60LEDs 14.4W/M\end{tabular}} &
\multicolumn{1}{l|}{B01DM9BL5I} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{DROK} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}DC Car Power Supply Voltage \\Regulator Buck Converter 8A/100W \\12A Max DC 5-40V to 1.2-36V Step \\Down Volt Convert Module\end{tabular}} &
\multicolumn{1}{l|}{90483} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{CENTROPOWER} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}10 Pairs DC Power Pigtail \\Cable 12V 5A Male Female Connectors \\DC Cable for CCTV Security Camera \\Power Adapter Connectors\end{tabular}} &
\multicolumn{1}{l|}{CT-DCCORD} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Marshall} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Potentiometer - 22K Linear,\\ Marshall, 16mm\end{tabular}} &
\multicolumn{1}{l|}{"0609722158497"} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{TDK-Lambda Americas} &
\multicolumn{1}{l|}{AC/DC CONVERTER 24V 27A 600W} &
\multicolumn{1}{l|}{285-1742-ND} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{LE PAON} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Embroidery Hoops Plastic \\Cross Stitch Hoop 7 Pcs\end{tabular}} &
\multicolumn{1}{l|}{4336933944} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Only the \\6 in hoops \\were used\end{tabular}} \\ \hline
\multicolumn{1}{|l|}{Thorlabs} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Black Hardboard, 24" x 24" \\(610 mm x 610 mm), 3/16" (4.76 mm) \\Thick, 3 Sheets\end{tabular}} &
\multicolumn{1}{l|}{TB4} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
&
&
&
&
\\ \hline
\multicolumn{1}{|l|}{Computer} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Origin PC} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}Custom Rackmount PC with \\AMD 3970X Processor\end{tabular}} &
\multicolumn{1}{l|}{L-Class} &
\multicolumn{1}{l|}{1} &
\multicolumn{1}{l|}{} \\ \hline
\multicolumn{1}{|l|}{Sabrant} &
\multicolumn{1}{l|}{\begin{tabular}[c]{@{}l@{}}2TB Rocket NVMe PCIe M.2 \\2280 Internal SSD High \\Performance Solid State Drive\end{tabular}} &
\multicolumn{1}{l|}{SB-ROCKET-2TB} &
\multicolumn{1}{l|}{4} &
\multicolumn{1}{l|}{} \\ \hline
\end{longtable}
\newpage
\paragraph*{Supplementary Video S1}
\label{vid:arena}
Video shows excerpt from recording of animals (AML470) crawling on plate and undergoing head and tail stimulation. Yellow numbered `x' indicates a tracked animal, and its track is shown in yellow. Green inset shows a single tracked individual in detail. Green dot indicates the animal's head. Its centerline is shown in green. Tracked animals' heads and tails are occasionally stimulated at various intensities, indicated by red. The dynamic circular pattern in the center of the screen is the visual time stamp projected by the projector and is used for temporal calibration.
\paragraph*{Supplementary Video S2}
\label{vid:control}
Example responses to control illumination (0 uW/mm$^2$). Strain AML470. The instrument performs all real-time processing to illuminate the head and the tail of each animal for 1 s, but no light is actually delivered to the animal. Targeted regions are shown in light blue. 20 stimulation-events are shown corresponding to the 20 randomly selected stimulation events shown in Figure \ref{fig:apresponse}e. The animal with the yellow square corresponds to the stimulation event shown in Figure \ref{fig:apresponse}a and denoted with an arrow in Figure \ref{fig:apresponse}e. The animal's centerline is shown in green. The head of the animal is denoted with a green circle. Note the field of view is centered on each animal, so the animal may be moving even though it never exits the field of view.
\paragraph*{Supplementary Video S3}
\label{vid:tail}
Example responses to tail illumination (80 uW/mm$^2$). Posterior mechanosensory neurons are activated by illuminating the tail of animals expression Chrimson int he soft touch mechanosensory neurons (strain AML470). Illumination is indicated by red circles. 20 stimulation-events are shown corresponding to the 20 randomly selected stimulation events shown in Figure \ref{fig:apresponse}f. The animal with the yellow square corresponds to the stimulation event shown in Figure \ref{fig:apresponse}b and denoted with an arrow in Figure \ref{fig:apresponse}f. The animal's centerline is shown in green. The head of the animal is denoted with a green circle. Note the field of view is centered on each animal, so the animal may be moving even though it never exits the field of view.
\paragraph*{Supplementary Video S4}
\label{vid:head}
Example responses to head illumination (80 uW/mm$^2$). Similar to \nameref{vid:tail}. 20 stimulation-events are shown corresponding to the 20 randomly selected stimulation events shown in Figure \ref{fig:apresponse}g. The animal with the yellow square corresponds to the stimulation event shown in Figure \ref{fig:apresponse}c.
\paragraph*{Supplementary Video S5}
\label{vid:headandtail}
Example responses to simultaneous head and tail illumination (80 uW/mm$^2$). Similar to \nameref{vid:tail}. 20 stimulation-events are shown corresponding to the 20 randomly selected stimulation events shown in Figure \ref{fig:apresponse}h. The animal with the yellow square corresponds to the stimulation event shown in Figure \ref{fig:apresponse}d.
\section*{Acknowledgments}
Plasmid pCFJ68 was a gift from Erik Jorgensen (University of Utah). We thank Chaogu Zheng (University of Hong Kong)
for productive discussions. This work used computing resources from the Princeton Institute for Computational Science and Engineering. Research reported in this work was supported by the Simons Foundation under award SCGB \#543003 to AML; and by the National Science Foundation, through an NSF CAREER Award to AML (IOS-1845137) and through the Center for the Physics of Biological Function (PHY-1734030); and by the National Institute of Neurological Disorders and Stroke of the National Institutes of Health under New Innovator award number DP2-NS116768 to AML. Strains from this work are being distributed by the CGC, which is funded by the NIH Office of Research Infrastructure Programs (P40 OD010440). The content is solely the responsibility of the authors and does not represent the official views of any funding agency.
\nolinenumbers
| {'timestamp': '2021-09-14T02:13:49', 'yymm': '2109', 'arxiv_id': '2109.05303', 'language': 'en', 'url': 'https://arxiv.org/abs/2109.05303'} | arxiv |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.